import { useEffect, useState } from "react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/common/ui/table";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/shared/common/ui/alert-dialog";
import { Button } from "@/shared/common/ui/button";
import { Skeleton } from "@/shared/common/ui/skeleton";
import { Edit, Trash2 } from "lucide-react";
import { getWorkingHoursByPositionServiceId } from "@/performance-management/services/api/workingHoursService";
import { WorkingHoursResponse } from "@/performance-management/types/workingHoursTypes";
import { t } from "i18next";

interface WorkingDaysTableProps {
  positionServiceId: string;
  onEdit?: (workingDay: WorkingHoursResponse) => void;
  onDelete?: (id: string) => void;
  refreshTrigger?: number;
}

export const WorkingDaysTable = ({
  positionServiceId,
  onEdit,
  onDelete,
  refreshTrigger,
}: WorkingDaysTableProps) => {
  const [workingDays, setWorkingDays] = useState<WorkingHoursResponse[]>([]);
  const [isLoading, setIsLoading] = useState(false);

  const fetchWorkingDays = async () => {
    if (!positionServiceId) {
      setWorkingDays([]);
      return;
    }

    setIsLoading(true);
    try {
      const response = await getWorkingHoursByPositionServiceId(
        positionServiceId
      );
      const data = response.data;

      if (data && Array.isArray(data.items)) {
        setWorkingDays(data.items);
      } else if (Array.isArray(data)) {
        setWorkingDays(data);
      } else {
        setWorkingDays([]);
      }
    } catch (error) {
      console.error("Failed to fetch working days", error);
      setWorkingDays([]);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchWorkingDays();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [positionServiceId, refreshTrigger]);

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

  if (workingDays.length === 0) {
    return (
      <div className="text-center py-8 text-gray-500">
        {t("noWorkingDaysFound", "No working days configured for this service")}
      </div>
    );
  }

  return (
    <div className="border rounded-md bg-white overflow-hidden">
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>{t("weekDay", "Week Day")}</TableHead>
            <TableHead>{t("slug", "Slug")}</TableHead>
            <TableHead>{t("startTime", "Start Time")}</TableHead>
            <TableHead>{t("endTime", "End Time")}</TableHead>
            <TableHead className="text-right">
              {t("actions", "Actions")}
            </TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {workingDays.map((day) => (
            <TableRow key={day.id}>
              <TableCell className="font-medium capitalize">
                {day.weekDay}
              </TableCell>
              <TableCell>{day.slug}</TableCell>
              <TableCell>{day.startTime}</TableCell>
              <TableCell>{day.endTime}</TableCell>
              <TableCell className="text-right">
                <div className="flex justify-end gap-2">
                  {onEdit && (
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => onEdit(day)}
                    >
                      <Edit className="h-4 w-4" />
                    </Button>
                  )}
                  {onDelete && (
                    <AlertDialog>
                      <AlertDialogTrigger asChild>
                        <Button variant="ghost" size="sm">
                          <Trash2 className="h-4 w-4 text-red-500" />
                        </Button>
                      </AlertDialogTrigger>
                      <AlertDialogContent>
                        <AlertDialogHeader>
                          <AlertDialogTitle>
                            Delete Working Hours
                          </AlertDialogTitle>
                          <AlertDialogDescription>
                            Are you sure you want to delete this working hours
                            configuration? This action cannot be undone.
                          </AlertDialogDescription>
                        </AlertDialogHeader>
                        <AlertDialogFooter>
                          <AlertDialogCancel>Cancel</AlertDialogCancel>
                          <AlertDialogAction
                            onClick={() => onDelete(day.id)}
                            className="bg-red-600 hover:bg-red-700"
                          >
                            Delete
                          </AlertDialogAction>
                        </AlertDialogFooter>
                      </AlertDialogContent>
                    </AlertDialog>
                  )}
                </div>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  );
};
