"use client"

import AppLayout from "@/Layouts/AppLayout"
import { Button } from "@/Components/UI/Button"
import { Badge } from "@/Components/UI/Badge"
import { Tabs, TabsList, TabsTrigger } from "@/Components/UI/Tabs"
import { Input } from "@/Components/UI/Input"
import { Checkbox } from "@/Components/UI/Checkbox"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/Components/UI/DropdownMenu"
import DataTable from "@/Components/DataTable"
import EmptyPage from "@/Components/EmptyPage"
import DeleteModal from "@/Components/DeleteModal"
import CampaignCard from "@/Components/Campaign/CampaignCard"
import { route } from "ziggy-js"
import { Plus, UserX, Edit, Trash2, Grid3X3, List, Search, Filter, ChartLine, Rocket } from "lucide-react"
import { Link, router } from "@inertiajs/react"
import { useState , useEffect} from "react"
import { useDeleteHandler } from "@/hooks/useDeleteHandler"
import { useBulkHandler } from "@/hooks/useBulkHandler"
import Pagination from "@/Components/UI/Pagination"
import PerformanceSummary from "@/Components/Analytics/PerformanceSummary"
import PostCard from "@/Components/Analytics/PostCard"
import EngagementChart from "@/Components/Analytics/EngagementChart"
import AccountPerformanceChart from "@/Components/Analytics/AccountPerformanceChart"
import AllContent from "@/Components/Analytics/AllContent"
import AccountAvatars from "@/Components/Platform/AccountAvatars"


