"use client";

import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import type { ActionResult } from "@/app/dashboard/actions";

type AccountSettingsFormProps = {
  name: string;
  email: string;
  pendingEmail: string | null;
  phone: string;
  emailVerifiedAt: string | null;
  updateProfileAction: (formData: FormData) => Promise<ActionResult>;
  requestEmailChangeAction: (formData: FormData) => Promise<ActionResult>;
  resendEmailChangeAction: () => Promise<ActionResult>;
  cancelEmailChangeAction: () => Promise<ActionResult>;
};

export function AccountSettingsForm(props: AccountSettingsFormProps) {
  const router = useRouter();
  const [profileError, setProfileError] = useState<string | null>(null);
  const [profileSaved, setProfileSaved] = useState(false);
  const [emailError, setEmailError] = useState<string | null>(null);
  const [emailSaved, setEmailSaved] = useState(false);
  const [pending, startTransition] = useTransition();

  const verifiedLabel = props.emailVerifiedAt
    ? `Verified ${new Date(props.emailVerifiedAt).toLocaleDateString(undefined, {
        year: "numeric",
        month: "short",
        day: "numeric",
      })}`
    : "Not verified yet";

  return (
    <div className="space-y-6">
      <section className="archi-panel space-y-5 p-5 sm:p-6">
        <div className="border-b border-[var(--archi-line)] pb-4">
          <p className="text-[0.65rem] tracking-[0.2em] text-[var(--archi-ink-muted)] uppercase">
            Account
          </p>
          <h2 className="mt-2 font-[family-name:var(--font-display)] text-xl tracking-tight sm:text-2xl">
            Login profile
          </h2>
          <p className="mt-2 text-sm leading-6 text-[var(--archi-ink-muted)]">
            Private to you. Public studio contact stays in the studio profile
            form.
          </p>
        </div>

        <form
          className="space-y-4"
          action={(formData) => {
            setProfileError(null);
            setProfileSaved(false);
            startTransition(async () => {
              const result = await props.updateProfileAction(formData);
              if (!result.ok) {
                setProfileError(result.error);
                return;
              }
              setProfileSaved(true);
              router.refresh();
            });
          }}
        >
          <div className="grid gap-4 sm:grid-cols-2">
            <label className="block text-sm">
              <span className="mb-1.5 block text-[0.7rem] tracking-[0.14em] text-[var(--archi-ink-muted)] uppercase">
                Display name
              </span>
              <input
                name="name"
                required
                defaultValue={props.name}
                className="archi-input"
                autoComplete="name"
              />
            </label>
            <label className="block text-sm">
              <span className="mb-1.5 block text-[0.7rem] tracking-[0.14em] text-[var(--archi-ink-muted)] uppercase">
                Phone
              </span>
              <input
                name="phone"
                defaultValue={props.phone}
                className="archi-input"
                autoComplete="tel"
                placeholder="+255…"
              />
            </label>
          </div>

          <div className="rounded-sm border border-[var(--archi-line)] bg-white/50 px-4 py-3">
            <p className="text-[0.65rem] tracking-[0.16em] text-[var(--archi-ink-muted)] uppercase">
              Active login email
            </p>
            <p className="mt-1 truncate text-sm font-medium">{props.email}</p>
            <p
              className={`mt-1 text-xs ${
                props.emailVerifiedAt
                  ? "text-[var(--archi-ink)]"
                  : "text-[var(--archi-ink-muted)]"
              }`}
            >
              {verifiedLabel}
            </p>
          </div>

          {profileError ? (
            <p className="text-sm text-red-700" role="alert">
              {profileError}
            </p>
          ) : null}
          {profileSaved ? (
            <p className="text-sm text-[var(--archi-gold)]" role="status">
              Account details saved
            </p>
          ) : null}

          <button
            type="submit"
            disabled={pending}
            className="archi-btn-primary disabled:opacity-60"
          >
            {pending ? "Saving…" : "Save account"}
          </button>
        </form>
      </section>

      <section className="archi-panel space-y-5 p-5 sm:p-6">
        <div className="border-b border-[var(--archi-line)] pb-4">
          <p className="text-[0.65rem] tracking-[0.2em] text-[var(--archi-ink-muted)] uppercase">
            Security
          </p>
          <h2 className="mt-2 font-[family-name:var(--font-display)] text-xl tracking-tight">
            Change login email
          </h2>
          <p className="mt-2 text-sm leading-6 text-[var(--archi-ink-muted)]">
            Your current email stays active until you confirm the new address
            from the verification link.
          </p>
        </div>

        {props.pendingEmail ? (
          <div className="space-y-4 border border-[var(--archi-line)] bg-[var(--archi-gold-soft)] px-4 py-4">
            <div>
              <p className="text-[0.65rem] tracking-[0.16em] text-[var(--archi-ink-muted)] uppercase">
                Pending verification
              </p>
              <p className="mt-1 text-sm font-medium">{props.pendingEmail}</p>
              <p className="mt-2 text-xs leading-5 text-[var(--archi-ink-muted)]">
                Check that inbox for a confirmation link. With{" "}
                <code className="text-[0.7rem]">EMAIL_PROVIDER=console</code>,
                the link is printed in the server logs.
              </p>
            </div>
            <div className="flex flex-wrap gap-2">
              <button
                type="button"
                disabled={pending}
                className="archi-btn-primary disabled:opacity-60"
                onClick={() => {
                  setEmailError(null);
                  setEmailSaved(false);
                  startTransition(async () => {
                    const result = await props.resendEmailChangeAction();
                    if (!result.ok) {
                      setEmailError(result.error);
                      return;
                    }
                    setEmailSaved(true);
                    router.refresh();
                  });
                }}
              >
                Send again
              </button>
              <button
                type="button"
                disabled={pending}
                className="inline-flex items-center justify-center border border-[var(--archi-line)] bg-white px-4 py-2 text-sm disabled:opacity-60"
                onClick={() => {
                  setEmailError(null);
                  setEmailSaved(false);
                  startTransition(async () => {
                    const result = await props.cancelEmailChangeAction();
                    if (!result.ok) {
                      setEmailError(result.error);
                      return;
                    }
                    router.refresh();
                  });
                }}
              >
                Cancel change
              </button>
            </div>
          </div>
        ) : (
          <form
            className="space-y-4"
            action={(formData) => {
              setEmailError(null);
              setEmailSaved(false);
              startTransition(async () => {
                const result = await props.requestEmailChangeAction(formData);
                if (!result.ok) {
                  setEmailError(result.error);
                  return;
                }
                setEmailSaved(true);
                router.refresh();
              });
            }}
          >
            <label className="block text-sm">
              <span className="mb-1.5 block text-[0.7rem] tracking-[0.14em] text-[var(--archi-ink-muted)] uppercase">
                New email
              </span>
              <input
                name="newEmail"
                type="email"
                required
                className="archi-input"
                autoComplete="email"
              />
            </label>
            <label className="block text-sm">
              <span className="mb-1.5 block text-[0.7rem] tracking-[0.14em] text-[var(--archi-ink-muted)] uppercase">
                Current password
              </span>
              <input
                name="currentPassword"
                type="password"
                required
                minLength={12}
                className="archi-input"
                autoComplete="current-password"
              />
            </label>
            <button
              type="submit"
              disabled={pending}
              className="archi-btn-primary disabled:opacity-60"
            >
              {pending ? "Sending…" : "Send verification link"}
            </button>
          </form>
        )}

        {emailError ? (
          <p className="text-sm text-red-700" role="alert">
            {emailError}
          </p>
        ) : null}
        {emailSaved ? (
          <p className="text-sm text-[var(--archi-gold)]" role="status">
            Verification email sent
          </p>
        ) : null}
      </section>
    </div>
  );
}
