'use client';

import { useRouter } from 'next/navigation';
import { useState, useTransition } from 'react';

export function DeleteAccountButton() {
  const router = useRouter();
  const [pending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);

  function handleClick() {
    if (
      !window.confirm(
        'Permanently delete your TOWER account? This cannot be undone.',
      )
    ) {
      return;
    }
    setError(null);
    startTransition(async () => {
      const res = await fetch('/api/my/account', { method: 'DELETE' });
      if (!res.ok) {
        const body = (await res.json().catch(() => ({}))) as { message?: string };
        setError(body.message ?? 'Delete failed');
        return;
      }
      router.replace('/');
    });
  }

  return (
    <div className="flex flex-col items-start gap-1">
      <button
        type="button"
        onClick={handleClick}
        disabled={pending}
        className="rounded border border-red-300 bg-white px-3 py-1.5 text-sm text-red-700 hover:bg-red-50 disabled:opacity-50"
      >
        {pending ? 'Deleting…' : 'Delete my account'}
      </button>
      {error && <span className="text-xs text-red-700">{error}</span>}
    </div>
  );
}
