"use client";
import React from "react";
import {
  ColumnDef,
  SortingState,
  flexRender,
  getCoreRowModel,
  useReactTable,
  getSortedRowModel,
  getPaginationRowModel,
} from "@tanstack/react-table";

import { Table, TableBody, TableCell, TableRow } from "@/components/ui/table";
import { Skeleton } from "@/components/ui/skeleton";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { Edit2, Trash2 } from "lucide-react";

import TopHeader from "./Header";
import TableHeader from "./TableHeader";
import { TableFooter } from "./Footer";
import { cn } from "@/lib/utils";

export interface DataTableProps<TData, TValue> {
  columns: ColumnDef<TData, TValue>[];
  data: TData[];
  title?: string;
  onAddNew?: () => void;
  addButtonText?: string;
  isLoading?: boolean;
  onEdit?: (item: TData) => void;
  onDelete?: (item: TData) => void;
  pagination?: {
    skip: number;
    limit: number;
    totalItems?: number;
    onPageChange: (newSkip: number) => void;
    onLimitChange: (newLimit: number) => void;
  };
}

export function DataTable<TData, TValue>({
  columns: initialColumns,
  data,
  title,
  onAddNew,
  addButtonText,
  isLoading = false,
  onEdit,
  onDelete,
  pagination,
}: DataTableProps<TData, TValue>) {
  const [rowSelection, setRowSelection] = React.useState({});
  const [sorting, setSorting] = React.useState<SortingState>([]);

  const columns = React.useMemo(() => {
    const cols = [...initialColumns];
    if (onEdit || onDelete) {
      cols.push({
        id: "actions",
        header: () => <div className="text-right">Actions</div>,
        cell: ({ row }) => {
          const item = row.original;
          return (
            <div className="flex justify-end gap-2">
              {onEdit && (
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={() => onEdit(item)}
                  className="h-8 w-8"
                >
                  <Edit2 className="h-4 w-4" />
                </Button>
              )}
              {onDelete && (
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={() => onDelete(item)}
                  className="h-8 w-8 text-destructive hover:text-destructive"
                >
                  <Trash2 className="h-4 w-4" />
                </Button>
              )}
            </div>
          );
        },
      });
    }
    return cols;
  }, [initialColumns, onEdit, onDelete]);

  const table = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel(),
    onRowSelectionChange: setRowSelection,
    onSortingChange: setSorting,
    getSortedRowModel: getSortedRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    manualPagination: !!pagination,
    pageCount: pagination?.totalItems ? Math.ceil(pagination.totalItems / pagination.limit) : -1,
    state: {
      rowSelection,
      sorting,
      pagination: pagination ? {
        pageIndex: Math.floor(pagination.skip / pagination.limit),
        pageSize: pagination.limit,
      } : undefined,
    },
    onPaginationChange: (updater) => {
        if (typeof updater === 'function' && pagination) {
            const newState = updater({
                pageIndex: Math.floor(pagination.skip / pagination.limit),
                pageSize: pagination.limit,
            });
            pagination.onLimitChange(newState.pageSize);
            pagination.onPageChange(newState.pageIndex * newState.pageSize);
        }
    },
    initialState: {
      pagination: {
        pageSize: 10,
        pageIndex: 0,
      },
    },
  });

  return (
    <div className="rounded-md border">
      <TopHeader 
        title={title} 
        itemCount={data.length} 
        onAddNew={onAddNew} 
        addButtonText={addButtonText} 
      />

      <div className="relative">
        <Table>
          <TableHeader table={table} />
          <TableBody className="bg-transparent">
            {isLoading ? (
                Array.from({ length: 5 }).map((_, idx) => (
                    <TableRow key={idx}>
                        {columns.map((_, colIdx) => (
                            <TableCell key={colIdx} className="px-8 py-4">
                                <Skeleton className="h-4 w-full max-w-[120px]" />
                            </TableCell>
                        ))}
                    </TableRow>
                ))
            ) : 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}>
                      {flexRender(
                        cell.column.columnDef.cell,
                        cell.getContext()
                      )}
                    </TableCell>
                  ))}
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell
                  colSpan={columns.length}
                  className="h-32 text-center text-sm"
                >
                  No results found.
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>
      
      <TableFooter table={table} />
    </div>
  );
}
