'use client';

import { useState, useEffect } from 'react';
import { TournamentHistory } from '@/lib/types';
import { formatCurrency } from '@/lib/prize-pool';

export default function HistoryPage() {
  const [history, setHistory] = useState<TournamentHistory[]>([]);
  const [loading, setLoading] = useState(true);
  const [expanded, setExpanded] = useState<string | null>(null);

  useEffect(() => {
    fetch('/api/history')
      .then((r) => r.json())
      .then((data) => {
        setHistory(data);
        setLoading(false);
      });
  }, []);

  const handleDelete = async (id: string) => {
    if (!confirm('Delete this history record?')) return;
    await fetch(`/api/history?id=${id}`, { method: 'DELETE' });
    setHistory((h) => h.filter((r) => r.id !== id));
  };

  const handleExportCSV = () => {
    window.open('/api/export?type=history&format=csv', '_blank');
  };

  const handleExportPDF = (id: string) => {
    window.open(`/api/export?type=history&format=pdf&id=${id}`, '_blank');
  };

  return (
    <div className="max-w-5xl mx-auto px-4 py-8">
      <div className="flex flex-wrap items-center justify-between gap-4 mb-6">
        <h1 className="text-3xl font-display font-bold text-poker-gold">Tournament History</h1>
        <button onClick={handleExportCSV} className="btn-secondary">
          Export All CSV
        </button>
      </div>

      {loading ? (
        <p className="text-white/60">Loading...</p>
      ) : history.length === 0 ? (
        <div className="card text-center py-12">
          <p className="text-white/60">No tournament history yet. Finish a tournament to see it here.</p>
        </div>
      ) : (
        <div className="space-y-4">
          {history.map((record) => (
            <div key={record.id} className="card">
              <div
                className="flex flex-wrap items-center justify-between gap-4 cursor-pointer"
                onClick={() => setExpanded(expanded === record.id ? null : record.id)}
              >
                <div>
                  <h2 className="text-xl font-semibold text-poker-gold">{record.name}</h2>
                  <p className="text-white/60 text-sm">
                    {record.date} · {record.type} · Buy-in {formatCurrency(record.buyIn)}
                  </p>
                </div>
                <div className="flex gap-6 text-center">
                  <div>
                    <div className="text-lg font-bold">{record.entries}</div>
                    <div className="text-xs text-white/50">Entries</div>
                  </div>
                  <div>
                    <div className="text-lg font-bold text-green-400">{formatCurrency(record.prizePool)}</div>
                    <div className="text-xs text-white/50">Pool</div>
                  </div>
                  <div>
                    <div className="text-lg font-bold">{record.rebuys}</div>
                    <div className="text-xs text-white/50">Rebuys</div>
                  </div>
                  <div>
                    <div className="text-lg font-bold">{record.addons}</div>
                    <div className="text-xs text-white/50">Addons</div>
                  </div>
                </div>
              </div>

              {expanded === record.id && (
                <div className="mt-4 pt-4 border-t border-white/10">
                  <h3 className="font-semibold mb-3">Winners</h3>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-3 mb-4">
                    {record.winners.map((w) => (
                      <div key={w.place} className="bg-white/5 rounded-lg p-3 flex justify-between">
                        <span>
                          {w.place === 1 ? '🥇' : w.place === 2 ? '🥈' : w.place === 3 ? '🥉' : `#${w.place}`} {w.name}
                        </span>
                        <span className="font-bold text-green-400">{formatCurrency(w.amount)}</span>
                      </div>
                    ))}
                  </div>
                  <div className="flex gap-2">
                    <button onClick={() => handleExportPDF(record.id)} className="btn-secondary text-sm">
                      Export PDF
                    </button>
                    <button onClick={() => handleDelete(record.id)} className="btn-danger text-sm">
                      Delete
                    </button>
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}