import * as React from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} 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 { Spinner } from "@/components/ui/spinner";
import { AddressAutocomplete } from "@/components/ui/form-primitives";

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

export interface CreateContactFormData {
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  address?: string;
  assignedStaffId?: string;
}

export interface StaffOption {
  id: string;
  displayName: string;
}

export interface CreateContactModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSubmit: (data: CreateContactFormData) => void;
  isLoading?: boolean;
  /** When provided, renders an "Assign to" staff selector (Admin role). */
  staffOptions?: StaffOption[];
  className?: string;
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function Field({
  id,
  label,
  required,
  children,
}: {
  id: string;
  label: string;
  required?: boolean;
  children: React.ReactNode;
}) {
  return (
    <div className="flex flex-col gap-1.5">
      <Label htmlFor={id}>
        {label}
        {required && <span className="ml-0.5 text-destructive">*</span>}
      </Label>
      {children}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

const EMPTY_FORM: CreateContactFormData = {
  firstName: "",
  lastName: "",
  email: "",
  phone: "",
  address: "",
};

export function CreateContactModal({
  open,
  onOpenChange,
  onSubmit,
  isLoading = false,
  staffOptions,
  className,
}: CreateContactModalProps) {
  const [form, setForm] = React.useState<CreateContactFormData>(EMPTY_FORM);

  // Reset form when dialog opens
  React.useEffect(() => {
    if (open) setForm(EMPTY_FORM);
  }, [open]);

  function set(field: keyof CreateContactFormData, value: string) {
    setForm((prev) => ({ ...prev, [field]: value }));
  }

  const isValid =
    form.firstName.trim() !== "" &&
    form.lastName.trim() !== "" &&
    form.email.trim() !== "";

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!isValid || isLoading) return;
    onSubmit(form);
  }

  return (
    <Dialog open={open} onOpenChange={isLoading ? undefined : onOpenChange}>
      <DialogContent size="lg" className={className}>
        <DialogHeader>
          <DialogTitle>Add New Client</DialogTitle>
        </DialogHeader>

        <form id="create-contact-form" onSubmit={handleSubmit}>
          <div className="flex flex-col gap-4">
            {/* Name row */}
            <div className="grid grid-cols-2 gap-3">
              <Field id="ccm-firstName" label="First name" required>
                <Input
                  id="ccm-firstName"
                  placeholder="First name"
                  value={form.firstName}
                  onChange={(e) => set("firstName", e.target.value)}
                  disabled={isLoading}
                  autoComplete="given-name"
                />
              </Field>
              <Field id="ccm-lastName" label="Last name" required>
                <Input
                  id="ccm-lastName"
                  placeholder="Last name"
                  value={form.lastName}
                  onChange={(e) => set("lastName", e.target.value)}
                  disabled={isLoading}
                  autoComplete="family-name"
                />
              </Field>
            </div>

            {/* Email */}
            <Field id="ccm-email" label="Email address" required>
              <Input
                id="ccm-email"
                type="email"
                placeholder="name@example.com"
                value={form.email}
                onChange={(e) => set("email", e.target.value)}
                disabled={isLoading}
                autoComplete="email"
              />
            </Field>

            {/* Phone */}
            <Field id="ccm-phone" label="Phone number">
              <Input
                id="ccm-phone"
                type="tel"
                placeholder="+61 4xx xxx xxx"
                value={form.phone}
                onChange={(e) => set("phone", e.target.value)}
                disabled={isLoading}
                autoComplete="tel"
              />
            </Field>

            {/* Address */}
            <Field id="ccm-address" label="Address">
              <AddressAutocomplete
                value={form.address ?? ""}
                onValueChange={(v) => set("address", v)}
                onSelect={(opt) => set("address", opt.label)}
                disabled={isLoading}
              />
            </Field>

            {/* Staff selector — Admin role only */}
            {staffOptions && staffOptions.length > 0 && (
              <Field id="ccm-staff" label="Assign to">
                <Select
                  value={form.assignedStaffId ?? ""}
                  onValueChange={(v) => set("assignedStaffId", v ?? "")}
                  disabled={isLoading}
                >
                  <SelectTrigger id="ccm-staff">
                    <SelectValue placeholder="Select staff member" />
                  </SelectTrigger>
                  <SelectContent>
                    {staffOptions.map((s) => (
                      <SelectItem key={s.id} value={s.id}>
                        {s.displayName}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </Field>
            )}
          </div>
        </form>

        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={isLoading}
          >
            Cancel
          </Button>
          <Button
            type="submit"
            form="create-contact-form"
            disabled={!isValid || isLoading}
          >
            {isLoading ? (
              <>
                <Spinner className="size-3.5" />
                Creating…
              </>
            ) : (
              "Create Client"
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
