"use client"

import { useMemo, useState } from "react"
import { toast } from "sonner"
import { Download, CalendarIcon } from "lucide-react"
import { format } 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 { getSaleColumns, Sale } from "@/components/channel-partners/SaleTableColumn"
import { salesData } from "@/utils/salesData"
import { usePagination } from "@/hooks/usePagination"
import { ROWS_PER_PAGE_OPTIONS } from "@/constants/constants"

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

export function SaleList() {
  const [searchTerm, setSearchTerm] = useState("")
  const [projectFilter, setProjectFilter] = useState("all")
  const [cpContactFilter, setCpContactFilter] = useState("all")
  const [soldByFilter, setSoldByFilter] = useState("all")
  const [timeRange, setTimeRange] = useState("all")
  const [customDateRange, setCustomDateRange] = useState<DateRange>({ from: undefined, to: undefined })
  const [calendarOpen, setCalendarOpen] = useState(false)

  // Get unique values for filters
  const uniqueProjects = useMemo(() => {
    return [...new Set(salesData.map(s => s.projectName))]
  }, [])

  const uniqueCpContacts = useMemo(() => {
    return [...new Set(salesData.map(s => s.cpContactName))]
  }, [])

  const uniqueSoldBy = useMemo(() => {
    return [...new Set(salesData.map(s => s.soldBy))]
  }, [])

  const filteredSales = useMemo(() => {
    let result = [...salesData]

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

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

    // Apply CP Contact filter
    if (cpContactFilter !== "all") {
      result = result.filter((s) => s.cpContactName === cpContactFilter)
    }

    // Apply Sold By filter
    if (soldByFilter !== "all") {
      result = result.filter((s) => s.soldBy === soldByFilter)
    }

    // Apply time range filter
    if (timeRange !== "all" && timeRange !== "custom") {
      const now = new Date()
      result = result.filter((s) => {
        const bookingDate = new Date(s.bookingDate)
        
        switch (timeRange) {
          case "today":
            return bookingDate.toDateString() === now.toDateString()
          case "thisWeek":
            const weekStart = new Date(now.setDate(now.getDate() - now.getDay()))
            return bookingDate >= weekStart
          case "thisMonth":
            return bookingDate.getMonth() === now.getMonth() && 
                   bookingDate.getFullYear() === now.getFullYear()
          case "lastMonth":
            const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1)
            return bookingDate.getMonth() === lastMonth.getMonth() &&
                   bookingDate.getFullYear() === lastMonth.getFullYear()
          default:
            return true
        }
      })
    }

    // Apply custom date range filter
    if (timeRange === "custom" && customDateRange.from && customDateRange.to) {
      result = result.filter((s) => {
        const bookingDate = new Date(s.bookingDate)
        return bookingDate >= customDateRange.from! && bookingDate <= customDateRange.to!
      })
    }

    return result
  }, [searchTerm, projectFilter, cpContactFilter, soldByFilter, timeRange, customDateRange])

  const totalRecords = filteredSales.length

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

  const currentSales = filteredSales.slice(startIndex, endIndex)

  const saleColumns = getSaleColumns()

  const handleExport = () => {
    toast.success(`Exporting ${filteredSales.length} sales records to Excel`)
    console.log("Export data:", filteredSales)
  }

  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 sales..."
          />
        </div>
        
        <div className="flex items-center gap-2 flex-wrap">
          {/* 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" />
            </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>
          )}

          {/* CP Contact Filter */}
          <Select value={cpContactFilter} onValueChange={setCpContactFilter}>
            <SelectTrigger className="w-[150px]">
              <SelectValue placeholder="CP Contact" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Contacts</SelectItem>
              {uniqueCpContacts.map((contact) => (
                <SelectItem key={contact} value={contact}>
                  {contact}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>

          {/* Sold By Filter */}
          <Select value={soldByFilter} onValueChange={setSoldByFilter}>
            <SelectTrigger className="w-[150px]">
              <SelectValue placeholder="Sold By" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Sales Reps</SelectItem>
              {uniqueSoldBy.map((rep) => (
                <SelectItem key={rep} value={rep}>
                  {rep}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>

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

      <CommonTable
        data={currentSales}
        columns={saleColumns}
        emptyStateMessage="No sales 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>
  )
}
