"use client"

import { Button } from "@/Components/UI/Button"
import { Input } from "@/Components/UI/Input"
import { Card } from "@/Components/UI/Card"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/Components/UI/DropdownMenu"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/Components/UI/Table"
import { Checkbox } from "@/Components/UI/Checkbox"
import DeleteModal from "@/Components/DeleteModal"
import { Search, Filter, Trash2, Minus, Settings2, Database } from "lucide-react"
import { useState } from "react"
import Pagination from "@/Components/UI/Pagination"


export default function DataTable({
  data = [],
  columns = [],
  searchFields = [],
  searchPlaceholder = "Search",
  filterOptions = [],
  actionMenuItems = [],
  className = "",
  paginationData,
  propName,
  statusEnum,
  onBulkActive,
  onBulkInactive,
  onBulkDelete,
  onRowAction,
  onSearch,
  onFilterChange,
  actionButton = null,
}) {
  const [selectedItems, setSelectedItems] = useState([])
  const [isBulkDeleteModalOpen, setIsBulkDeleteModalOpen] = useState(false)
  const [searchQuery, setSearchQuery] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")
  const [isDeleting, setIsDeleting] = useState(false)

  const handleSearchInput = (value) => {
    setSearchQuery(value);
    if (onSearch) onSearch(value);
  };

  const handleFilterSelect = (value) => {
    setStatusFilter(value);
    if (onFilterChange) onFilterChange(value);
  };

  const handleSelectAll = () => {
    if (selectedItems.length === data.length) {
      setSelectedItems([]);
    } else {
      setSelectedItems(data.map((item) => item.id));
    }
  };

  const handleDeselectAll = () => {
    setSelectedItems([])
  }

  const handleSelectItem = (itemId) => {
    setSelectedItems((prev) => (prev.includes(itemId) ? prev.filter((id) => id !== itemId) : [...prev, itemId]))
  }

  const handleBulkActivate = () => {
    if (onBulkActive) {
      onBulkActive(selectedItems)
    }
    setSelectedItems([])
  }

  const handleBulkDeactivate = () => {
    if (onBulkInactive) {
      onBulkInactive(selectedItems)
    }
    setSelectedItems([])
  }

  const handleBulkDeleteClick = () => {
    setIsBulkDeleteModalOpen(true)
  }

  const handleBulkDeleteConfirm = async () => {
    setIsDeleting(true)
    if (onBulkDelete) {
      await onBulkDelete(selectedItems)
    }
    setSelectedItems([])
    setIsBulkDeleteModalOpen(false)
    setIsDeleting(false)
  }

  const handleRowActionClick = (action, item) => {
    if (onRowAction) {
      onRowAction(action, item)
    }
  }

  const isAllSelected = selectedItems.length === data.length && data.length > 0;
  const isPartiallySelected = selectedItems.length > 0 && selectedItems.length < data.length;


  return (
    <Card className={`bg-white dark:bg-zinc-900 rounded-xl border border-gray-200 dark:border-zinc-800 lg:p-6 p-4 ${className}`}>
      {/* Search and Filter */}
      <div className="flex items-center justify-between flex-wrap lg:flex-nowrap lg:gap-8 gap-4 mb-6">
        <div className="flex w-full flex-wrap items-center gap-3">
          <div className="relative flex-1 w-full">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 dark:text-gray-400 w-4 h-4" />
            <Input
              placeholder={searchPlaceholder}
              className="pl-10 h-9 bg-white dark:bg-zinc-800 text-gray-900 dark:text-neutral-200 border border-gray-300 dark:border-gray-600"
              value={searchQuery}
              onChange={(e) => handleSearchInput(e.target.value)}
            />
          </div>

          {/* Filter Dropdown */}
          {filterOptions.length > 0 && (
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" size="sm" className="flex items-center gap-2 bg-transparent h-9 dark:text-neutral-200 dark:border-gray-600">
                  <Filter className="w-4 h-4" />
                  Filter
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent className="rounded-lg bg-white dark:bg-zinc-800 text-gray-900 dark:text-neutral-200 border border-gray-200 dark:border-gray-600">
                <DropdownMenuItem
                  onClick={() => handleFilterSelect("all")}
                  className="hover:bg-gray-100 dark:hover:bg-zinc-700 cursor-pointer rounded-md"
                >
                  <Checkbox
                    checked={statusFilter === "all"}
                    className="mr-2 data-[state=checked]:bg-gradient-to-r data-[state=checked]:from-primary data-[state=checked]:to-cyan-500 data-[state=checked]:border-transparent"
                  />
                  All
                </DropdownMenuItem>
                {filterOptions.map((option) => (
                  <DropdownMenuItem
                    key={option.value}
                    onClick={() => handleFilterSelect(option.value)}
                    className="hover:bg-gray-100 dark:hover:bg-zinc-700 cursor-pointer rounded-md"
                  >
                    <Checkbox
                      checked={statusFilter === option.value}
                      className="mr-2 data-[state=checked]:bg-gradient-to-r data-[state=checked]:from-primary data-[state=checked]:to-cyan-500 data-[state=checked]:border-transparent"
                    />
                    {option.label}
                  </DropdownMenuItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>
          )}

          {/* Bulk action buttons */}
          {selectedItems.length > 0 && (
            <>
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="outline" size="sm" className="flex items-center gap-2 bg-transparent h-9 dark:text-neutral-200 dark:border-gray-600">
                    <Settings2 className="w-4 h-4" />
                    All
                    <svg className="w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                    </svg>
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent className="rounded-lg bg-white dark:bg-zinc-800 text-gray-900 dark:text-neutral-200 border border-gray-200 dark:border-gray-600">
                  <DropdownMenuItem
                    onClick={handleBulkActivate}
                    className="hover:bg-gray-100 dark:hover:bg-zinc-700 cursor-pointer rounded-md"
                  >
                    Active
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    onClick={handleBulkDeactivate}
                    className="hover:bg-gray-100 dark:hover:bg-zinc-700 cursor-pointer rounded-md"
                  >
                    Inactive
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>

              <Button
                size="sm"
                onClick={handleBulkDeleteClick}
                className="bg-gradient-to-r from-red-500 to-red-600 text-white hover:from-red-600 hover:to-red-700 h-9"
              >
                <Trash2 className="w-4 h-4 mr-2" />
                Delete
              </Button>
            </>
          )}
        </div>

        {/* Action Button on Right Side */}
        {actionButton && (
          <div className="flex-shrink-0">
            {actionButton}
          </div>
        )}
      </div>

      {/* Table */}
      <div className="mb-6 border border-gray-200 dark:border-zinc-800 rounded-lg overflow-hidden">
        <Table>
          <TableHeader>
            <TableRow className="bg-gray-50 dark:bg-zinc-800">
              <TableHead className="w-12">
                {isPartiallySelected ? (
                  <div
                    className="w-4 h-4 bg-gradient-to-r from-primary to-secondary rounded-sm flex items-center justify-center cursor-pointer"
                    onClick={handleDeselectAll}
                  >
                    <Minus className="w-3 h-3 text-white" />
                  </div>
                ) : (
                  <Checkbox
                    checked={isAllSelected}
                    onCheckedChange={handleSelectAll}
                    className="data-[state=checked]:bg-gradient-to-r data-[state=checked]:from-primary data-[state=checked]:to-secondary text-white data-[state=checked]:border-transparent"
                  />
                )}
              </TableHead>
              {columns.map((column) => (
                <TableHead
                  key={column.key}
                  className="text-gray-900 dark:text-neutral-200"
                >
                  {column.label}
                </TableHead>
              ))}
              {actionMenuItems.length > 0 && <TableHead className="text-right">Action</TableHead>}
            </TableRow>
          </TableHeader>

          <TableBody>
            {data.length > 0 ? (
              data.map((item, index) => (
                <TableRow key={item.id} className="odd:bg-white even:bg-gray-50 dark:odd:bg-zinc-900 dark:even:bg-zinc-800">
                  <TableCell className="px-2 text-center">
                    <Checkbox
                      checked={selectedItems.includes(item.id)}
                      onCheckedChange={() => handleSelectItem(item.id)}
                      className="data-[state=checked]:bg-gradient-to-r data-[state=checked]:from-primary data-[state=checked]:to-secondary data-[state=checked]:border-transparent text-white border-gray-300 dark:border-gray-600"
                    />
                  </TableCell>
                  {columns.map((column) => (
                    <TableCell key={column.key} className={column.cellClassName}>
                      {column.render ? column.render(item, index) : item[column.key]}
                    </TableCell>
                  ))}
                  {actionMenuItems.length > 0 && (
                    <TableCell className="text-right">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="sm" className="dark:text-neutral-200">
                            <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                              <path d="M10 6a2 2 0 110-4 2 2 0 010 4zM10 12a2 2 0 110-4 2 2 0 010 4zM10 18a2 2 0 110-4 2 2 0 010 4z" />
                            </svg>
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end" className="w-34 bg-white dark:bg-zinc-800 text-gray-900 dark:text-neutral-200 border border-gray-200 dark:border-gray-600">
                          {actionMenuItems.map((action) => (
                            <DropdownMenuItem
                              key={action.key}
                              className="text-gray-600 dark:text-neutral-200 hover:text-black dark:hover:text-white cursor-pointer"
                              onClick={() => handleRowActionClick(action.key, item)}
                            >
                              {action.icon && <action.icon className="w-4 h-4 mr-2" />}
                              {action.label}
                            </DropdownMenuItem>
                          ))}
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  )}
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell
                  colSpan={columns.length + (actionMenuItems.length > 0 ? 2 : 1)}
                  className="text-center py-16"
                >
                  <div className="flex flex-col items-center justify-center space-y-4">
                    <div className="w-16 h-16 bg-gradient-to-br from-gray-100 to-gray-200 dark:from-zinc-700 dark:to-zinc-800 rounded-full flex items-center justify-center">
                      <Database className="w-8 h-8 text-gray-400 dark:text-neutral-400" />
                    </div>
                    <div className="space-y-2">
                      <h3 className="text-lg font-semibold text-gray-900 dark:text-neutral-200">No data available</h3>
                      <p className="text-sm text-gray-500 dark:text-neutral-400 max-w-sm">
                        {searchQuery || statusFilter !== "all"
                          ? "No results match your current search or filter criteria. Try adjusting your filters."
                          : "There's no data to display at the moment. Data will appear here once it's available."}
                      </p>
                    </div>
                  </div>
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>

      {/* Pagination */}
      {paginationData && (
        <Pagination
          links={paginationData.links}
          currentPage={paginationData.currentPage}
          lastPage={paginationData.lastPage}
          preserveState={true}
          preserveScroll={true}
          only={[propName]}
          className="mt-4 dark:text-neutral-200"
        />
      )}

      {/* Bulk Delete Modal */}
      <DeleteModal
        isOpen={isBulkDeleteModalOpen}
        onClose={() => setIsBulkDeleteModalOpen(false)}
        title={`Delete ${selectedItems.length} item${selectedItems.length > 1 ? "s" : ""}?`}
        description={`Are you really sure you want to delete ${selectedItems.length} selected item${selectedItems.length > 1 ? "s" : ""}?`}
        onConfirm={handleBulkDeleteConfirm}
        isDeleting={isDeleting}
      />
    </Card>

  )
}