import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { EditIcon, TrashIcon, PlusIcon } from "lucide-react";
import { AdvancedTable } from "@/shared/common/ui/table/AdvancedTable";
import { WorkingHoursResponse } from "../../types/workingHoursTypes";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/common/ui/alert-dialog";
import { ColumnDef } from "@tanstack/react-table";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/shared/common/ui/tooltip";
import { Button } from "@/shared/common/ui/button";
import { Skeleton } from "@/shared/common/ui/skeleton";
import {
  useWorkingHoursList,
  useWorkingHoursMutations,
} from "@/performance-management/hooks/useWorkingHoursHook";
import { CreateWorkingHoursModal } from "./CreateWorkingHoursModal";

const WorkingHoursTable = () => {
  const [pageIndex, setPageIndex] = useState(0);
  const [selectedHours, setSelectedHours] =
    useState<WorkingHoursResponse | null>(null);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);

  const { data, isLoading, isError, refetch } = useWorkingHoursList();
  const { delete: deleteMutation } = useWorkingHoursMutations();

  const handleDelete = async () => {
    if (!selectedHours) return;

    deleteMutation.mutate(selectedHours.id, {
      onSuccess: () => {
        setIsDeleteDialogOpen(false);
        setSelectedHours(null);
        refetch();
      },
    });
  };

  const workingHours = data?.data?.items || data?.data || [];

  const columns: ColumnDef<WorkingHoursResponse>[] = [
    {
      accessorKey: "slug",
      header: "Slug",
      size: 150,
    },
    {
      accessorKey: "weekDay",
      header: "Week Day",
      cell: ({ row }) => (
        <span className="capitalize">{row.original.weekDay}</span>
      ),
    },
    {
      accessorKey: "startTime",
      header: "Start Time",
    },
    {
      accessorKey: "endTime",
      header: "End Time",
    },
    {
      accessorKey: "positionServiceId",
      header: "Position Service ID",
      cell: ({ row }) => (
        <div
          className="max-w-[200px] truncate"
          title={row.original.positionServiceId}
        >
          {row.original.positionServiceId}
        </div>
      ),
    },
    {
      id: "actions",
      header: "Actions",
      cell: ({ row }) => (
        <div className="flex gap-2">
          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    setSelectedHours(row.original);
                    setIsDeleteDialogOpen(true);
                  }}
                  disabled={deleteMutation.isPending}
                >
                  <TrashIcon className="h-4 w-4" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>Delete</TooltipContent>
            </Tooltip>
          </TooltipProvider>
        </div>
      ),
    },
  ];

  const extraToolbar = (
    <div className="flex gap-2">
      <Button
        onClick={() => setIsCreateModalOpen(true)}
        className="bg-gradient-to-r from-purple-500 to-violet-600 text-white"
      >
        <PlusIcon className="h-4 w-4 mr-2" />
        Create Working Hours
      </Button>
    </div>
  );

  if (isLoading)
    return (
      <div className="p-6 space-y-6">
        <Skeleton className="h-8 w-64" />
        <Skeleton className="h-12 w-full" />
        <Skeleton className="h-12 w-full" />
      </div>
    );

  if (isError)
    return (
      <div className="p-6 space-y-4">
        <p className="text-destructive font-semibold">
          Failed to load working hours
        </p>
        <Button onClick={() => refetch()}>Retry</Button>
      </div>
    );

  return (
    <div className="p-6">
      <AdvancedTable<WorkingHoursResponse, unknown>
        columns={columns}
        data={workingHours}
        tableName="Working Hours Management"
        extraToolbar={extraToolbar}
        toolBarPosition="right"
        itemCount={workingHours.length}
        pageIndex={pageIndex}
        onPageChange={setPageIndex}
        nextFunction={() => setPageIndex((p) => p + 1)}
        prevFunction={() => setPageIndex((p) => Math.max(0, p - 1))}
        refresh={refetch}
      />

      <CreateWorkingHoursModal
        open={isCreateModalOpen}
        onClose={() => setIsCreateModalOpen(false)}
        onSuccess={refetch}
      />

      <AlertDialog
        open={isDeleteDialogOpen}
        onOpenChange={setIsDeleteDialogOpen}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Confirm Deletion</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete working hours for "
              {selectedHours?.weekDay}"? This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>

          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>

            <AlertDialogAction
              className="bg-red-600 hover:bg-red-700"
              disabled={deleteMutation.isPending}
              onClick={handleDelete}
            >
              {deleteMutation.isPending ? "Deleting..." : "Delete"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
};

export default WorkingHoursTable;
