﻿"use client";

import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { citySchema, type CityInput } from "@/lib/validations/location";
import type {
  City,
  State,
} from "@/features/locations/services/locations.service";
import DOMPurify from "dompurify";

interface EditCityDialogProps {
  city: City | null;
  states: State[];
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSave: (id: string, stateId: string, name: string) => Promise<boolean>;
}

export function EditCityDialog({
  city,
  states,
  open,
  onOpenChange,
  onSave,
}: EditCityDialogProps) {
  const [isSubmitting, setIsSubmitting] = useState(false);

  const {
    register,
    handleSubmit,
    reset,
    setValue,
    watch,
    formState: { errors },
  } = useForm<CityInput>({
    resolver: zodResolver(citySchema),
    defaultValues: { stateId: "", name: "" },
  });

  const selectedStateId = watch("stateId");

  useEffect(() => {
    if (city) {
      reset({ stateId: city.stateId, name: city.name });
    }
  }, [city, reset]);

  const onSubmit = async (data: CityInput) => {
    if (!city) return;

    setIsSubmitting(true);
    try {
      const sanitizedName = DOMPurify.sanitize(data.name.trim());
      await onSave(city.id, data.stateId, sanitizedName);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Edit City</DialogTitle>
          <DialogDescription>Update the city details.</DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label htmlFor="edit-state-select">State</Label>
              <Select
                value={selectedStateId}
                onValueChange={(value) =>
                  setValue("stateId", value, { shouldValidate: true })
                }
              >
                <SelectTrigger
                  id="edit-state-select"
                  aria-invalid={!!errors.stateId}
                  aria-describedby={
                    errors.stateId ? "edit-state-select-error" : undefined
                  }
                >
                  <SelectValue placeholder="Select a state" />
                </SelectTrigger>
                <SelectContent>
                  {states.map((state) => (
                    <SelectItem key={state.id} value={state.id}>
                      {state.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {errors.stateId && (
                <p
                  id="edit-state-select-error"
                  className="text-sm text-destructive"
                >
                  {errors.stateId.message}
                </p>
              )}
            </div>
            <div className="grid gap-2">
              <Label htmlFor="edit-city-name">City Name</Label>
              <Input
                id="edit-city-name"
                placeholder="Enter city name"
                {...register("name")}
                aria-invalid={!!errors.name}
                aria-describedby={
                  errors.name ? "edit-city-name-error" : undefined
                }
              />
              {errors.name && (
                <p
                  id="edit-city-name-error"
                  className="text-sm text-destructive"
                >
                  {errors.name.message}
                </p>
              )}
            </div>
          </div>
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={isSubmitting}>
              {isSubmitting ? "Saving..." : "Save Changes"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
