"use client"

import { useMemo, useState } from "react"
import { Download, CalendarIcon } from "lucide-react"
import { format, startOfToday, startOfWeek, startOfMonth, subMonths, endOfMonth, isWithinInterval } from "date-fns"

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 {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover"
import { Calendar } from "@/components/ui/calendar"
import { cn } from "@/lib/utils"
import { toast } from "sonner"

import { getCommissionLedgerColumns, CommissionLedger } from "@/components/channel-partners/CommissionLedgerTableColumn"
import { commissionLedgerData } from "@/utils/commissionLedgerData"
import { usePagination } from "@/hooks/usePagination"
import { ROWS_PER_PAGE_OPTIONS } from "@/constants/constants"

type DateRange = {
  from: Date | undefined
  to: Date | undefined
}

interface CommissionLedgerListProps {
  totalCommissionGenerated: string
  totalCommissionPaid: string
  totalCommissionPending: string
  lastPaymentDate: string
}

export function CommissionLedgerList({
  totalCommissionGenerated,
  totalCommissionPaid,
  totalCommissionPending,
  lastPaymentDate,
}: CommissionLedgerListProps) {
  const [searchTerm, setSearchTerm] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")
  const [projectFilter, setProjectFilter] = useState("all")
  const [timeRange, setTimeRange] = useState("all")
  const [customDateRange, setCustomDateRange] = useState<DateRange>({ from: undefined, to: undefined })
  const [calendarOpen, setCalendarOpen] = useState(false)

  // Get unique projects for filter
  const uniqueProjects = useMemo(() => {
    const projects = [...new Set(commissionLedgerData.map(l => l.projectName))]
    return projects
  }, [])

  const filteredLedger = useMemo(() => {
    let result = [...commissionLedgerData]

    // Apply search filter
    if (searchTerm) {
      const term = searchTerm.toLowerCase()
      result = result.filter(
        (l) =>
          l.bookingId.toLowerCase().includes(term) ||
          l.projectName.toLowerCase().includes(term) ||
          l.unitNumber.toLowerCase().includes(term) ||
          l.cpContactName.toLowerCase().includes(term)
      )
    }

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

    // Apply project filter
    if (projectFilter !== "all") {
      result = result.filter((l) => l.projectName === projectFilter)
    }

    // Apply time range filter (based on booking date - you may want to add a bookingDate field)
    // For now, we'll skip time filtering as commissionLedgerData doesn't have booking dates
    // TODO: Add bookingDate field to CommissionLedger interface if time filtering is needed

    return result
  }, [searchTerm, statusFilter, projectFilter])

  const totalRecords = filteredLedger.length

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

  const currentLedger = filteredLedger.slice(startIndex, endIndex)

  const ledgerColumns = getCommissionLedgerColumns()

  const handleExport = () => {
    // TODO: Implement actual export logic
    toast.success(`Exporting ${filteredLedger.length} commission records to Excel`)
    console.log("Export data:", filteredLedger)
  }

  const handleTimeRangeChange = (value: string) => {
    setTimeRange(value)
    if (value !== "custom") {
      setCustomDateRange({ from: undefined, to: undefined })
    }
  }

  return (
    <div className="space-y-6">
      {/* Summary Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="border rounded-lg p-4">
          <div className="text-sm text-muted-foreground">Total Commission Generated</div>
          <div className="text-2xl font-bold mt-1">{totalCommissionGenerated}</div>
        </div>
        <div className="border rounded-lg p-4">
          <div className="text-sm text-muted-foreground">Total Commission Paid</div>
          <div className="text-2xl font-bold mt-1">{totalCommissionPaid}</div>
        </div>
        <div className="border rounded-lg p-4">
          <div className="text-sm text-muted-foreground">Total Commission Pending</div>
          <div className="text-2xl font-bold mt-1">{totalCommissionPending}</div>
        </div>
        <div className="border rounded-lg p-4">
          <div className="text-sm text-muted-foreground">Last Payment Date</div>
          <div className="text-2xl font-bold mt-1">{lastPaymentDate}</div>
        </div>
      </div>

      {/* Datatable */}
      <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 ledger..."
            />
          </div>
          
          <div className="flex items-center gap-2 flex-wrap">
            {/* Status Filter */}
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-[150px]">
                <SelectValue placeholder="Status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Status</SelectItem>
                <SelectItem value="Pending">Pending</SelectItem>
                <SelectItem value="Partially Paid">Partially Paid</SelectItem>
                <SelectItem value="Paid">Paid</SelectItem>
              </SelectContent>
            </Select>

            {/* Project Filter */}
            <Select value={projectFilter} onValueChange={setProjectFilter}>
              <SelectTrigger className="w-[180px]">
                <SelectValue placeholder="Project" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Projects</SelectItem>
                {uniqueProjects.map((project) => (
                  <SelectItem key={project} value={project}>
                    {project}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            {/* Time Range Filter */}
            <Select value={timeRange} onValueChange={handleTimeRangeChange}>
              <SelectTrigger className="w-[150px]">
                <SelectValue placeholder="Time Range" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Time</SelectItem>
                <SelectItem value="today">Today</SelectItem>
                <SelectItem value="thisWeek">This Week</SelectItem>
                <SelectItem value="thisMonth">This Month</SelectItem>
                <SelectItem value="lastMonth">Last Month</SelectItem>
                <SelectItem value="custom">Custom Range</SelectItem>
              </SelectContent>
            </Select>

            {/* Custom Date Range Picker */}
            {timeRange === "custom" && (
              <Popover open={calendarOpen} onOpenChange={setCalendarOpen}>
                <PopoverTrigger asChild>
                  <Button
                    variant="outline"
                    className={cn(
                      "justify-start text-left font-normal",
                      !customDateRange.from && !customDateRange.to && "text-muted-foreground"
                    )}
                  >
                    <CalendarIcon className="mr-2 h-4 w-4" />
                    {customDateRange.from && customDateRange.to
                      ? `${format(customDateRange.from, "dd MMM")} - ${format(customDateRange.to, "dd MMM")}`
                      : "Pick dates"}
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-auto p-0" align="end">
                  <Calendar
                    mode="range"
                    selected={customDateRange}
                    onSelect={(range: any) => {
                      setCustomDateRange(range || { from: undefined, to: undefined })
                      if (range?.from && range?.to) {
                        setCalendarOpen(false)
                      }
                    }}
                    numberOfMonths={2}
                  />
                </PopoverContent>
              </Popover>
            )}

            {/* Export Button */}
            <Button onClick={handleExport} variant="outline" className="gap-2">
              <Download className="h-4 w-4" />
              Export
            </Button>
          </div>
        </div>

        <CommonTable
          data={currentLedger}
          columns={ledgerColumns}
          emptyStateMessage="No commission records 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}
          />
        )}
      </div>
    </div>
  )
}
