"use client";

import { useState, type FormEvent } from "react";
import { Button, Dialog, Field, Input } from "@/components/ui/kit";
import { useToast } from "@/components/ui/toast";
import { api, ApiError } from "@/lib/api";
import type { WhatsAppAccount, WhatsAppConfig } from "@/lib/types";

/** Connect a number, or (with `account`) replace its access token. Mounted only while open. */
export function ConnectDialog({
  account,
  prefill,
  config,
  onClose,
  onDone,
}: {
  account?: WhatsAppAccount;
  prefill?: { waba_id: string; phone_number_id: string };
  config: WhatsAppConfig | null;
  onClose: () => void;
  onDone: (a: WhatsAppAccount) => void;
}) {
  const toast = useToast();
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [saving, setSaving] = useState(false);
  const rotating = Boolean(account);

  async function submit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const body = Object.fromEntries(new FormData(e.currentTarget)) as Record<string, string>;
    setSaving(true);
    setErrors({});
    try {
      const res = rotating
        ? await api.patch<{ data: WhatsAppAccount }>(`/whatsapp/accounts/${account!.id}/credentials`, body)
        : await api.post<{ data: WhatsAppAccount }>("/whatsapp/accounts", body);
      toast("success", rotating ? "Credentials updated" : `Connected ${res.data.display_phone_number ?? "number"}`);
      onDone(res.data);
    } catch (err) {
      if (err instanceof ApiError && Object.keys(err.fields).length) setErrors(err.fields);
      else toast("error", (err as Error).message);
    } finally {
      setSaving(false);
    }
  }

  return (
    <Dialog
      open
      onClose={onClose}
      title={rotating ? "Update credentials" : "Connect a WhatsApp number"}
      description={rotating ? `For ${account!.display_phone_number}. We check the new token with Meta before saving it.` : "We check these details with Meta before saving anything."}
      size="lg"
      footer={
        <>
          <Button onClick={onClose}>Cancel</Button>
          <Button variant="primary" type="submit" form="wa-connect" loading={saving}>
            {rotating ? "Save credentials" : "Connect number"}
          </Button>
        </>
      }
    >
      {!rotating && (
        <ol className="mb-6 space-y-3 rounded-lg bg-paper p-4 text-sm text-muted">
          {[
            <>
              In <span className="font-medium text-text">Meta for Developers</span>, create a Business app and add the WhatsApp product. Your business must own the phone number.
            </>,
            <>
              In <span className="font-medium text-text">Business settings › System users</span>, generate a permanent token for the app with the{" "}
              <code className="text-teal">whatsapp_business_messaging</code> and <code className="text-teal">whatsapp_business_management</code> permissions.
            </>,
            <>
              From the app&apos;s <span className="font-medium text-text">WhatsApp › API Setup</span> page, copy the WhatsApp Business Account ID and the Phone number ID. The app secret is under <span className="font-medium text-text">App settings › Basic</span>.
            </>,
          ].map((step, i) => (
            <li key={i} className="flex gap-3">
              <span className="tabular grid size-6 shrink-0 place-items-center rounded-full bg-white text-xs font-semibold text-teal ring-1 ring-inset ring-line">{i + 1}</span>
              <span className="pt-0.5">{step}</span>
            </li>
          ))}
        </ol>
      )}
      <form id="wa-connect" onSubmit={submit} noValidate className="space-y-4">
        {!rotating && (
          <div className="grid gap-4 sm:grid-cols-2">
            <Field label="WhatsApp Business Account ID" htmlFor="wa-waba" error={errors.waba_id}>
              <Input id="wa-waba" name="waba_id" inputMode="numeric" className="tabular" defaultValue={prefill?.waba_id} invalid={!!errors.waba_id} autoFocus />
            </Field>
            <Field label="Phone number ID" htmlFor="wa-phone" error={errors.phone_number_id} hint="Not the phone number itself.">
              <Input id="wa-phone" name="phone_number_id" inputMode="numeric" className="tabular" defaultValue={prefill?.phone_number_id} invalid={!!errors.phone_number_id} />
            </Field>
          </div>
        )}
        <Field label="Permanent access token" htmlFor="wa-token" error={errors.access_token} hint="Stored encrypted. It is never shown again or sent to your browser.">
          <Input id="wa-token" name="access_token" type="password" autoComplete="off" spellCheck={false} invalid={!!errors.access_token} autoFocus={rotating} />
        </Field>
        <Field
          label="App secret"
          htmlFor="wa-secret"
          optional={rotating}
          error={errors.app_secret}
          hint={rotating ? "Leave blank to keep the current one." : "Used to confirm that webhook notifications really come from Meta."}
        >
          <Input id="wa-secret" name="app_secret" type="password" autoComplete="off" spellCheck={false} invalid={!!errors.app_secret} />
        </Field>
        {config?.mode === "simulation" && !rotating && (
          <p className="rounded-md bg-amber-soft px-3 py-2 text-[13px] text-amber">
            Simulation mode: any numeric IDs work, the token needs 20+ characters, and the app secret any 32 hex characters (for example 32 letter a&apos;s).
          </p>
        )}
      </form>
    </Dialog>
  );
}
