import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/shared/common/ui/dialog";
import { Button } from "@/shared/common/ui/button";
import { Input } from "@/shared/common/ui/input";
import { Label } from "@/shared/common/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { toast } from "sonner";
import { useWorkingHoursMutations } from "@/performance-management/hooks/useWorkingHoursHook";
import { CreateWorkingHoursDto, WeekDay } from "../../types/workingHoursTypes";

interface CreateWorkingHoursModalProps {
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
  positionServiceId?: string;
}

const weekDays: (WeekDay | "all")[] = [
  "all",
  "monday",
  "tuesday",
  "wednesday",
  "thursday",
  "friday",
  "saturday",
  "sunday",
];

export const CreateWorkingHoursModal = ({
  open,
  onClose,
  onSuccess,
  positionServiceId = "",
}: CreateWorkingHoursModalProps) => {
  const { create } = useWorkingHoursMutations();
  const [selectedWeekDay, setSelectedWeekDay] = useState<WeekDay | "all">(
    "all"
  );

  const {
    register,
    handleSubmit,
    reset,
    setValue,
    formState: { errors },
  } = useForm<CreateWorkingHoursDto>({
    defaultValues: {
      slug: "",
      weekDay: "monday",
      positionServiceId: positionServiceId,
      startTime: "09:00",
      endTime: "17:00",
    },
  });

  // Update form when positionServiceId prop changes
  useEffect(() => {
    if (positionServiceId) {
      setValue("positionServiceId", positionServiceId);
    }
  }, [positionServiceId, setValue]);

  const onSubmit = async (data: CreateWorkingHoursDto) => {
    // If "all" is selected, create working hours for all days
    if (selectedWeekDay === "all") {
      const allDays: WeekDay[] = [
        "monday",
        "tuesday",
        "wednesday",
        "thursday",
        "friday",
        "saturday",
        "sunday",
      ];

      let successCount = 0;
      let errorCount = 0;

      for (const day of allDays) {
        const payload = {
          ...data,
          weekDay: day,
        };

        try {
          await create.mutateAsync(payload);
          successCount++;
        } catch (error) {
          errorCount++;
          console.error(`Failed to create working hours for ${day}:`, error);
        }
      }

      if (successCount > 0) {
        toast.success(`Working hours created for ${successCount} day(s)${errorCount > 0 ? `, ${errorCount} failed` : ""}`);
        reset();
        onClose();
        onSuccess();
      } else {
        toast.error("Failed to create working hours for all days");
      }
    } else {
      // Single day creation
      const payload = {
        ...data,
        weekDay: selectedWeekDay as WeekDay,
      };

      create.mutate(payload, {
        onSuccess: () => {
          reset();
          onClose();
          onSuccess();
        },
      });
    }
  };

  const handleClose = () => {
    reset();
    onClose();
  };

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Create Working Hours</DialogTitle>
        </DialogHeader>

        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="slug">Slug</Label>
            <Input
              id="slug"
              {...register("slug", { required: "Slug is required" })}
              placeholder="e.g., morning-shift"
            />
            {errors.slug && (
              <p className="text-sm text-red-500">{errors.slug.message}</p>
            )}
          </div>

          <div className="space-y-2">
            <Label htmlFor="weekDay">Week Day</Label>
            <Select
              value={selectedWeekDay}
              onValueChange={(value) =>
                setSelectedWeekDay(value as WeekDay | "all")
              }
            >
              <SelectTrigger>
                <SelectValue placeholder="Select a day" />
              </SelectTrigger>
              <SelectContent>
                {weekDays.map((day) => (
                  <SelectItem key={day} value={day}>
                    <span className="capitalize">
                      {day === "all" ? "All Days" : day}
                    </span>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="startTime">Start Time</Label>
              <Input
                id="startTime"
                type="time"
                {...register("startTime", {
                  required: "Start time is required",
                })}
              />
              {errors.startTime && (
                <p className="text-sm text-red-500">
                  {errors.startTime.message}
                </p>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="endTime">End Time</Label>
              <Input
                id="endTime"
                type="time"
                {...register("endTime", { required: "End time is required" })}
              />
              {errors.endTime && (
                <p className="text-sm text-red-500">{errors.endTime.message}</p>
              )}
            </div>
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={handleClose}>
              Cancel
            </Button>
            <Button
              type="submit"
              disabled={create.isPending}
              className="bg-gradient-to-r from-purple-500 to-violet-600 text-white"
            >
              {create.isPending ? "Creating..." : "Create"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
};
