'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { ArrowLeft, History as HistoryIcon, AlertCircle } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { getReferralHistory } from '@/services/referral/referral.service';

export default function ReferralHistoryPage() {
  const [data, setData] = useState<Awaited<ReturnType<typeof getReferralHistory>>>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const res = await getReferralHistory();
        if (!cancelled) setData(res ?? []);
      } catch (err: any) {
        if (!cancelled) setError(err?.message || 'Failed to load history');
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, []);

  return (
    <div className="space-y-6">
      <Link href="/dashboard/referral" className="inline-flex items-center gap-1 text-sm text-ink-muted hover:text-ink">
        <ArrowLeft className="h-4 w-4" /> Back to Referral Center
      </Link>
      <div>
        <h1 className="text-2xl font-bold tracking-tight text-ink">Referral History</h1>
        <p className="mt-1 text-sm text-ink-muted">Users who signed up through your link</p>
      </div>

      {error && (
        <div className="flex items-center gap-2 rounded-xl border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-600 dark:text-red-300">
          <AlertCircle className="h-4 w-4" /> {error}
        </div>
      )}

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <HistoryIcon className="h-4 w-4" /> All Referrals
          </CardTitle>
          <CardDescription className="mt-1">
            {loading ? 'Loading…' : `${data.length} user(s) referred`}
          </CardDescription>
        </CardHeader>
        <CardContent>
          {loading ? (
            <p className="text-sm text-ink-muted py-4 text-center">Loading…</p>
          ) : data.length === 0 ? (
            <p className="text-sm text-ink-faint py-4 text-center">No referred users yet.</p>
          ) : (
            <div className="divide-y divide-line">
              {data.map((row) => (
                <div key={row.id} className="flex items-center justify-between py-3 text-sm">
                  <div>
                    <p className="font-medium text-ink">
                      {row.referred?.firstName ?? ''} {row.referred?.lastName ?? ''} ({row.referred?.email ?? '—'})
                    </p>
                    <p className="text-xs text-ink-muted">Depth {row.depth ?? 1} · {new Date(row.createdAt).toLocaleDateString()}</p>
                  </div>
                  <span className="text-xs uppercase tracking-wide text-ink-faint">{row.status}</span>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
