import React, { useEffect, useState } from "react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/common/ui/table";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/shared/common/ui/dropdown-menu";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/common/ui/alert-dialog";
import { Button } from "@/shared/common/ui/button";
import {
  MoreVertical,
  Clock,
  ChevronDown,
  ChevronRight,
  Trash2,
} from "lucide-react";
import {
  getPositionServices,
  deletePositionService,
} from "@/performance-management/services/api/serviceAssignmentService";
import { useLocalizedName } from "@/shared/common/localizedName";
import { Skeleton } from "@/shared/common/ui/skeleton";
import { useToast } from "@/shared/common/ui/use-toast";
import { CreateWorkingHoursModal } from "@/performance-management/components/WorkingHours/CreateWorkingHoursModal";
import { EditWorkingHoursModal } from "@/performance-management/components/WorkingHours/EditWorkingHoursModal";
import { WorkingDaysTable } from "@/performance-management/components/WorkingHours/WorkingDaysTable";
import { useWorkingHoursMutations } from "@/performance-management/hooks/useWorkingHoursHook";
import { WorkingHoursResponse } from "@/performance-management/types/workingHoursTypes";
import { t } from "i18next";

interface PositionServicesListProps {
  positionId: string;
}

export const PositionServicesList = ({
  positionId,
}: PositionServicesListProps) => {
  const [services, setServices] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isWorkingHoursModalOpen, setIsWorkingHoursModalOpen] = useState(false);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [selectedPositionServiceId, setSelectedPositionServiceId] =
    useState<string>("");
  const [editingWorkingDay, setEditingWorkingDay] =
    useState<WorkingHoursResponse | null>(null);
  const [expandedServiceId, setExpandedServiceId] = useState<string | null>(
    null
  );
  const [refreshTrigger, setRefreshTrigger] = useState(0);
  const [deletingServiceId, setDeletingServiceId] = useState<string | null>(
    null
  );
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [isDeletingService, setIsDeletingService] = useState(false);
  const localizedName = useLocalizedName();
  const { toast } = useToast();
  const { delete: deleteWorkingHours } = useWorkingHoursMutations();

  const handleCreateWorkingHours = (positionServiceId: string) => {
    setSelectedPositionServiceId(positionServiceId);
    setIsWorkingHoursModalOpen(true);
  };

  const handleWorkingHoursSuccess = () => {
    setIsWorkingHoursModalOpen(false);
    setSelectedPositionServiceId("");
    setRefreshTrigger((prev) => prev + 1);
  };

  const handleEditWorkingDay = (workingDay: WorkingHoursResponse) => {
    setEditingWorkingDay(workingDay);
    setIsEditModalOpen(true);
  };

  const handleEditSuccess = () => {
    setIsEditModalOpen(false);
    setEditingWorkingDay(null);
    setRefreshTrigger((prev) => prev + 1);
  };

  const handleDeleteWorkingDay = async (id: string) => {
    deleteWorkingHours.mutate(id, {
      onSuccess: () => {
        toast({
          title: "Success",
          description: "Working hours deleted successfully",
        });
        setRefreshTrigger((prev) => prev + 1);
      },
      onError: (error: any) => {
        toast({
          title: "Error",
          description:
            error?.response?.data?.message || "Failed to delete working hours",
          variant: "destructive",
        });
      },
    });
  };

  const toggleExpand = (serviceId: string) => {
    setExpandedServiceId(expandedServiceId === serviceId ? null : serviceId);
  };

  const handleDeleteService = (positionServiceId: string) => {
    setDeletingServiceId(positionServiceId);
    setIsDeleteDialogOpen(true);
  };

  const confirmDeleteService = async () => {
    if (!deletingServiceId) return;

    setIsDeletingService(true);
    try {
      await deletePositionService(deletingServiceId);
      toast({
        title: "Success",
        description: "Service removed from position successfully",
      });
      // Refresh the services list
      const response = await getPositionServices(positionId);
      const data = response.data;
      if (data && Array.isArray(data.items)) {
        setServices(data.items);
      } else if (Array.isArray(data)) {
        setServices(data);
      } else {
        setServices([]);
      }
      setIsDeleteDialogOpen(false);
      setDeletingServiceId(null);
    } catch (error: any) {
      toast({
        title: "Error",
        description:
          error?.response?.data?.message || "Failed to remove service",
        variant: "destructive",
      });
    } finally {
      setIsDeletingService(false);
    }
  };

  useEffect(() => {
    const fetchServices = async () => {
      if (!positionId) {
        setServices([]);
        return;
      }

      setIsLoading(true);
      try {
        const response = await getPositionServices(positionId);
        // Handle both array and single object response
        const data = response.data;
        if (data && Array.isArray(data.items)) {
          setServices(data.items);
        } else if (Array.isArray(data)) {
          setServices(data);
        } else if (data) {
          setServices([data]);
        } else {
          setServices([]);
        }
      } catch (error) {
        console.error("Failed to fetch position services", error);
        setServices([]);
      } finally {
        setIsLoading(false);
      }
    };

    fetchServices();
  }, [positionId]);

  if (!positionId) {
    return null;
  }

  if (isLoading) {
    return (
      <div className="space-y-2 border rounded-md p-4 bg-white mt-4">
        <Skeleton className="h-8 w-full" />
        <Skeleton className="h-8 w-full" />
        <Skeleton className="h-8 w-full" />
      </div>
    );
  }

  if (services.length === 0) {
    return (
      <div className="text-center py-8 text-gray-500 border rounded-md bg-white mt-4">
        {t("noServicesFound", "No services found for this position")}
      </div>
    );
  }

  return (
    <div className="border rounded-md bg-white overflow-hidden mt-4 shadow-sm">
      <div className="p-3 border-b bg-gray-50">
        <h3 className="font-medium text-gray-700">
          {t("associatedServices", "Associated Services")}
        </h3>
      </div>
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead className="w-12"></TableHead>
            <TableHead>{t("name", "Name")}</TableHead>
            <TableHead>{t("slug", "Slug")}</TableHead>
            <TableHead>{t("description", "Description")}</TableHead>
            <TableHead className="text-right">
              {t("actions", "Actions")}
            </TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {services.map((positionService) => (
            <React.Fragment key={positionService.id}>
              <TableRow className="cursor-pointer hover:bg-gray-50">
                <TableCell onClick={() => toggleExpand(positionService.id)}>
                  <Button variant="ghost" size="sm" className="p-0 h-6 w-6">
                    {expandedServiceId === positionService.id ? (
                      <ChevronDown className="h-4 w-4" />
                    ) : (
                      <ChevronRight className="h-4 w-4" />
                    )}
                  </Button>
                </TableCell>
                <TableCell
                  className="font-medium"
                  onClick={() => toggleExpand(positionService.id)}
                >
                  {localizedName(positionService.service?.name)}
                </TableCell>
                <TableCell onClick={() => toggleExpand(positionService.id)}>
                  {positionService.service?.slug}
                </TableCell>
                <TableCell onClick={() => toggleExpand(positionService.id)}>
                  {localizedName(positionService.service?.description)}
                </TableCell>
                <TableCell className="text-right">
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button variant="ghost" size="sm">
                        <MoreVertical className="h-4 w-4" />
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                      <DropdownMenuItem
                        onClick={() =>
                          handleCreateWorkingHours(positionService.id)
                        }
                      >
                        <Clock className="h-4 w-4 mr-2" />
                        {t("createWorkingHours", "Create Working Hours")}
                      </DropdownMenuItem>
                      <DropdownMenuItem
                        onClick={() => handleDeleteService(positionService.id)}
                        className="text-red-600 focus:text-red-600"
                      >
                        <Trash2 className="h-4 w-4 mr-2" />
                        {t("removeService", "Remove Service")}
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                </TableCell>
              </TableRow>
              {expandedServiceId === positionService.id && (
                <TableRow>
                  <TableCell colSpan={5} className="bg-gray-50 p-4">
                    <div className="space-y-2">
                      <h4 className="font-semibold text-sm text-gray-700">
                        {t("workingDays", "Working Days")}
                      </h4>
                      <WorkingDaysTable
                        positionServiceId={positionService.id}
                        onEdit={handleEditWorkingDay}
                        onDelete={handleDeleteWorkingDay}
                        refreshTrigger={refreshTrigger}
                      />
                    </div>
                  </TableCell>
                </TableRow>
              )}
            </React.Fragment>
          ))}
        </TableBody>
      </Table>

      {/* Create Working Hours Modal */}
      <CreateWorkingHoursModal
        open={isWorkingHoursModalOpen}
        onClose={() => {
          setIsWorkingHoursModalOpen(false);
          setSelectedPositionServiceId("");
        }}
        onSuccess={handleWorkingHoursSuccess}
        positionServiceId={selectedPositionServiceId}
      />

      {/* Edit Working Hours Modal */}
      <EditWorkingHoursModal
        open={isEditModalOpen}
        onClose={() => {
          setIsEditModalOpen(false);
          setEditingWorkingDay(null);
        }}
        onSuccess={handleEditSuccess}
        workingDay={editingWorkingDay}
      />

      {/* Delete Service Confirmation Dialog */}
      <AlertDialog
        open={isDeleteDialogOpen}
        onOpenChange={setIsDeleteDialogOpen}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Remove Service from Position</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to remove this service from the position?
              This will also delete all associated working hours. This action
              cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isDeletingService}>
              Cancel
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={confirmDeleteService}
              disabled={isDeletingService}
              className="bg-red-600 hover:bg-red-700"
            >
              {isDeletingService ? "Removing..." : "Remove"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
};
