"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 { getPaymentHistoryColumns, PaymentHistory } from "@/components/channel-partners/PaymentHistoryTableColumn"
import { paymentHistoryData } from "@/utils/paymentHistoryData"
import { usePagination } from "@/hooks/usePagination"
import { ROWS_PER_PAGE_OPTIONS } from "@/constants/constants"

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

export function PaymentHistoryList() {
  const [searchTerm, setSearchTerm] = useState("")
  const [timeRange, setTimeRange] = useState("all")
  const [customDateRange, setCustomDateRange] = useState<DateRange>({ from: undefined, to: undefined })
  const [calendarOpen, setCalendarOpen] = useState(false)

  const filteredPayments = useMemo(() => {
    let result = [...paymentHistoryData]

    // Apply search filter
    if (searchTerm) {
      const term = searchTerm.toLowerCase()
      result = result.filter(
        (p) =>
          p.adjustedAgainst.toLowerCase().includes(term) ||
          p.notes.toLowerCase().includes(term) ||
          p.addedBy.toLowerCase().includes(term)
      )
    }

    // Apply time range filter
    if (timeRange !== "all") {
      const today = startOfToday()
      
      result = result.filter((p) => {
        const paymentDate = new Date(p.paymentDate)
        
        switch (timeRange) {
          case "today":
            return format(paymentDate, "yyyy-MM-dd") === format(today, "yyyy-MM-dd")
          case "thisWeek":
            const weekStart = startOfWeek(today, { weekStartsOn: 1 }) // Monday
            return paymentDate >= weekStart && paymentDate <= today
          case "thisMonth":
            const monthStart = startOfMonth(today)
            return paymentDate >= monthStart && paymentDate <= today
          case "lastMonth":
            const lastMonthStart = startOfMonth(subMonths(today, 1))
            const lastMonthEnd = endOfMonth(subMonths(today, 1))
            return isWithinInterval(paymentDate, { start: lastMonthStart, end: lastMonthEnd })
          case "custom":
            if (customDateRange.from && customDateRange.to) {
              return isWithinInterval(paymentDate, { 
                start: customDateRange.from, 
                end: customDateRange.to 
              })
            }
            return true
          default:
            return true
        }
      })
    }

    return result
  }, [searchTerm, timeRange, customDateRange])

  const totalRecords = filteredPayments.length

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

  const currentPayments = filteredPayments.slice(startIndex, endIndex)

  const paymentColumns = getPaymentHistoryColumns()

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

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

  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 payments..."
          />
        </div>
        
        <div className="flex items-center gap-2">
          {/* Time Range Filter */}
          <Select value={timeRange} onValueChange={handleTimeRangeChange}>
            <SelectTrigger className="w-[180px]">
              <SelectValue placeholder="Select 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={currentPayments}
        columns={paymentColumns}
        emptyStateMessage="No payment 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>
  )
}
