"use client";

import { useState, type FormEvent } from "react";
import { Button } from "@/components/ui/button";
import { FormField } from "@/components/shared/form-field";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import type { OrganizationRecord, OrganizationWriteValues } from "./types";

function writeValuesFrom(organization?: OrganizationRecord): OrganizationWriteValues {
  return {
    code: organization?.code ?? "",
    name: organization?.name ?? "",
    phone: organization?.phone ?? "",
    email: organization?.email ?? "",
  };
}

export function OrganizationEditorDialog({
  organization,
  onOpenChange,
  onSave,
}: {
  organization: OrganizationRecord | null;
  onOpenChange(open: boolean): void;
  onSave(values: OrganizationWriteValues): Promise<boolean>;
}) {
  const [draft, setDraft] = useState<OrganizationWriteValues>(() => writeValuesFrom(organization ?? undefined));
  const [saving, setSaving] = useState(false);

  function update<K extends keyof OrganizationWriteValues>(key: K, value: OrganizationWriteValues[K]) {
    setDraft((current) => ({ ...current, [key]: value }));
  }

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setSaving(true);
    try {
      const values = {
        code: draft.code.trim(),
        name: draft.name.trim(),
        phone: draft.phone.trim(),
        email: draft.email.trim(),
      };
      if (await onSave(values)) onOpenChange(false);
    } finally {
      setSaving(false);
    }
  }

  return (
    <Dialog open onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-2xl">
        <DialogHeader>
          <DialogTitle>{organization ? "Edit Organization" : "Create Organization"}</DialogTitle>
          <DialogDescription>
            {organization
              ? "Update the organization contact details."
              : "Create an organization for this tenant."}{" "}
            Tenant scope comes from your account and is not editable here.
          </DialogDescription>
        </DialogHeader>

        <form className="space-y-6" onSubmit={submit}>
          <div className="grid gap-4 sm:grid-cols-2">
            <FormField
              name="organization-code"
              label="Code"
              required
              value={draft.code}
              onChange={(event) => update("code", event.target.value)}
              placeholder="organization-code"
            />
            <FormField
              name="organization-name"
              label="Name"
              required
              value={draft.name}
              onChange={(event) => update("name", event.target.value)}
              placeholder="Organization name"
            />
            <FormField
              name="organization-phone"
              label="Phone"
              value={draft.phone}
              onChange={(event) => update("phone", event.target.value)}
              placeholder="+62 812-3456-7890"
            />
            <FormField
              name="organization-email"
              label="Email"
              type="email"
              value={draft.email}
              onChange={(event) => update("email", event.target.value)}
              placeholder="contact@example.com"
            />
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" disabled={saving} onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
            <Button type="submit" disabled={saving}>
              {saving ? "Saving…" : organization ? "Save Changes" : "Create Organization"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
