'use client';

import { useState } from 'react';
import { AlertTriangle, Loader2, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { api } from '@/lib/api';
import { useAuth } from '@/contexts/AuthContext';
import { cn, formatDate } from '@/lib/utils';

const DEFAULT_GRACE_HOURS = 48;

function formatWhen(iso?: string | null) {
  if (!iso) return '—';
  try {
    return new Date(iso).toLocaleString('en-PH', {
      dateStyle: 'medium',
      timeStyle: 'short',
    });
  } catch {
    return formatDate(iso);
  }
}

export function AccountDeletionCard({ className }: { className?: string }) {
  const { user, refreshUser, logout } = useAuth();
  const [reason, setReason] = useState('');
  const [confirmText, setConfirmText] = useState('');
  const [openForm, setOpenForm] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [info, setInfo] = useState('');

  const scheduledFor =
    typeof user?.deletionScheduledFor === 'string' ? user.deletionScheduledFor : null;
  const requestedAt =
    typeof user?.deletionRequestedAt === 'string' ? user.deletionRequestedAt : null;
  const pending = Boolean(scheduledFor);

  const requestDeletion = async () => {
    if (confirmText.trim().toUpperCase() !== 'DELETE') {
      setError('Type DELETE to confirm.');
      return;
    }
    setLoading(true);
    setError('');
    setInfo('');
    try {
      const res = await api<{
        data: { deletionScheduledFor?: string; graceHours?: number };
        message?: string;
      }>('/users/me/deletion-request', {
        method: 'POST',
        body: JSON.stringify({ reason: reason.trim() || undefined }),
      });
      setInfo(
        res.message ||
          `Removal scheduled in ${res.data.graceHours ?? DEFAULT_GRACE_HOURS} hours.`
      );
      setOpenForm(false);
      setConfirmText('');
      await refreshUser();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Could not schedule removal');
    } finally {
      setLoading(false);
    }
  };

  const cancelDeletion = async () => {
    setLoading(true);
    setError('');
    setInfo('');
    try {
      await api('/users/me/deletion-request', { method: 'DELETE' });
      setInfo('Account removal cancelled. Your account stays active.');
      await refreshUser();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Could not cancel removal');
    } finally {
      setLoading(false);
    }
  };

  return (
    <section
      className={cn(
        'border border-rose-200 bg-rose-50/60',
        className
      )}
    >
      <div className="border-b border-rose-200/80 px-4 py-4 sm:px-5">
        <div className="flex items-start gap-3">
          <div className="flex h-10 w-10 shrink-0 items-center justify-center bg-rose-600 text-white">
            <Trash2 className="h-5 w-5" />
          </div>
          <div className="min-w-0">
            <h3 className="font-bold text-[var(--home-ink)]">Remove account</h3>
            <p className="mt-1 text-sm leading-relaxed text-slate-600">
              Request permanent removal. Your account stays active for{' '}
              <span className="font-semibold">{DEFAULT_GRACE_HOURS} hours</span> so you can
              cancel if this was a mistake. After that, personal details are anonymized and
              the account is closed.
            </p>
          </div>
        </div>
      </div>

      <div className="space-y-3 px-4 py-4 sm:px-5">
        {pending ? (
          <>
            <div className="flex items-start gap-2 border border-amber-200 bg-amber-50 px-3 py-3">
              <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-600" />
              <div className="text-sm text-amber-950">
                <p className="font-semibold">Removal scheduled</p>
                <p className="mt-1">
                  Requested {formatWhen(requestedAt)}. Your account will be removed on{' '}
                  <span className="font-semibold">{formatWhen(scheduledFor)}</span> unless you
                  cancel.
                </p>
              </div>
            </div>
            <div className="flex flex-col gap-2 sm:flex-row">
              <Button
                type="button"
                variant="outline"
                className="rounded-none"
                disabled={loading}
                onClick={cancelDeletion}
              >
                {loading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
                Cancel removal
              </Button>
              <Button
                type="button"
                variant="ghost"
                className="rounded-none text-muted"
                disabled={loading}
                onClick={() => logout()}
              >
                Log out
              </Button>
            </div>
          </>
        ) : openForm ? (
          <div className="space-y-3">
            <div>
              <label className="text-sm font-medium text-slate-700" htmlFor="deletion-reason">
                Reason (optional)
              </label>
              <textarea
                id="deletion-reason"
                value={reason}
                onChange={(e) => setReason(e.target.value)}
                rows={3}
                maxLength={1000}
                placeholder="Tell us why you’re leaving…"
                className="search-input mt-1.5 min-h-[80px] w-full resize-y py-2.5"
              />
            </div>
            <div>
              <label className="text-sm font-medium text-slate-700" htmlFor="deletion-confirm">
                Type <span className="font-bold">DELETE</span> to confirm
              </label>
              <input
                id="deletion-confirm"
                value={confirmText}
                onChange={(e) => setConfirmText(e.target.value)}
                className="search-input mt-1.5 h-10 w-full"
                autoComplete="off"
              />
            </div>
            <div className="flex flex-col gap-2 sm:flex-row">
              <Button
                type="button"
                variant="destructive"
                className="rounded-none"
                disabled={loading}
                onClick={requestDeletion}
              >
                {loading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
                Schedule removal
              </Button>
              <Button
                type="button"
                variant="outline"
                className="rounded-none"
                disabled={loading}
                onClick={() => {
                  setOpenForm(false);
                  setConfirmText('');
                  setError('');
                }}
              >
                Never mind
              </Button>
            </div>
          </div>
        ) : (
          <Button
            type="button"
            variant="outline"
            className="rounded-none border-rose-300 text-rose-700 hover:bg-rose-100"
            onClick={() => setOpenForm(true)}
          >
            Request account removal
          </Button>
        )}

        {error ? <p className="text-sm text-red-600">{error}</p> : null}
        {info ? <p className="text-sm text-emerald-700">{info}</p> : null}
      </div>
    </section>
  );
}
