import { useState, useMemo } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { PlusIcon, RefreshCw } from "lucide-react";
import { useQueryClient } from "@tanstack/react-query";
import { Button } from "@/shared/common/ui/button";
import { Skeleton } from "@/shared/common/ui/skeleton";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/common/ui/alert-dialog";
import { PlanYearCard } from "./PlanYearCard";
import {
  usePlanYears,
  usePlanYearMutations,
} from "@/performance-management/hooks/usePlanYear";
import { PlanYear } from "@/performance-management/types/planYearTypes";
import { useAuth } from "@/shared/context/AuthContext";
import {
  checkIsPlanInitiator,
  checkIsUnitAdmin,
} from "@/performance-management/hooks/usePlans";
import { useLocalizedName } from "@/shared/common/localizedName";

export default function PlanYearList() {
  const navigate = useNavigate();
  const location = useLocation();
  const queryClient = useQueryClient();
  const { t } = useTranslation();
  const { user } = useAuth();
  const localizedName = useLocalizedName();
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [selectedPlanYear, setSelectedPlanYear] = useState<PlanYear | null>(
    null
  );
  const basePath = useMemo(() => {
    const segments = location.pathname.startsWith("/objective");
    if (segments) {
      return "/objective-management";
    }
    return "/performance-management";
  }, [location.pathname]);

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

  // Check if user is unit admin
  const isUnitAdmin = useMemo(() => checkIsPlanInitiator(user), [user]);
  console.log("isUnitAdmin", isUnitAdmin);
  const { data, isLoading, isFetching, isError, error, refetch } = usePlanYears(
    organizationId,
    {
      take: 100,
      skip: 0,
    }
  );

  const { delete: deletePlanYear } = usePlanYearMutations();

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

  const handleEdit = (id: string) => {
    navigate(`${basePath}/plan-years/${id}/edit`);
  };

  const handleRefresh = () => {
    queryClient.invalidateQueries({
      queryKey: ["planYears", "list", organizationId],
    });
  };

  const handleDelete = (id: string) => {
    const planYear = planYears.find((py: PlanYear) => py.id === id);
    if (planYear) {
      setSelectedPlanYear(planYear);
      setIsDeleteDialogOpen(true);
    }
  };

  const confirmDelete = () => {
    if (!selectedPlanYear) return;

    deletePlanYear.mutate(selectedPlanYear.id, {
      onSuccess: () => {
        setIsDeleteDialogOpen(false);
        setSelectedPlanYear(null);
      },
    });
  };

  if (isLoading) {
    return (
      <div className="p-6 space-y-6">
        <div className="flex justify-between items-center mb-6">
          <Skeleton className="h-8 w-64" />
          <Skeleton className="h-10 w-40" />
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {[1, 2, 3, 4, 5, 6].map((i) => (
            <Skeleton key={i} className="h-64 w-full rounded-lg" />
          ))}
        </div>
      </div>
    );
  }

  if (isError) {
    return (
      <div className="p-6 space-y-4">
        <div className="text-destructive text-lg font-semibold">
          {t("planYear.loadingError", "Error loading plan years")}
        </div>
        <div className="text-muted-foreground">
          {error?.message ||
            t(
              "planYear.loadingErrorMessage",
              "Failed to load plan years. Please try again."
            )}
        </div>
        <Button onClick={() => refetch()}>
          {t("planYear.retry", "Retry")}
        </Button>
      </div>
    );
  }

  return (
    <div className="p-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">
            {t("planYearList.title", "Plan Years")}
          </h1>
          <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
            {t("planYearList.description", "Manage and organize plans by year")}
          </p>
        </div>

        <div className="flex flex-wrap gap-2">
          {isUnitAdmin && (
            <Button
              onClick={() => navigate(`${basePath}/plan-years/new`)}
              className="bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700 text-white">
              <PlusIcon className="h-4 w-4 mr-2" />
              {t("planYearList.createPlanYear", "Create Plan Year")}
            </Button>
          )}

          <Button
            variant="outline"
            onClick={handleRefresh}
            disabled={isFetching}
            className="gap-2"
          >
            <RefreshCw className={`h-4 w-4 ${isFetching ? "animate-spin" : ""}`} />
            {t("common.refresh", "Refresh")}
          </Button>
        </div>
      </div>

      {/* Plan Years Grid */}
      {planYears.length === 0 ? (
        <div className="text-center py-12">
          <div className="text-gray-400 dark:text-gray-500 mb-4">
            <svg
              className="mx-auto h-12 w-12"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor">
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
              />
            </svg>
          </div>
          <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
            {t("planYearList.noPlanYears", "No plan years yet")}
          </h3>
          <p className="text-gray-600 dark:text-gray-400 mb-4">
            {t(
              "planYearList.getStarted",
              "Get started by creating your first plan year"
            )}
          </p>
          {isUnitAdmin && (
            <Button
              onClick={() => navigate("/performance-management/plan-years/new")}
              className="bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700 text-white">
              <PlusIcon className="h-4 w-4 mr-2" />
              {t("planYearList.createPlanYear", "Create Plan Year")}
            </Button>
          )}
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
          {planYears.map((planYear: PlanYear) => (
            <PlanYearCard
              key={planYear.id}
              planYear={planYear}
              onEdit={handleEdit}
              onDelete={handleDelete}
              isUnitAdmin={isUnitAdmin}
            />
          ))}
        </div>
      )}

      {/* Delete Confirmation Dialog */}
      <AlertDialog
        open={isDeleteDialogOpen}
        onOpenChange={setIsDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              {t("planYearList.confirmDeletion", "Confirm Deletion")}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {t(
                "planYearList.deleteConfirmation",
                'Are you sure you want to delete the plan year "{{year}} - {{name}}"? This action cannot be undone and may affect associated plans.',
                {
                  year: selectedPlanYear?.year,
                  name: localizedName(selectedPlanYear?.name),
                }
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel
              onClick={() => {
                setIsDeleteDialogOpen(false);
                setSelectedPlanYear(null);
              }}
              disabled={deletePlanYear.isPending}>
              {t("common.cancel", "Cancel")}
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmDelete}
              disabled={deletePlanYear.isPending}
              className="bg-red-600 hover:bg-red-700">
              {deletePlanYear.isPending ? (
                <>
                  <div className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent mr-2" />
                  {t("planYearList.deleting", "Deleting...")}
                </>
              ) : (
                t("planYearList.delete", "Delete")
              )}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
