﻿"use client";

import { useState } 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 { State } from "@/features/locations/services/locations.service";
import DOMPurify from "dompurify";

interface AddCityDialogProps {
  states: State[];
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onAdd: (stateId: string, name: string) => Promise<boolean>;
}

export function AddCityDialog({
  states,
  open,
  onOpenChange,
  onAdd,
}: AddCityDialogProps) {
  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");

  const onSubmit = async (data: CityInput) => {
    setIsSubmitting(true);
    try {
      const sanitizedName = DOMPurify.sanitize(data.name.trim());
      const success = await onAdd(data.stateId, sanitizedName);
      if (success) {
        reset();
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleOpenChange = (newOpen: boolean) => {
    if (!newOpen) {
      reset();
    }
    onOpenChange(newOpen);
  };

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Add New City</DialogTitle>
          <DialogDescription>
            Select a state and enter the city name to add to the platform.
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label htmlFor="state-select">State</Label>
              <Select
                value={selectedStateId}
                onValueChange={(value) =>
                  setValue("stateId", value, { shouldValidate: true })
                }
              >
                <SelectTrigger
                  id="state-select"
                  aria-invalid={!!errors.stateId}
                  aria-describedby={
                    errors.stateId ? "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="state-select-error" className="text-sm text-destructive">
                  {errors.stateId.message}
                </p>
              )}
            </div>
            <div className="grid gap-2">
              <Label htmlFor="city-name">City Name</Label>
              <Input
                id="city-name"
                placeholder="Enter city name"
                {...register("name")}
                aria-invalid={!!errors.name}
                aria-describedby={errors.name ? "city-name-error" : undefined}
              />
              {errors.name && (
                <p id="city-name-error" className="text-sm text-destructive">
                  {errors.name.message}
                </p>
              )}
            </div>
          </div>
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => handleOpenChange(false)}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={isSubmitting}>
              {isSubmitting ? "Adding..." : "Add City"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
