"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 { stateSchema, type StateInput } from "@/lib/validations/location";
import DOMPurify from "dompurify";

interface AddStateDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onAdd: (name: string) => Promise<boolean>;
}

export function AddStateDialog({
  open,
  onOpenChange,
  onAdd,
}: AddStateDialogProps) {
  const [isSubmitting, setIsSubmitting] = useState(false);

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<StateInput>({
    resolver: zodResolver(stateSchema),
    defaultValues: { name: "" },
  });

  const onSubmit = async (data: StateInput) => {
    setIsSubmitting(true);
    try {
      const sanitizedName = DOMPurify.sanitize(data.name.trim());
      const success = await onAdd(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 State</DialogTitle>
          <DialogDescription>
            Enter the name of the state you want 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-name">State Name</Label>
              <Input
                id="state-name"
                placeholder="Enter state name"
                {...register("name")}
                aria-invalid={!!errors.name}
                aria-describedby={errors.name ? "state-name-error" : undefined}
              />
              {errors.name && (
                <p id="state-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 State"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
