"use client"

import { useMemo, useState } from "react"
import { useRouter } from "next/navigation"
import { Pencil, Trash2 } 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 { getChannelPartnerColumns, ChannelPartner } from "@/components/channel-partners/ChannelPartnerTableColumn"
import { channelPartnersData } from "@/utils/channelPartnersData"
import { usePagination } from "@/hooks/usePagination"
import { ROWS_PER_PAGE_OPTIONS } from "@/constants/constants"
import { ActionItem } from "@/types/table"
import { EditCPFirmSheet } from "@/components/channel-partners/edit-cp-firm-sheet"

export function ChannelPartnerList() {
  const router = useRouter()
  const [searchTerm, setSearchTerm] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")
  const [selectedRows, setSelectedRows] = useState<string[]>([])
  const [hoveredRow, setHoveredRow] = useState<string | null>(null)
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
  const [bulkDeleteDialogOpen, setBulkDeleteDialogOpen] = useState(false)
  const [statusDialogOpen, setStatusDialogOpen] = useState(false)
  const [editSheetOpen, setEditSheetOpen] = useState(false)
  const [editingPartner, setEditingPartner] = useState<ChannelPartner | null>(null)
  const [pendingAction, setPendingAction] = useState<{
    type: "activate" | "deactivate" | "delete" | "bulkDelete" | "bulkActivate" | "bulkDeactivate"
    data?: ChannelPartner
  } | null>(null)

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

    // Apply search filter
    if (searchTerm) {
      const term = searchTerm.toLowerCase()
      result = result.filter(
        (cp) =>
          cp.firmName.toLowerCase().includes(term) ||
          cp.primaryContactName.toLowerCase().includes(term) ||
          cp.city.toLowerCase().includes(term)
      )
    }

    // Apply status filter
    if (statusFilter !== "all") {
      result = result.filter((cp) => cp.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((cp) => cp.id))
    } else {
      setSelectedRows([])
    }
  }

  const handleEdit = (partner: ChannelPartner) => {
    setEditingPartner(partner)
    setEditSheetOpen(true)
  }

  const handleEditSubmit = (data: any) => {
    console.log("Update partner:", data)
    toast.success(`${data.companyName} has been updated successfully`)
    setEditSheetOpen(false)
    setEditingPartner(null)
  }

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

  const handleDelete = (partner: ChannelPartner) => {
    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?.firmName} has been marked as Active`)
        break
      case "deactivate":
        toast.success(`${pendingAction.data?.firmName} has been marked as Inactive`)
        break
      case "delete":
        toast.success(`${pendingAction.data?.firmName} has been deleted successfully`)
        break
      case "bulkActivate":
        toast.success(`${selectedRows.length} ${selectedRows.length === 1 ? 'partner' : 'partners'} marked as Active`)
        setSelectedRows([])
        break
      case "bulkDeactivate":
        toast.success(`${selectedRows.length} ${selectedRows.length === 1 ? 'partner' : 'partners'} marked as Inactive`)
        setSelectedRows([])
        break
      case "bulkDelete":
        toast.success(`${selectedRows.length} ${selectedRows.length === 1 ? 'partner' : 'partners'} 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 ChannelPartner),
    },
    {
      label: (row: any) => (row.status === "Active" ? "Make Inactive" : "Make Active"),
      icon: null,
      onClick: (row) => handleToggleStatus(row as ChannelPartner),
    },
    {
      label: "Delete",
      icon: <Trash2 className="mr-2 h-4 w-4" />,
      onClick: (row) => handleDelete(row as ChannelPartner),
      isDanger: true,
      divider: true,
    },
  ]

  const handleRowClick = (partner: ChannelPartner) => {
    router.push(`/channel-partners/${partner.id}`)
  }

  const channelPartnerColumns = getChannelPartnerColumns({
    selectedRows,
    onSelectRow: handleSelectRow,
    onSelectAll: handleSelectAll,
    hoveredRow,
  })

  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 channel partners..."
          />
        </div>
        
        {/* 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>
      </div>

      <CommonTable
        data={currentPartners}
        columns={channelPartnerColumns}
        actions={actions}
        emptyStateMessage="No channel partners found."
        onRowClick={handleRowClick}
        onRowHover={setHoveredRow}
        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 ? 'partner' : 'partners'} selected
          </span>
          <div className="flex items-center gap-2 border-l pl-4">
            {/* Mark Active button */}
            <Button
              variant="ghost"
              size="sm"
              onClick={() => handleBulkToggleStatus("Active")}
              className="text-sm"
            >
              Mark Active
            </Button>

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

            {/* Delete 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 Partner Dialog */}
      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Channel Partner?</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete <strong>{pendingAction?.data?.firmName}</strong>? This action cannot be undone and will permanently remove all associated data.
            </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 Partners?</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete {selectedRows.length} {selectedRows.length === 1 ? 'partner' : 'partners'}? This action cannot be undone and will permanently remove all associated data.
            </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?.firmName}</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 ? 'partner' : 'partners'} as {pendingAction?.type === "bulkActivate" ? "Active" : "Inactive"}?
                </>
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={cancelAction}>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={confirmAction}>
              Confirm
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Edit CP Firm Sheet */}
      <EditCPFirmSheet
        open={editSheetOpen}
        onOpenChange={setEditSheetOpen}
        onSubmit={handleEditSubmit}
        initialData={editingPartner ? {
          id: editingPartner.id,
          companyName: editingPartner.firmName,
          website: "",
          address: editingPartner.address,
          city: editingPartner.city,
          state: "",
          country: "India",
          baseCommissionRate: "",
          notes: "",
        } : null}
      />
    </div>
  )
}
