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 { useWorkingHoursMutations } from "@/performance-management/hooks/useWorkingHoursHook";
import {
  CreateWorkingHoursDto,
  WeekDay,
  WorkingHoursResponse,
} from "../../types/workingHoursTypes";

interface EditWorkingHoursModalProps {
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
  workingDay: WorkingHoursResponse | null;
}

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

export const EditWorkingHoursModal = ({
  open,
  onClose,
  onSuccess,
  workingDay,
}: EditWorkingHoursModalProps) => {
  const { update } = useWorkingHoursMutations();
  const [selectedWeekDay, setSelectedWeekDay] = useState<WeekDay>("monday");

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

  // Update form when workingDay changes
  useEffect(() => {
    if (workingDay) {
      setValue("slug", workingDay.slug);
      setValue("positionServiceId", workingDay.positionServiceId);
      setValue("startTime", workingDay.startTime.substring(0, 5)); // Remove seconds
      setValue("endTime", workingDay.endTime.substring(0, 5)); // Remove seconds
      setSelectedWeekDay(workingDay.weekDay);
    }
  }, [workingDay, setValue]);

  const onSubmit = async (data: CreateWorkingHoursDto) => {
    if (!workingDay?.id) return;

    const payload = {
      ...data,
      weekDay: selectedWeekDay,
    };

    update.mutate(
      { id: workingDay.id, data: payload },
      {
        onSuccess: () => {
          reset();
          onClose();
          onSuccess();
        },
      }
    );
  };

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

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Edit 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)}
            >
              <SelectTrigger>
                <SelectValue placeholder="Select a day" />
              </SelectTrigger>
              <SelectContent>
                {weekDays.map((day) => (
                  <SelectItem key={day} value={day}>
                    <span className="capitalize">{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={update.isPending}
              className="bg-gradient-to-r from-purple-500 to-violet-600 text-white"
            >
              {update.isPending ? "Updating..." : "Update"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
};
