"use client";

import { useState } from "react";
import {
  useReactTable,
  getCoreRowModel,
  getPaginationRowModel,
  flexRender,
} from "@tanstack/react-table";
import { useQuery, useQueryClient } from "@tanstack/react-query";

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";

import { Pencil, Trash2, ChevronLeft, ChevronRight } from "lucide-react";
import { Loader2 } from "lucide-react";
import { useModal } from "@/context/ModalProvider";

const DataTable = ({
  fetchData,
  columnsConfig = [],
  title,
  onDelete,
  EditComponent = null,
  tag,
}) => {
  const queryClient = useQueryClient();
  const [pageSize, setPageSize] = useState(10);
  // const [dialogOpen, setDialogOpen] = useState(false);
  // const [selectedRowData, setSelectedRowData] = useState(null);
  const { openModal } = useModal();

  // Fetch Data Using React Query
  const { data: tableData, isLoading } = useQuery({
    queryKey: [tag],
    queryFn: fetchData,
    staleTime: 300000, // 5 minutes
  });

  const handleDeleteClick = async (id) => {
    if (window.confirm("Are you sure you want to delete this item?")) {
      try {
        await onDelete(id);
        queryClient.invalidateQueries([tag]);
      } catch (error) {
        console.error("Delete error:", error);
      }
    }
  };

  // const handleEditClick = (row) => {
  //   setSelectedRowData(row.original);
  //   setDialogOpen(true);
  // };
  const handleEditClick = (row) => {
    // setSelectedRowData(row.original);
    openModal(
      <EditComponent
        key={row.original.id}
        type="edit"
        editData={row.original}
      />
    );
  };

  // Action column config
  let actionsColumn = null;
  if (onDelete || EditComponent) {
    actionsColumn = {
      header: "Action",
      id: "actions",
      cell: ({ row }) => (
        <div className="flex items-center justify-center space-x-2">
          {EditComponent && (
            <Button
              variant="ghost"
              size="icon"
              onClick={() => handleEditClick(row)}
              className="h-8 w-8 p-0"
            >
              <Pencil className="h-4 w-4 text-blue-500" />
            </Button>
          )}
          {onDelete && (
            <Button
              variant="ghost"
              size="icon"
              onClick={() => handleDeleteClick(row.original.id)}
              className="h-8 w-8 p-0"
            >
              <Trash2 className="h-4 w-4 text-red-500" />
            </Button>
          )}
        </div>
      ),
    };
  }

  // Final columns configuration
  const finalColumnsConfig = [...columnsConfig];
  if (actionsColumn) {
    finalColumnsConfig.push(actionsColumn);
  }

  // Table instance
  const table = useReactTable({
    data: tableData?.rows || [],
    columns: finalColumnsConfig,
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    initialState: { pagination: { pageSize } },
  });

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-48">
        <Loader2 className="h-8 w-8 animate-spin" />
      </div>
    );
  }

  return (
    <Card className="mt-4 pt-0 rounded-md overflow-hidden">
      <CardHeader className="p-4 bg-brand-dark/5 pb-4">
        <CardTitle className="text-xl font-semibold text-brand-dark">
          {title}
        </CardTitle>
      </CardHeader>
      <CardContent className="">
        <div className="rounded-md border">
          <Table>
            <TableHeader>
              {table.getHeaderGroups().map((headerGroup) => (
                <TableRow key={headerGroup.id}>
                  {headerGroup.headers.map((header) => (
                    <TableHead
                      key={header.id}
                      className="text-center font-bold text-base"
                    >
                      {header.isPlaceholder
                        ? null
                        : flexRender(
                            header.column.columnDef.header,
                            header.getContext()
                          )}
                    </TableHead>
                  ))}
                </TableRow>
              ))}
            </TableHeader>
            <TableBody>
              {table.getRowModel().rows?.length ? (
                table.getRowModel().rows.map((row) => (
                  <TableRow
                    key={row.id}
                    data-state={row.getIsSelected() && "selected"}
                  >
                    {row.getVisibleCells().map((cell) => (
                      <TableCell key={cell.id} className="text-center">
                        {flexRender(
                          cell.column.columnDef.cell,
                          cell.getContext()
                        )}
                      </TableCell>
                    ))}
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell
                    colSpan={finalColumnsConfig.length}
                    className="h-24 text-center"
                  >
                    No results.
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>

        <div className="flex items-center justify-between space-x-2 py-4">
          <div className="flex items-center space-x-2">
            <p className="text-sm font-medium">Items per page</p>
            <Select
              value={pageSize.toString()}
              onValueChange={(value) => {
                table.setPageSize(Number(value));
                setPageSize(Number(value));
              }}
            >
              <SelectTrigger className="h-8 w-[70px]">
                <SelectValue placeholder={pageSize} />
              </SelectTrigger>
              <SelectContent side="top">
                {[5, 10, 15, 20].map((size) => (
                  <SelectItem key={size} value={size.toString()}>
                    {size}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="flex items-center space-x-2">
            <Button
              variant="outline"
              className="h-8 w-8 p-0"
              onClick={() => table.previousPage()}
              disabled={!table.getCanPreviousPage()}
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <div className="flex w-[100px] items-center justify-center text-sm font-medium">
              Page {table.getState().pagination.pageIndex + 1} of{" "}
              {table.getPageCount()}
            </div>
            <Button
              variant="outline"
              className="h-8 w-8 p-0"
              onClick={() => table.nextPage()}
              disabled={!table.getCanNextPage()}
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      </CardContent>
    </Card>
  );
};

export default DataTable;
