'use client';

import { useState, useEffect } from 'react';
import { Users, Gift, CheckCircle2, Clock } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { apiListReferrals, type ApiReferral, type ReferralStats } from '@/lib/api';

const statusConfig: Record<string, { label: string; color: string; icon: typeof CheckCircle2 }> = {
  pending: { label: 'Pending', color: 'bg-slate-50 text-slate-600', icon: Clock },
  signed_up: { label: 'Signed Up', color: 'bg-blue-50 text-blue-700', icon: CheckCircle2 },
  subscribed: { label: 'Subscribed', color: 'bg-emerald-50 text-emerald-700', icon: Gift },
  rewarded: { label: 'Rewarded', color: 'bg-purple-50 text-purple-700', icon: Gift },
};

function formatDate(iso: string) {
  return new Date(iso).toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  });
}

export default function ReferralsPage() {
  const [referrals, setReferrals] = useState<ApiReferral[]>([]);
  const [stats, setStats] = useState<ReferralStats>({ total: 0, completed: 0, rewarded: 0 });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function load() {
      setLoading(true);
      const { data } = await apiListReferrals();
      if (data) {
        setReferrals(data.referrals);
        setStats(data.stats);
      }
      setLoading(false);
    }
    load();
  }, []);

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Referral Program</h1>
        <p className="text-sm text-muted-foreground">
          Track user referrals and rewards across the platform
        </p>
      </div>

      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Total Referrals
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.total}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Completed</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.completed}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Rewarded</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.rewarded}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Conversion Rate
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {stats.total > 0 ? `${Math.round((stats.completed / stats.total) * 100)}%` : '—'}
            </div>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardContent className="p-0">
          {loading ? (
            <div className="p-8 text-center text-muted-foreground">Loading...</div>
          ) : referrals.length === 0 ? (
            <div className="p-8 text-center text-muted-foreground">
              <Users className="mx-auto mb-2 h-8 w-8 opacity-40" />
              No referrals yet. Users can share their referral links from the portal.
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Referrer</TableHead>
                  <TableHead>Referred Email</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Referrer Reward</TableHead>
                  <TableHead>Referred Reward</TableHead>
                  <TableHead>Created</TableHead>
                  <TableHead>Completed</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {referrals.map(ref => {
                  const cfg = statusConfig[ref.status] || statusConfig.pending;
                  const StatusIcon = cfg.icon;
                  return (
                    <TableRow key={ref.id}>
                      <TableCell className="text-sm">{ref.referrerEmail}</TableCell>
                      <TableCell className="text-sm">{ref.referredEmail}</TableCell>
                      <TableCell>
                        <Badge className={`${cfg.color} border-0 gap-1`}>
                          <StatusIcon className="h-3 w-3" />
                          {cfg.label}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <span className="text-sm">
                          {ref.referrerRewardTokens.toLocaleString()} tokens
                          {ref.referrerRewarded && (
                            <CheckCircle2 className="inline ml-1 h-3.5 w-3.5 text-emerald-600" />
                          )}
                        </span>
                      </TableCell>
                      <TableCell>
                        <span className="text-sm">
                          {ref.referredRewardTokens.toLocaleString()} tokens
                          {ref.referredRewarded && (
                            <CheckCircle2 className="inline ml-1 h-3.5 w-3.5 text-emerald-600" />
                          )}
                        </span>
                      </TableCell>
                      <TableCell className="text-muted-foreground text-xs">
                        {formatDate(ref.createdAt)}
                      </TableCell>
                      <TableCell className="text-muted-foreground text-xs">
                        {ref.completedAt ? formatDate(ref.completedAt) : '—'}
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
