'use client';

import { useEffect, useState } from 'react';
import { FightCard, EmptyState } from '@/components/vyndr';
import type { FighterTape } from '@/components/vyndr';

interface RawFighter {
  id?: string | null;
  name: string;
  record?: { display?: string | null; wins?: number | null; losses?: number | null; draws?: number | null } | null;
  stance?: string | null;
  reach?: string | number | null;
  blend?: { archetype: string; weight: number }[] | null;
  pedigrees?: string[] | null;
}
interface RawBout {
  id?: string | null;
  weightClass?: string | null;
  rounds?: number | null;
  status?: string | null;
  fighters: RawFighter[];
  odds?: { moneyline?: { home?: number | null; away?: number | null } | null; roundTotal?: { line?: number | null; over?: number | null; under?: number | null } | null } | null;
  verdict?: { verdict: string; edgeSide?: 'a' | 'b' | null; summary?: string } | null;
}
interface RawEvent {
  id?: string | null;
  name?: string | null;
  shortName?: string | null;
  date?: string | null;
  venue?: string | null;
  bouts: RawBout[];
}

export default function FightCardClient({ id }: { id: string }) {
  const [event, setEvent] = useState<RawEvent | null>(null);
  const [state, setState] = useState<'loading' | 'ready' | 'empty'>('loading');

  useEffect(() => {
    let active = true;
    fetch(`/api/fight/${encodeURIComponent(id)}`, { headers: { Accept: 'application/json' } })
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => {
        if (!active) return;
        const ev: RawEvent | null = d && d.event ? d.event : null;
        if (ev && Array.isArray(ev.bouts) && ev.bouts.length > 0) {
          setEvent(ev);
          setState('ready');
        } else {
          setState('empty');
        }
      })
      .catch(() => { if (active) setState('empty'); });
    return () => { active = false; };
  }, [id]);

  if (state === 'loading') {
    return (
      <div className="mono" style={{ padding: '80px 24px', textAlign: 'center', color: 'var(--text-2)', letterSpacing: '0.2em', fontSize: 12 }}>
        LOADING THE CARD…
      </div>
    );
  }

  if (state === 'empty' || !event) {
    return (
      <EmptyState
        code="NO CARD SCHEDULED"
        title="No fight card here"
        message="The octagon is dark right now. Combat cards post the week of a UFC event — check back closer to fight night."
        actions={[{ label: 'BACK TO THE SLATE', href: '/dashboard', primary: true }]}
      />
    );
  }

  const dateStr = event.date ? new Date(event.date).toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' }) : null;

  return (
    <div style={{ maxWidth: 680, margin: '0 auto', padding: '24px 16px 80px' }}>
      <header style={{ marginBottom: 20 }}>
        <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', color: 'var(--text-2)', marginBottom: 6 }}>
          {[event.shortName, dateStr, event.venue].filter(Boolean).join(' · ') || 'UFC'}
        </div>
        <h1 style={{ fontSize: 24, fontWeight: 800, letterSpacing: '-0.02em', margin: 0, color: 'var(--text-0)' }}>
          {event.name || 'Fight Card'}
        </h1>
      </header>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {event.bouts.map((bout, i) => {
          const fighters: FighterTape[] = (bout.fighters || []).slice(0, 2).map((f) => ({
            id: f.id,
            name: f.name,
            record: f.record,
            stance: f.stance,
            reach: f.reach,
            blend: f.blend,
            pedigrees: f.pedigrees,
          }));
          return (
            <FightCard
              key={bout.id || `${i}`}
              weightClass={bout.weightClass}
              rounds={bout.rounds}
              status={bout.status}
              fighters={fighters}
              odds={bout.odds}
              verdict={bout.verdict}
            />
          );
        })}
      </div>
    </div>
  );
}
