"use client";

import { useRef, useState } from "react";
import { Loader2 } from "lucide-react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { FormField, SelectField } from "@/components/shared/form-field";
import type { Location } from "./types";
import { siteManagerCreateFromForm } from "./site-manager-contract";
import { createSiteManager } from "./site-manager-client-api";

export function CreateSiteManagerDialog({ location, onOpenChange, onCreated }: {
  location: Pick<Location, "id" | "name">;
  onOpenChange: (open: boolean) => void;
  onCreated: () => void;
}) {
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const pending = useRef(false);
  function changeOpen(open: boolean) { if (!pending.current) onOpenChange(open); }

  return <Dialog open onOpenChange={changeOpen}>
    <DialogContent className="flex max-h-[92dvh] flex-col gap-0 overflow-clip p-0 sm:max-w-[640px]" showCloseButton={!saving}>
      <DialogHeader className="shrink-0 border-b px-6 py-5 pr-14">
        <DialogTitle>Add Site Manager</DialogTitle>
        <DialogDescription>Create an account and assign it to {location.name}.</DialogDescription>
      </DialogHeader>
      <form className="flex min-h-0 flex-1 flex-col" onSubmit={async event => {
        event.preventDefault();
        if (pending.current) return;
        setError("");
        const payload = siteManagerCreateFromForm(new FormData(event.currentTarget), location.id);
        if (!payload) { setError("Check the name, email, international phone number, and optional profile details."); return; }
        pending.current = true; setSaving(true);
        try { await createSiteManager(location.id, payload); onCreated(); }
        catch (cause) { setError(cause instanceof Error ? cause.message : "Unable to create the Site Manager."); }
        finally { pending.current = false; setSaving(false); }
      }}>
        <div className="min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-5">
          {error && <p role="alert" className="rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">{error}</p>}
          <fieldset disabled={saving} className="space-y-5 disabled:opacity-70">
            <div className="rounded-lg border bg-muted/40 px-4 py-3"><p className="text-xs text-muted-foreground">Assigned location</p><p className="mt-1 break-words font-medium">{location.name}</p></div>
            <div className="grid gap-4 sm:grid-cols-2">
              <FormField name="firstname" label="First name" autoComplete="given-name" required maxLength={100} />
              <FormField name="lastname" label="Last name" autoComplete="family-name" required maxLength={100} />
              <FormField name="email" label="Email" type="email" autoComplete="email" required maxLength={254} />
              <div><FormField name="phone" label="Phone" type="tel" autoComplete="tel" placeholder="+628123456789" required maxLength={32} /><p className="mt-1.5 text-xs text-muted-foreground">Include the country code, e.g. +62.</p></div>
              <SelectField name="active" label="Status" options={[{ value: "true", label: "Active" }, { value: "false", label: "Inactive" }]} />
            </div>
            <details className="rounded-lg border p-4"><summary className="cursor-pointer font-medium">Profile details <span className="ml-1 text-xs font-normal text-muted-foreground">Optional</span></summary>
              <div className="mt-4 grid gap-4 sm:grid-cols-2">
                <SelectField name="gender" label="Gender" options={[{ value: "", label: "Not specified" }, "Male", "Female", "Other"]} />
                <FormField name="date_of_birth" label="Date of birth" type="date" />
                <FormField name="place_of_birth" label="Place of birth" maxLength={256} />
                <FormField name="avatar_url" label="Avatar URL" type="url" placeholder="https://…" maxLength={2048} />
              </div>
            </details>
            <details className="rounded-lg border p-4"><summary className="cursor-pointer font-medium">Address <span className="ml-1 text-xs font-normal text-muted-foreground">Optional</span></summary>
              <div className="mt-4 grid gap-4 sm:grid-cols-2">
                <FormField className="sm:col-span-2" name="street_and_number" label="Street and number" autoComplete="street-address" maxLength={256} />
                <FormField name="city" label="City" autoComplete="address-level2" maxLength={256} />
                <FormField name="postal_code" label="Postal code" autoComplete="postal-code" maxLength={256} />
                <FormField name="state" label="State / Province" autoComplete="address-level1" maxLength={256} />
                <FormField name="country" label="Country" autoComplete="country-name" maxLength={256} />
              </div>
            </details>
          </fieldset>
        </div>
        <DialogFooter className="mx-0 mb-0 shrink-0 rounded-b-xl border-t px-6 py-4">
          <Button type="button" variant="outline" disabled={saving} onClick={() => changeOpen(false)}>Cancel</Button>
          <Button type="submit" disabled={saving} aria-busy={saving}>{saving && <Loader2 aria-hidden="true" className="animate-spin motion-reduce:animate-none" />}{saving ? "Creating…" : "Create Site Manager"}</Button>
        </DialogFooter>
      </form>
    </DialogContent>
  </Dialog>;
}
