"use client";

import { useState, useEffect } from "react";
import { UserPlus } from "lucide-react";
import { Input } from "@/shared/components/ui/input";
import { Label } from "@/shared/components/ui/label";
import { Button } from "@/shared/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/shared/components/ui/dialog";

export interface QuickContactData {
  name: string;
  company: string;
  phone: string;
  email: string;
}

interface QuickContactDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  /** Pre-filled name from the text the user typed */
  initialName: string;
  onConfirm: (data: QuickContactData) => void;
}

/**
 * Rapid popup for creating a new Address Book contact from Registratura.
 * Requires either Name or Company; Phone and Email are optional.
 */
export function QuickContactDialog({
  open,
  onOpenChange,
  initialName,
  onConfirm,
}: QuickContactDialogProps) {
  const [name, setName] = useState(initialName);
  const [company, setCompany] = useState("");
  const [phone, setPhone] = useState("");
  const [email, setEmail] = useState("");

  // Sync name with initialName whenever the dialog opens
  useEffect(() => {
    if (open) {
      setName(initialName);
      setCompany("");
      setPhone("");
      setEmail("");
    }
  }, [open, initialName]);

  const hasIdentifier = name.trim() || company.trim();

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    // Stop propagation so the submit doesn't bubble through the React portal
    // to the outer registry-entry-form, which would close the whole form.
    e.stopPropagation();
    if (!hasIdentifier) return;
    onConfirm({
      name: name.trim(),
      company: company.trim(),
      phone: phone.trim(),
      email: email.trim(),
    });
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <UserPlus className="h-4 w-4" />
            Contact nou rapid
          </DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-3">
          {!hasIdentifier && (
            <p className="text-xs text-destructive">
              Completează cel puțin Numele sau Compania/Organizația.
            </p>
          )}
          <div className="grid gap-3 sm:grid-cols-2">
            <div>
              <Label>Nume {!company.trim() ? "*" : ""}</Label>
              <Input
                value={name}
                onChange={(e) => setName(e.target.value)}
                className="mt-1"
                required={!company.trim()}
                autoFocus
              />
            </div>
            <div>
              <Label>Companie/Organizație {!name.trim() ? "*" : ""}</Label>
              <Input
                value={company}
                onChange={(e) => setCompany(e.target.value)}
                className="mt-1"
                required={!name.trim()}
              />
            </div>
          </div>
          <div className="grid gap-3 sm:grid-cols-2">
            <div>
              <Label>Telefon</Label>
              <Input
                value={phone}
                onChange={(e) => setPhone(e.target.value)}
                className="mt-1"
                placeholder="Opțional"
              />
            </div>
            <div>
              <Label>Email</Label>
              <Input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="mt-1"
                placeholder="Opțional"
              />
            </div>
          </div>
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
            >
              Anulează
            </Button>
            <Button type="submit" disabled={!hasIdentifier}>
              Creează contact
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
