"use client"

import { useMemo, useState } from "react"
import { Pencil, Trash2, Plus } from "lucide-react"
import { toast } from "sonner"

import { CommonTable } from "@/components/common/Table"
import { TablePagination } from "@/components/common/TablePagination"
import { SearchInput } from "@/components/ui/custom/SearchInput"
import { Button } from "@/components/ui/button"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
  TooltipProvider,
} from "@/components/ui/tooltip"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog"

import { getPartnerColumns, Partner } from "@/components/channel-partners/PartnerTableColumn"
import { partnersData } from "@/utils/partnersData"
import { usePagination } from "@/hooks/usePagination"
import { ROWS_PER_PAGE_OPTIONS } from "@/constants/constants"
import { ActionItem } from "@/types/table"
import { AddCPContactSheet } from "@/components/channel-partners/add-cp-contact-sheet"

interface PartnerListProps {
  cpCompanyId?: string
  cpCompanyName?: string
}

export function PartnerList({ cpCompanyId, cpCompanyName }: PartnerListProps = {}) {
  const [searchTerm, setSearchTerm] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")
  const [selectedRows, setSelectedRows] = useState<string[]>([])
  const [addContactSheetOpen, setAddContactSheetOpen] = useState(false)
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
  const [bulkDeleteDialogOpen, setBulkDeleteDialogOpen] = useState(false)
  const [statusDialogOpen, setStatusDialogOpen] = useState(false)
  const [pendingAction, setPendingAction] = useState<{
    type: "activate" | "deactivate" | "delete" | "bulkDelete" | "bulkActivate" | "bulkDeactivate"
    data?: Partner
  } | null>(null)

  const filteredPartners = useMemo(() => {
    let result = [...partnersData]

    // Apply search filter
    if (searchTerm) {
      const term = searchTerm.toLowerCase()
      result = result.filter(
        (p) =>
          p.name.toLowerCase().includes(term) ||
          p.phone.toLowerCase().includes(term) ||
          p.email.toLowerCase().includes(term)
      )
    }

    // Apply status filter
    if (statusFilter !== "all") {
      result = result.filter((p) => p.status === statusFilter)
    }

    return result
  }, [searchTerm, statusFilter])

  const totalRecords = filteredPartners.length

  const {
    currentPage,
    recordsPerPage,
    totalPages,
    startIndex,
    endIndex,
    handlePreviousPage,
    handleNextPage,
    handleRecordsPerPageChange,
  } = usePagination(totalRecords, 10)

  const currentPartners = filteredPartners.slice(startIndex, endIndex)

  const handleSelectRow = (id: string) => {
    setSelectedRows((prev) =>
      prev.includes(id) ? prev.filter((rowId) => rowId !== id) : [...prev, id]
    )
  }

  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedRows(currentPartners.map((p) => p.id))
    } else {
      setSelectedRows([])
    }
  }

  const handleEdit = (partner: Partner) => {
    console.log("Edit partner:", partner)
    // TODO: Open edit sheet
  }

  const handleMakePrimary = (partner: Partner) => {
    console.log("Make primary:", partner)
    toast.success(`${partner.name} has been set as the primary contact`)
    // TODO: Update primary contact in backend
  }

  const handleToggleStatus = (partner: Partner) => {
    const action = partner.status === "Active" ? "deactivate" : "activate"
    setPendingAction({ type: action, data: partner })
    setStatusDialogOpen(true)
  }

  const handleDelete = (partner: Partner) => {
    setPendingAction({ type: "delete", data: partner })
    setDeleteDialogOpen(true)
  }

  const handleBulkDelete = () => {
    setPendingAction({ type: "bulkDelete" })
    setBulkDeleteDialogOpen(true)
  }

  const handleBulkToggleStatus = (status: "Active" | "Inactive") => {
    const action = status === "Active" ? "bulkActivate" : "bulkDeactivate"
    setPendingAction({ type: action })
    setStatusDialogOpen(true)
  }

  const confirmAction = () => {
    if (!pendingAction) return

    switch (pendingAction.type) {
      case "activate":
        toast.success(`${pendingAction.data?.name} has been marked as Active`)
        break
      case "deactivate":
        toast.success(`${pendingAction.data?.name} has been marked as Inactive`)
        break
      case "delete":
        toast.success(`${pendingAction.data?.name} has been deleted successfully`)
        break
      case "bulkActivate":
        toast.success(`${selectedRows.length} ${selectedRows.length === 1 ? 'contact' : 'contacts'} marked as Active`)
        setSelectedRows([])
        break
      case "bulkDeactivate":
        toast.success(`${selectedRows.length} ${selectedRows.length === 1 ? 'contact' : 'contacts'} marked as Inactive`)
        setSelectedRows([])
        break
      case "bulkDelete":
        toast.success(`${selectedRows.length} ${selectedRows.length === 1 ? 'contact' : 'contacts'} deleted successfully`)
        setSelectedRows([])
        break
    }

    // Close dialogs and reset
    setDeleteDialogOpen(false)
    setBulkDeleteDialogOpen(false)
    setStatusDialogOpen(false)
    setPendingAction(null)
  }

  const cancelAction = () => {
    setDeleteDialogOpen(false)
    setBulkDeleteDialogOpen(false)
    setStatusDialogOpen(false)
    setPendingAction(null)
  }

  const actions: ActionItem[] = [
    {
      label: "Edit",
      icon: <Pencil className="mr-2 h-4 w-4" />,
      onClick: (row) => handleEdit(row as Partner),
    },
    {
      label: "Make Primary",
      icon: null,
      onClick: (row) => handleMakePrimary(row as Partner),
      hidden: (row: any) => row.isPrimary === true,
    },
    {
      label: (row: any) => (row.status === "Active" ? "Make Inactive" : "Make Active"),
      icon: null,
      onClick: (row) => handleToggleStatus(row as Partner),
    },
    {
      label: "Delete",
      icon: <Trash2 className="mr-2 h-4 w-4" />,
      onClick: (row) => handleDelete(row as Partner),
      isDanger: true,
      divider: true,
    },
  ]

  const partnerColumns = getPartnerColumns({
    selectedRows,
    onSelectRow: handleSelectRow,
    onSelectAll: handleSelectAll,
  })

  const handleAddContact = () => {
    setAddContactSheetOpen(true)
  }

  const handleAddContactSubmit = (data: any) => {
    console.log("Add contact:", data)
    toast.success("Contact(s) added successfully")
    setAddContactSheetOpen(false)
  }

  return (
    <div>
      <div className="flex flex-col sm:flex-row gap-4 items-center justify-between mb-3">
        <div className="relative w-full max-w-sm">
          <SearchInput
            value={searchTerm}
            onChange={setSearchTerm}
            placeholder="Search contacts..."
          />
        </div>
        
        <div className="flex items-center gap-2">
          {/* Status Filter */}
          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger className="w-[150px]">
              <SelectValue placeholder="Status" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Status</SelectItem>
              <SelectItem value="Active">Active</SelectItem>
              <SelectItem value="Inactive">Inactive</SelectItem>
            </SelectContent>
          </Select>

          <Button onClick={handleAddContact}>
            <Plus className="h-4 w-4 mr-2" />
            Add CP Contact
          </Button>
        </div>
      </div>

      <CommonTable
        data={currentPartners}
        columns={partnerColumns}
        actions={actions}
        emptyStateMessage="No contacts found."
        className="mb-3"
      />

      {totalRecords > 0 && (
        <TablePagination
          currentPage={currentPage}
          totalPages={totalPages}
          totalRecords={totalRecords}
          recordsPerPage={recordsPerPage}
          rowsPerPageOptions={ROWS_PER_PAGE_OPTIONS}
          startIndex={startIndex + 1}
          endIndex={Math.min(endIndex, totalRecords)}
          onPreviousPage={handlePreviousPage}
          onNextPage={handleNextPage}
          onRecordsPerPageChange={handleRecordsPerPageChange}
        />
      )}

      {/* Floating Action Bar */}
      {selectedRows.length > 0 && (
        <div className="fixed left-1/2 transform -translate-x-1/2 shadow-lg rounded-lg border bg-background px-6 py-3 flex items-center gap-4 z-50 animate-in slide-in-from-bottom-5" style={{ bottom: '50px' }}>
          <span className="text-sm font-medium">
            {selectedRows.length} {selectedRows.length === 1 ? 'contact' : 'contacts'} selected
          </span>
          <div className="flex items-center gap-2 border-l pl-4">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => handleBulkToggleStatus("Active")}
              className="text-sm"
            >
              Mark Active
            </Button>

            <Button
              variant="ghost"
              size="sm"
              onClick={() => handleBulkToggleStatus("Inactive")}
              className="text-sm"
            >
              Mark Inactive
            </Button>

            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    variant="ghost"
                    size="icon"
                    onClick={handleBulkDelete}
                    className="text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-950"
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </TooltipTrigger>
                <TooltipContent>
                  <p>Delete selected</p>
                </TooltipContent>
              </Tooltip>
            </TooltipProvider>
          </div>
        </div>
      )}

      {/* Delete Single Contact Dialog */}
      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Contact?</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete <strong>{pendingAction?.data?.name}</strong>? This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={cancelAction}>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={confirmAction} className="bg-red-600 hover:bg-red-700">
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Bulk Delete Dialog */}
      <AlertDialog open={bulkDeleteDialogOpen} onOpenChange={setBulkDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Selected Contacts?</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete {selectedRows.length} {selectedRows.length === 1 ? 'contact' : 'contacts'}? This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={cancelAction}>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={confirmAction} className="bg-red-600 hover:bg-red-700">
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Status Change Dialog */}
      <AlertDialog open={statusDialogOpen} onOpenChange={setStatusDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {pendingAction?.type === "activate" && "Mark as Active?"}
              {pendingAction?.type === "deactivate" && "Mark as Inactive?"}
              {pendingAction?.type === "bulkActivate" && "Mark Selected as Active?"}
              {pendingAction?.type === "bulkDeactivate" && "Mark Selected as Inactive?"}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {(pendingAction?.type === "activate" || pendingAction?.type === "deactivate") && (
                <>
                  Are you sure you want to mark <strong>{pendingAction?.data?.name}</strong> as {pendingAction?.type === "activate" ? "Active" : "Inactive"}?
                </>
              )}
              {(pendingAction?.type === "bulkActivate" || pendingAction?.type === "bulkDeactivate") && (
                <>
                  Are you sure you want to mark {selectedRows.length} {selectedRows.length === 1 ? 'contact' : 'contacts'} as {pendingAction?.type === "bulkActivate" ? "Active" : "Inactive"}?
                </>
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={cancelAction}>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={confirmAction}>
              Confirm
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Add CP Contact Sheet */}
      <AddCPContactSheet
        open={addContactSheetOpen}
        onOpenChange={setAddContactSheetOpen}
        onSubmit={handleAddContactSubmit}
        cpCompany={cpCompanyId}
        cpCompanyName={cpCompanyName}
      />
    </div>
  )
}
