import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import {
  DownloadIcon,
  EditIcon,
  TrashIcon,
  EyeIcon,
  PlusIcon,
} from "lucide-react";
import { AdvancedTable } from "@/shared/common/ui/table/AdvancedTable";
import { IServiceResponse } from "../../types/servicetypes";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/common/ui/alert-dialog";
import { useToast } from "@/shared/common/ui/use-toast";
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 {
  useServiceList,
  useServiceMutations,
} from "@/performance-management/hooks/useServiceHook";
import { useAuth } from "@/shared/context/AuthContext";
import { useLocalizedName } from "@/shared/common/localizedName";

const ServicesTable = () => {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const { toast } = useToast();
  const [pageIndex, setPageIndex] = useState(0);

  const [selectedService, setSelectedService] =
    useState<IServiceResponse | null>(null);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const { user } = useAuth();

  const organizationId =
    user?.employee?.length && user.employee.length > 0
      ? user.employee[0].organizationId
      : undefined;

  const localizedName = useLocalizedName();
  // ✅ SAFELY HANDLE employee ARRAY

  // Use the organizationId directly from user's employee data
  const { data, isLoading, isError, refetch } = useServiceList(
    organizationId || ""
  );

  const { delete: deleteMutation } = useServiceMutations();

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

    deleteMutation.mutate(selectedService.id, {
      onSuccess: () => {
        toast({
          title: t("services.deleteSuccess", "Deleted"),
          description: t(
            "services.deleteSuccessMessage",
            "Service deleted successfully"
          ),
        });
        setIsDeleteDialogOpen(false);
        setSelectedService(null);
        refetch();
      },
      onError: () => {
        toast({
          title: t("common.error", "Error"),
          description: t("services.deleteError", "Failed to delete service"),
          variant: "destructive",
        });
      },
    });
  };

  const services = (data?.data?.items || []).sort(
    (a: IServiceResponse, b: IServiceResponse) => {
      const dateA = new Date(a.createdAt).getTime();
      const dateB = new Date(b.createdAt).getTime();
      return dateB - dateA; // Descending order (newest first)
    }
  );

  const columns: ColumnDef<IServiceResponse>[] = [
    {
      accessorKey: "name",
      header: ({ column }) => {
        return (
          <Button
            variant="ghost"
            onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
            className="h-auto p-0 font-semibold"
          >
            {t("services.serviceName", "Service Name")}
            {column.getIsSorted() === "asc"
              ? " ↑"
              : column.getIsSorted() === "desc"
              ? " ↓"
              : ""}
          </Button>
        );
      },
      cell: ({ row }) => localizedName(row.original.name),
      size: 200,
      enableSorting: true,
      sortingFn: (rowA, rowB) => {
        const nameA = localizedName(rowA.original.name).toLowerCase();
        const nameB = localizedName(rowB.original.name).toLowerCase();
        return nameA.localeCompare(nameB);
      },
    },

    {
      accessorKey: "description",
      header: ({ column }) => {
        return (
          <Button
            variant="ghost"
            onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
            className="h-auto p-0 font-semibold"
          >
            {t("services.description", "Description")}
            {column.getIsSorted() === "asc"
              ? " ↑"
              : column.getIsSorted() === "desc"
              ? " ↓"
              : ""}
          </Button>
        );
      },
      cell: ({ row }) => (
        <div
          className="max-w-[300px] truncate"
          title={localizedName(row.original.description)}
        >
          {localizedName(row.original.description)}
        </div>
      ),
      enableSorting: true,
      sortingFn: (rowA, rowB) => {
        const descA = localizedName(rowA.original.description).toLowerCase();
        const descB = localizedName(rowB.original.description).toLowerCase();
        return descA.localeCompare(descB);
      },
    },

    {
      accessorKey: "estimatedTime",
      header: ({ column }) => {
        return (
          <Button
            variant="ghost"
            onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
            className="h-auto p-0 font-semibold"
          >
            {t("services.estimatedTime", "Estimated Time")}
            {column.getIsSorted() === "asc"
              ? " ↑"
              : column.getIsSorted() === "desc"
              ? " ↓"
              : ""}
          </Button>
        );
      },
      cell: ({ row }) =>
        `${row.original.estimatedTime} ${t(
          `services.timeUnits.${row.original.estimatedTimeUnit.toLowerCase()}`,
          row.original.estimatedTimeUnit
        )}`,
      enableSorting: true,
      sortingFn: (rowA, rowB) => {
        return rowA.original.estimatedTime - rowB.original.estimatedTime;
      },
    },

    {
      accessorKey: "createdAt",
      header: ({ column }) => {
        return (
          <Button
            variant="ghost"
            onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
            className="h-auto p-0 font-semibold"
          >
            {t("services.createdAt", "Created At")}
            {column.getIsSorted() === "asc"
              ? " ↑"
              : column.getIsSorted() === "desc"
              ? " ↓"
              : " ↓"}
          </Button>
        );
      },
      cell: ({ row }) => new Date(row.original.createdAt).toLocaleString(),
      enableSorting: true,
      sortingFn: (rowA, rowB) => {
        const dateA = new Date(rowA.original.createdAt).getTime();
        const dateB = new Date(rowB.original.createdAt).getTime();
        return dateA - dateB;
      },
    },

    {
      id: "actions",
      header: t("common.actions", "Actions"),
      cell: ({ row }) => (
        <div className="flex gap-2">
          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() =>
                    navigate(
                      `/performance-management/services/${row.original.id}`
                    )
                  }
                >
                  <EyeIcon className="h-4 w-4" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>
                {t("services.viewDetails", "View details")}
              </TooltipContent>
            </Tooltip>
          </TooltipProvider>

          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() =>
                    navigate(
                      `/performance-management/services/${row.original.id}/edit`
                    )
                  }
                >
                  <EditIcon className="h-4 w-4" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>{t("common.edit", "Edit")}</TooltipContent>
            </Tooltip>
          </TooltipProvider>

          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    setSelectedService(row.original);
                    setIsDeleteDialogOpen(true);
                  }}
                  disabled={deleteMutation.isPending}
                >
                  <TrashIcon className="h-4 w-4" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>{t("common.delete", "Delete")}</TooltipContent>
            </Tooltip>
          </TooltipProvider>
        </div>
      ),
    },
  ];

  const extraToolbar = (
    <div className="flex gap-2">
      <Button
        onClick={() => navigate(`/performance-management/services/new`)}
        className="bg-gradient-to-r from-purple-500 to-violet-600 text-white"
      >
        <PlusIcon className="h-4 w-4 mr-2" />
        {t("services.createService", "Create Service")}
      </Button>

      <Button
        variant="outline"
        onClick={() =>
          toast({
            title: t("services.exporting", "Exporting"),
            description: t(
              "services.preparingData",
              "Preparing service data..."
            ),
          })
        }
      >
        <DownloadIcon className="h-4 w-4 mr-2" />
        {t("services.exportAll", "Export All")}
      </Button>
    </div>
  );

  // ⬇️ LOADING UI
  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>
    );

  // ⬇️ ERROR UI
  if (isError)
    return (
      <div className="p-6 space-y-4">
        <p className="text-destructive font-semibold">
          {t("services.loadError", "Failed to load services")}
        </p>
        <Button onClick={() => refetch()}>{t("common.retry", "Retry")}</Button>
      </div>
    );

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

      {/* DELETE DIALOG */}
      <AlertDialog
        open={isDeleteDialogOpen}
        onOpenChange={setIsDeleteDialogOpen}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {t("services.deleteTitle", "Confirm Deletion")}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {t(
                "services.deleteConfirmation",
                'Are you sure you want to delete "{{name}}"? This action cannot be undone.',
                { name: localizedName(selectedService?.name) }
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>

          <AlertDialogFooter>
            <AlertDialogCancel>
              {t("common.cancel", "Cancel")}
            </AlertDialogCancel>

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

export default ServicesTable;
