"use client";

import { useCallback, useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { useAuth } from "@/components/auth/AuthProvider";
import { Button } from "@/components/Button";
import { ApiError, authApi } from "@/lib/api";
import { ConfirmDialog } from "@/components/ui/ConfirmDialog";
import { PageHeader } from "@/components/ui/PageHeader";
import {
  ACCOUNT_DELETION_DANGER_ZONE,
  ACCOUNT_DELETION_REDIRECT_PATH,
  ACCOUNT_DELETION_SUCCESS_MESSAGE,
  accountDeletionErrorMessage,
  beginAccountDeletionSubmit,
  cancelAccountDeletionDialog,
  initialAccountDeletionDialogState,
  openAccountDeletionDialog,
  type AccountDeletionDialogState,
} from "@/lib/account-deletion";
import { DashboardShell } from "./DashboardShell";

export function DashboardSettingsPage() {
  return (
    <DashboardShell title="Settings">
      {() => <SettingsContent />}
    </DashboardShell>
  );
}

function SettingsContent() {
  const router = useRouter();
  const { setUser, user } = useAuth();
  const [dialogState, setDialogState] = useState<AccountDeletionDialogState>(
    initialAccountDeletionDialogState,
  );
  const [error, setError] = useState("");

  const busy = dialogState === "submitting";

  const onCancel = useCallback(() => {
    setDialogState((current) => cancelAccountDeletionDialog(current));
    setError("");
  }, []);

  const onConfirm = useCallback(async () => {
    let canSubmit = false;

    setDialogState((current) => {
      const next = beginAccountDeletionSubmit(current);
      canSubmit = next !== null;
      return next ?? current;
    });

    if (!canSubmit) {
      return;
    }

    setError("");

    try {
      await authApi.deleteAccount();
      setUser(null);
      toast.success(ACCOUNT_DELETION_SUCCESS_MESSAGE);
      router.replace(ACCOUNT_DELETION_REDIRECT_PATH);
    } catch (caught) {
      const status = caught instanceof ApiError ? caught.status : null;
      setError(accountDeletionErrorMessage(status));
      setDialogState("error");
    }
  }, [router, setUser]);

  return (
    <div className="mx-auto w-full max-w-2xl space-y-8 px-4 py-8 sm:px-6">
      <PageHeader description="Manage account security and deletion options for your Postvertise account." />

      {user?.account_type === "creator" ? (
        <>
          <section
            aria-labelledby="rates-settings-heading"
            className="rounded-pv border border-line bg-surface p-5"
          >
            <h2 id="rates-settings-heading" className="text-sm font-semibold text-primary">
              Creator Rates
            </h2>
            <p className="mt-2 text-[0.8125rem] text-ink-60">
              Set prices for the deliverable types you offer.
            </p>
            <div className="mt-4">
              <Button type="button" size="sm" variant="secondary" href="/dashboard/settings/rates">
                Manage rates
              </Button>
            </div>
          </section>

          <section
            aria-labelledby="payout-settings-heading"
            className="rounded-pv border border-line bg-surface p-5"
          >
            <h2 id="payout-settings-heading" className="text-sm font-semibold text-primary">
              Payouts
            </h2>
            <p className="mt-2 text-[0.8125rem] text-ink-60">
              Set up your payout account for campaign payments.
            </p>
            <div className="mt-4">
              <Button type="button" size="sm" variant="secondary" href="/dashboard/settings/payouts">
                Manage payouts
              </Button>
            </div>
          </section>
        </>
      ) : null}

      {user?.account_type === "brand" ? (
        <section
          aria-labelledby="billing-settings-heading"
          className="rounded-pv border border-line bg-surface p-5"
        >
          <h2 id="billing-settings-heading" className="text-sm font-semibold text-primary">
            Billing address
          </h2>
          <p className="mt-2 text-[0.8125rem] text-ink-60">
            Used for tax calculation on campaign charges. Not taken from audience targeting.
          </p>
          <div className="mt-4">
            <Button type="button" size="sm" variant="secondary" href="/dashboard/settings/billing">
              Manage billing address
            </Button>
          </div>
        </section>
      ) : null}

      <section
        aria-labelledby="danger-zone-heading"
        className="rounded-pv border border-red-200 bg-red-50/40 p-5"
      >
        <h2 id="danger-zone-heading" className="text-sm font-semibold text-primary">
          {ACCOUNT_DELETION_DANGER_ZONE.title}
        </h2>
        <h3 className="mt-3 text-[0.9375rem] font-semibold text-primary">
          {ACCOUNT_DELETION_DANGER_ZONE.heading}
        </h3>
        <ul className="mt-3 list-disc space-y-1.5 pl-5 text-[0.8125rem] text-ink-60">
          {ACCOUNT_DELETION_DANGER_ZONE.bullets.map((bullet) => (
            <li key={bullet}>{bullet}</li>
          ))}
        </ul>
        {error ? (
          <p className="mt-3 text-[0.8125rem] text-red-700" role="alert">
            {error}
          </p>
        ) : null}
        <div className="mt-4">
          <Button
            type="button"
            size="sm"
            variant="secondary"
            className="border-red-300 text-red-700 hover:border-red-700"
            onClick={() => setDialogState((current) => openAccountDeletionDialog(current))}
          >
            Delete account
          </Button>
        </div>
      </section>

      {dialogState === "confirming" || dialogState === "submitting" || dialogState === "error" ? (
        <ConfirmDialog
          title={ACCOUNT_DELETION_DANGER_ZONE.confirmTitle}
          description={ACCOUNT_DELETION_DANGER_ZONE.confirmDescription}
          confirmLabel={ACCOUNT_DELETION_DANGER_ZONE.confirmLabel}
          busy={busy}
          busyLabel="Deleting…"
          onCancel={onCancel}
          onConfirm={() => {
            void onConfirm();
          }}
        />
      ) : null}
    </div>
  );
}