export default function CampaignIndex({ campaigns = {}, AnalyticalData }) {
  const [campaignList, setCampaignList] = useState(campaigns.data || [])
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)
  const [campaignToDelete, setCampaignToDelete] = useState(null)
  const [searchQuery, setSearchQuery] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")
  const [activeTab, setActiveTab] = useState("campaigns")
  const [viewMode, setViewMode] = useState("list")
  const [activePlatform, setActivePlatform] = useState("facebook")
  const [selectedCampaign, setSelectedCampaign] = useState(null)

  const breadcrumbs = [{ label: "Home", href: route("user.home") }, { label: "Campaign" }]

  const filterOptions = [
    { label: "Draft", value: "draft" },
    { label: "Sent", value: "sent" },
    { label: "Failed", value: "failed" },
  ]

  useEffect(() => {
    if (campaigns.data) {
      setCampaignList(campaigns.data)
    }
  }, [campaigns])

  


  const handleTab = (tab) => {
    setActiveTab(tab)

    if (tab === "campaigns") {
      router.get(
        route("user.campaign.index"),
        {
          search: searchQuery,
          status: statusFilter !== "all" ? statusFilter : undefined,
        },
        { preserveState: true, replace: true },
      )
    } else if (tab === "analytics") {
      router.get(route("user.campaign.index"), {}, { preserveState: true, replace: true })
    }
  }

  const handleViewMode = (mode) => {
    setViewMode(mode)
  }

  const { handleDelete, isDeleting } = useDeleteHandler("user.campaign.delete", (deletedId) => {
    setCampaignList((prev) => prev.filter((campaign) => campaign.id !== deletedId))
    setIsDeleteModalOpen(false)
    setCampaignToDelete(null)
  })

  const { handleBulkAction, isBulkProcessing } = useBulkHandler("user.campaign.bulk", (action, ids, statusEnum) => {
    setCampaignList((prev) => {
      switch (action) {
        case "active":
          return prev.map((campaign) => (ids.includes(campaign.id) ? { ...campaign, status: "sent" } : campaign))
        case "inactive":
          return prev.map((campaign) => (ids.includes(campaign.id) ? { ...campaign, status: "draft" } : campaign))
        case "delete":
          return prev.filter((campaign) => !ids.includes(campaign.id))
        default:
          return prev
      }
    })
  })

  const handleSearch = (value) => {
    setSearchQuery(value)
    router.get(
      route("user.campaign.index"),
      {
        search: value,
        status: statusFilter !== "all" ? statusFilter : undefined,
        page: 1,
      },
      { preserveState: true, replace: true },
    )
  }

  const handleFilter = (value) => {
    setStatusFilter(value)
    router.get(
      route("user.campaign.index"),
      {
        search: searchQuery,
        status: value !== "all" ? value : undefined,
        page: 1,
      },
      { preserveState: true, replace: true },
    )
  }

  const handleDeleteClick = (campaign) => {
    setCampaignToDelete(campaign)
    setIsDeleteModalOpen(true)
  }

  const calculateProgress = (startDate, endDate) => {
    if (!startDate || !endDate) return 0

    const now = new Date()
    const start = new Date(startDate)
    const end = new Date(endDate)

    if (now < start) return 0
    if (now > end) return 100

    const totalDuration = end.getTime() - start.getTime()
    const elapsed = now.getTime() - start.getTime()

    return Math.round((elapsed / totalDuration) * 100)
  }

  const columns = [
    {
      key: "name",
      label: "Campaign Name",
      render: (campaign) => (
        <div className="space-y-2">
          <div className="font-medium text-gray-900 dark:text-white">{campaign.name}</div>
          <div className="flex items-center space-x-3">
            <div className="flex-1 bg-gray-200 dark:bg-gray-700 rounded-full h-2 overflow-hidden">
              <div
                className="h-full bg-gradient-to-r from-blue-500 to-teal-400 rounded-full transition-all duration-300"
                style={{ width: `${calculateProgress(campaign.start_date, campaign.end_date)}%` }}
              />
            </div>
            <span className="text-xs text-gray-500 dark:text-gray-400 min-w-[35px]">
              {calculateProgress(campaign.start_date, campaign.end_date)}%
            </span>
          </div>
        </div>
      ),
    },
    {
      key: "status",
      label: "Status",
      render: (campaign) => (
        <Badge
          variant={campaign.status === "sent" ? "default" : campaign.status === "failed" ? "destructive" : "secondary"}
          className={
            campaign.status === "sent"
              ? "bg-green-100 text-green-800 hover:bg-green-100"
              : campaign.status === "failed"
                ? "bg-red-100 text-red-800 hover:bg-red-100"
                : "bg-gray-100 text-gray-800 hover:bg-gray-100"
          }
        >
          {campaign.status === "sent" ? "Sent" : campaign.status === "failed" ? "Failed" : "Draft"}
        </Badge>
      ),
    },
    {
      key: "created_at",
      label: "Created Date",
      render: (campaign) => (
        <span className="text-gray-600 dark:text-gray-300">
          {new Date(campaign.created_at).toLocaleDateString("en-US", {
            year: "numeric",
            month: "2-digit",
            day: "2-digit",
            hour: "2-digit",
            minute: "2-digit",
            hour12: true,
          })}
        </span>
      ),
    },
    {
      key: "start_date",
      label: "Start Date",
      render: (campaign) => (
        <span className="text-gray-600 dark:text-gray-300">
          {campaign.start_date
            ? new Date(campaign.start_date).toLocaleDateString("en-US", {
              year: "numeric",
              month: "2-digit",
              day: "2-digit",
              hour: "2-digit",
              minute: "2-digit",
              hour12: true,
            })
            : "-"}
        </span>
      ),
    },
    {
      key: "accounts",
      label: "Platform",
      render: (campaign) => (
        <div className="flex -space-x-2">
          {campaign.accounts && campaign.accounts.length > 0 ? (
            <AccountAvatars accounts={campaign.accounts} size="sm" />
          ) : (
            <span className="text-gray-400 text-sm">No accounts</span>
          )}
        </div>
      ),
    },
  ]

  const actionMenuItems = [
    {
      key: "edit",
      label: "Edit",
      icon: Edit,
    },
    {
      key: "view_analytics",
      label: "View Analytics",
      icon: ChartLine,
    },
    {
      key: "delete",
      label: "Delete",
      icon: Trash2,
    },
  ]

  const handleRowAction = (action, campaign) => {

    switch (action) {
      case "edit":
        router.get(route("user.campaign.edit", campaign.id));
        break;

      case "delete":
        handleDeleteClick(campaign);
        break;

      case "view_analytics":
        router.get(route("user.campaign.index"), { campaign_id: campaign.id }, { preserveState: true })
        setSelectedCampaign(campaign);
        setActiveTab("analytics");
        break;

      default:
        console.warn(`Unhandled action: ${action}`);
        break;
    }
  };


  const handleBulkDelete = async (selectedIds) => {
    await handleBulkAction("delete", selectedIds)
  }

  const handleBulkActive = (selectedIds) => {
    handleBulkAction("active", selectedIds)
  }

  const handleBulkInactive = (selectedIds) => {
    handleBulkAction("inactive", selectedIds)
  }

  const renderCampaignContent = () => {
    if (!campaignList || campaignList.length === 0) {
      return (
        <EmptyPage
          heading="No Campaigns Created"
          subheading="Don't forget to share your social media accounts to connect with others online!"
          buttonTitle="Create Campaign"
          buttonUrl={route("user.campaign.create")}
          icon={UserX}
        />
      )
    }

    if (viewMode === "list") {
      return (
        <DataTable
          data={campaignList}
          columns={columns}
          searchFields={["name", "status"]}
          searchPlaceholder="Search campaigns..."
          filterOptions={filterOptions}
          actionMenuItems={actionMenuItems}
          onRowAction={handleRowAction}
          onBulkDelete={handleBulkDelete}
          onBulkActive={handleBulkActive}
          onBulkInactive={handleBulkInactive}
          onSearch={handleSearch}
          onFilterChange={handleFilter}
          paginationData={{
            links: campaigns.links,
            currentPage: campaigns.current_page,
            lastPage: campaigns.last_page,
          }}
        />
      )
    }

    return (
      <>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {campaignList.map((campaign) => (
            <CampaignCard
              key={campaign.id}
              campaign={campaign}
              onRowAction={handleRowAction}
              calculateProgress={calculateProgress}
            />
          ))}


        </div>

        {/* Pagination */}
        {campaigns && (
          <Pagination
            links={campaigns.links}
            currentPage={campaigns.currentPage}
            lastPage={campaigns.lastPage}
            preserveState={true}
            preserveScroll={true}
            className="mt-4 dark:text-neutral-200"
          />
        )}
      </>

    )
  }

  return (
    <AppLayout breadcrumbs={breadcrumbs}>
      <div className="flex-1 p-4 sm:p-6 overflow-hidden max-w-full">
        <div className="mb-6">
          <div className="flex items-center justify-between">
            <div>
              <div className="flex items-center gap-3 mb-2">
                <div>
                  <Rocket className="h-6 w-6 text-primary" />
                </div>
                <h1 className="text-xl sm:text-2xl dark:text-gray-200 font-bold">
                  Campaigns
                </h1>
              </div>
              <p className="text-gray-500 dark:text-gray-200">
                Create and manage your marketing campaigns across social media platforms
              </p>
            </div>
            <div>
              <Link href={route("user.campaign.create")}>
                <Button className="bg-gradient-to-r from-primary to-secondary hover:from-secondary hover:to-primary text-white shadow-sm">
                  <Plus className="w-4 h-4 mr-2" />
                  Create Campaign
                </Button>
              </Link>
            </div>
          </div>
        </div>

        <div className="flex justify-between items-center mb-6">
          <div className="flex gap-1">
            <Tabs value={activeTab} onValueChange={handleTab} className="space-y-6">
              <TabsList className="inline-flex bg-white dark:bg-zinc-900 rounded-lg p-1 shadow-sm gap-1">
                <TabsTrigger
                  value="campaigns"
                  className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-primary data-[state=active]:to-secondary data-[state=active]:text-white data-[state=active]:shadow-sm rounded-md px-4 py-2 text-sm font-medium transition-colors"
                >
                  Campaign List
                </TabsTrigger>
                <TabsTrigger
                  value="analytics"
                  className="data-[state=active]:bg-gradient-to-r data-[state=active]:from-primary data-[state=active]:to-secondary data-[state=active]:text-white data-[state=active]:shadow-sm rounded-md px-4 py-2 text-sm font-medium transition-colors"
                >
                  Analytics
                </TabsTrigger>
              </TabsList>
            </Tabs>
          </div>

          <div className="flex items-center gap-4">
            {activeTab === "campaigns" && viewMode === "grid" && (
              <>
                <div className="relative max-w-xs">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                  <Input
                    placeholder="Search"
                    value={searchQuery}
                    onChange={(e) => handleSearch(e.target.value)}
                    className="pl-10 w-64 bg-white dark:bg-zinc-900 border-gray-200 dark:border-gray-600"
                  />
                </div>
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button
                      variant="outline"
                      size="sm"
                      className="flex items-center gap-2 bg-white dark:bg-zinc-900 h-9 dark:text-neutral-200 dark:border-gray-600 border-gray-200"
                    >
                      <Filter className="w-4 h-4" />
                      Filter
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent className="rounded-lg bg-white dark:bg-zinc-800 text-gray-900 dark:text-neutral-200 border border-gray-200 dark:border-gray-600">
                    <DropdownMenuItem
                      onClick={() => handleFilter("all")}
                      className="hover:bg-gray-100 dark:hover:bg-zinc-700 cursor-pointer rounded-md"
                    >
                      <Checkbox
                        checked={statusFilter === "all"}
                        className="mr-2 data-[state=checked]:bg-gradient-to-r data-[state=checked]:from-primary data-[state=checked]:to-cyan-500 data-[state=checked]:border-transparent"
                      />
                      All
                    </DropdownMenuItem>
                    {filterOptions.map((option) => (
                      <DropdownMenuItem
                        key={option.value}
                        onClick={() => handleFilter(option.value)}
                        className="hover:bg-gray-100 dark:hover:bg-zinc-700 cursor-pointer rounded-md"
                      >
                        <Checkbox
                          checked={statusFilter === option.value}
                          className="mr-2 data-[state=checked]:bg-gradient-to-r data-[state=checked]:from-primary data-[state=checked]:to-cyan-500 data-[state=checked]:border-transparent"
                        />
                        {option.label}
                      </DropdownMenuItem>
                    ))}
                  </DropdownMenuContent>
                </DropdownMenu>
              </>
            )}

            {activeTab === "campaigns" && (
              <div className="flex items-center space-x-2">
                <button
                  onClick={() => handleViewMode("grid")}
                  className={`p-2 rounded-lg transition-colors ${viewMode === "grid"
                    ? "bg-gradient-to-r from-primary to-secondary hover:from-sky-600 hover:to-cyan-600 text-white dark:text-white"
                    : "text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                    }`}
                  title="Grid View"
                >
                  <Grid3X3 className="w-5 h-5" />
                </button>
                <button
                  onClick={() => handleViewMode("list")}
                  className={`p-2 rounded-lg transition-colors ${viewMode === "list"
                    ? "bg-gradient-to-r from-primary to-secondary hover:from-sky-600 hover:to-cyan-600 text-white dark:text-white"
                    : "text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                    }`}
                  title="List View"
                >
                  <List className="w-5 h-5" />
                </button>
              </div>
            )}
          </div>
        </div>

        {activeTab === "campaigns" ? (
          renderCampaignContent()
        ) : (
          <div className="max-w-full">
            <div className="space-y-6 w-full max-w-none">
              <PerformanceSummary
                platform={activePlatform}
                data={AnalyticalData.postSummary}
                metrics={AnalyticalData.postSummary.metrics}
              />
              <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 sm:gap-6 w-full">
                <div className="lg:col-span-2 min-w-0 w-full">
                  <EngagementChart platform={activePlatform} data={AnalyticalData.engagementAnalytics} />
                </div>
                <div className="lg:col-span-1 min-w-0 w-full">
                  <AccountPerformanceChart
                    platform={activePlatform}
                    data={AnalyticalData.accountPerformance}
                    accounts={AnalyticalData.accountPerformance.accounts}
                  />
                </div>
              </div>
              <PostCard platform={activePlatform} data={AnalyticalData.topPosts} />

              <AllContent platform={activePlatform} data={AnalyticalData.allContents} />
            </div>
          </div>
        )}

        <DeleteModal
          isOpen={isDeleteModalOpen}
          onClose={() => setIsDeleteModalOpen(false)}
          title="Delete this Campaign?"
          description="Are you really sure you want to delete this campaign?"
          onConfirm={() => handleDelete(campaignToDelete?.id)}
          isDeleting={isDeleting}
        />
      </div>
    </AppLayout>
  )
}
