'use client';

import React, { useState, useEffect } from 'react';
import { TrendingUp, Loader2, RefreshCw, Trophy, Calendar } from 'lucide-react';

interface CategoryWidgetsProps {
  category: string;
}

interface CurrencyData {
  USD: number;
  EUR: number;
  GBP: number;
}

interface TeamStanding {
  pos: number;
  team: string;
  played: number;
  points: number;
  logo?: string;
}

interface Match {
  home: string;
  away: string;
  date: string;
  time: string;
  homeLogo?: string;
  awayLogo?: string;
}

// Döviz kurlarını çek
async function fetchCurrencyRates(): Promise<CurrencyData | null> {
  try {
    const response = await fetch('https://open.er-api.com/v6/latest/TRY');
    if (response.ok) {
      const data = await response.json();
      return {
        USD: 1 / data.rates.USD,
        EUR: 1 / data.rates.EUR,
        GBP: 1 / data.rates.GBP,
      };
    }
    return null;
  } catch {
    return null;
  }
}

// Süper Lig puan durumunu çek (TheSportsDB API)
async function fetchLeagueTable(): Promise<TeamStanding[]> {
  try {
    // TheSportsDB - Türkiye Süper Lig (ID: 4339)
    const response = await fetch(
      'https://www.thesportsdb.com/api/v1/json/3/lookuptable.php?l=4339&s=2024-2025'
    );

    if (!response.ok) return [];

    const data = await response.json();
    if (!data.table) return [];

    return data.table.slice(0, 8).map((team: { intRank: number; strTeam: string; intPlayed: number; intPoints: number; strBadge: string }) => ({
      pos: team.intRank,
      team: team.strTeam,
      played: team.intPlayed,
      points: team.intPoints,
      logo: team.strBadge,
    }));
  } catch {
    return [];
  }
}

// Süper Lig fikstürünü çek
async function fetchNextMatches(): Promise<Match[]> {
  try {
    // TheSportsDB - Sonraki maçlar
    const response = await fetch(
      'https://www.thesportsdb.com/api/v1/json/3/eventsnextleague.php?id=4339'
    );

    if (!response.ok) return [];

    const data = await response.json();
    if (!data.events) return [];

    return data.events.slice(0, 4).map((event: { strHomeTeam: string; strAwayTeam: string; dateEvent: string; strTime: string; strHomeTeamBadge: string; strAwayTeamBadge: string }) => {
      const date = new Date(event.dateEvent);
      const options: Intl.DateTimeFormatOptions = { day: 'numeric', month: 'short' };
      return {
        home: event.strHomeTeam,
        away: event.strAwayTeam,
        date: date.toLocaleDateString('tr-TR', options),
        time: event.strTime?.substring(0, 5) || 'TBA',
        homeLogo: event.strHomeTeamBadge,
        awayLogo: event.strAwayTeamBadge,
      };
    });
  } catch {
    return [];
  }
}

export default function CategoryWidgets({ category }: CategoryWidgetsProps) {
  const [currencies, setCurrencies] = useState<CurrencyData | null>(null);
  const [standings, setStandings] = useState<TeamStanding[]>([]);
  const [matches, setMatches] = useState<Match[]>([]);
  const [loading, setLoading] = useState(false);
  const [lastUpdate, setLastUpdate] = useState<string>('');

  // Verileri yükle
  useEffect(() => {
    if (category === 'Ekonomi') {
      loadCurrencies();
    } else if (category === 'Spor') {
      loadSportsData();
    }
  }, [category]);

  const loadCurrencies = async () => {
    setLoading(true);
    const data = await fetchCurrencyRates();
    if (data) {
      setCurrencies(data);
      setLastUpdate(new Date().toLocaleTimeString('tr-TR', { hour: '2-digit', minute: '2-digit' }));
    }
    setLoading(false);
  };

  const loadSportsData = async () => {
    setLoading(true);
    const [tableData, matchData] = await Promise.all([
      fetchLeagueTable(),
      fetchNextMatches(),
    ]);
    setStandings(tableData);
    setMatches(matchData);
    setLastUpdate(new Date().toLocaleTimeString('tr-TR', { hour: '2-digit', minute: '2-digit' }));
    setLoading(false);
  };

  // Ekonomi kategorisi
  if (category === 'Ekonomi') {
    return (
      <div className="bg-white rounded-2xl border border-gray-100 overflow-hidden shadow-sm">
        <div className="bg-gradient-to-r from-amber-500 to-orange-500 px-4 py-3 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <TrendingUp size={18} className="text-white" />
            <h3 className="font-bold text-white text-sm">Döviz Kurları</h3>
          </div>
          <button
            onClick={loadCurrencies}
            disabled={loading}
            className="p-1 hover:bg-white/20 rounded transition-colors"
            title="Yenile"
          >
            <RefreshCw size={14} className={`text-white ${loading ? 'animate-spin' : ''}`} />
          </button>
        </div>
        <div className="p-3">
          {loading && !currencies ? (
            <div className="flex items-center justify-center py-4">
              <Loader2 className="w-5 h-5 animate-spin text-amber-500" />
            </div>
          ) : currencies ? (
            <div className="space-y-2">
              <div className="flex items-center justify-between py-2 border-b border-gray-50">
                <span className="font-medium text-gray-700 text-xs">🇺🇸 USD/TRY</span>
                <span className="font-bold text-gray-900 text-sm">{currencies.USD.toFixed(2)} ₺</span>
              </div>
              <div className="flex items-center justify-between py-2 border-b border-gray-50">
                <span className="font-medium text-gray-700 text-xs">🇪🇺 EUR/TRY</span>
                <span className="font-bold text-gray-900 text-sm">{currencies.EUR.toFixed(2)} ₺</span>
              </div>
              <div className="flex items-center justify-between py-2">
                <span className="font-medium text-gray-700 text-xs">🇬🇧 GBP/TRY</span>
                <span className="font-bold text-gray-900 text-sm">{currencies.GBP.toFixed(2)} ₺</span>
              </div>
              {lastUpdate && (
                <p className="text-[10px] text-gray-400 text-right pt-2 border-t border-gray-100">
                  Son güncelleme: {lastUpdate}
                </p>
              )}
            </div>
          ) : (
            <p className="text-xs text-gray-500 text-center py-4">Veriler yüklenemedi</p>
          )}
        </div>
      </div>
    );
  }

  // Spor kategorisi - Gerçek API verileri
  if (category === 'Spor') {
    return (
      <div className="space-y-4">
        {/* Puan Durumu */}
        <div className="bg-white rounded-2xl border border-gray-100 overflow-hidden shadow-sm">
          <div className="bg-gradient-to-r from-green-600 to-emerald-600 px-4 py-3 flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Trophy size={18} className="text-white" />
              <h3 className="font-bold text-white text-sm">Süper Lig Puan Durumu</h3>
            </div>
            <button
              onClick={loadSportsData}
              disabled={loading}
              className="p-1 hover:bg-white/20 rounded transition-colors"
              title="Yenile"
            >
              <RefreshCw size={14} className={`text-white ${loading ? 'animate-spin' : ''}`} />
            </button>
          </div>
          <div className="p-3">
            {loading && standings.length === 0 ? (
              <div className="flex items-center justify-center py-4">
                <Loader2 className="w-5 h-5 animate-spin text-green-600" />
              </div>
            ) : standings.length > 0 ? (
              <table className="w-full text-xs">
                <thead>
                  <tr className="text-gray-500 border-b">
                    <th className="text-left py-2 w-6">#</th>
                    <th className="text-left py-2">Takım</th>
                    <th className="text-center py-2 w-8">O</th>
                    <th className="text-center py-2 w-8">P</th>
                  </tr>
                </thead>
                <tbody>
                  {standings.map((team) => (
                    <tr key={team.pos} className="border-b border-gray-50 hover:bg-gray-50">
                      <td className={`py-2 font-bold ${team.pos <= 4 ? 'text-green-600' : team.pos >= 17 ? 'text-red-500' : 'text-gray-400'}`}>
                        {team.pos}
                      </td>
                      <td className="py-2 font-medium text-gray-800 flex items-center gap-1.5">
                        {team.logo && (
                          <img src={team.logo} alt="" className="w-4 h-4 object-contain" />
                        )}
                        <span className="truncate max-w-[100px]">{team.team}</span>
                      </td>
                      <td className="py-2 text-center text-gray-500">{team.played}</td>
                      <td className="py-2 text-center font-bold text-gray-900">{team.points}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            ) : (
              <p className="text-xs text-gray-500 text-center py-4">Veriler yüklenemedi</p>
            )}
          </div>
        </div>

        {/* Fikstür */}
        {matches.length > 0 && (
          <div className="bg-white rounded-2xl border border-gray-100 overflow-hidden shadow-sm">
            <div className="bg-gradient-to-r from-blue-600 to-indigo-600 px-4 py-3 flex items-center gap-2">
              <Calendar size={18} className="text-white" />
              <h3 className="font-bold text-white text-sm">Yaklaşan Maçlar</h3>
            </div>
            <div className="p-3 space-y-2">
              {matches.map((match, idx) => (
                <div key={idx} className="flex items-center justify-between py-2 border-b border-gray-50 last:border-0">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-1 text-xs font-medium text-gray-800">
                      {match.homeLogo && <img src={match.homeLogo} alt="" className="w-4 h-4" />}
                      <span className="truncate">{match.home}</span>
                    </div>
                    <div className="flex items-center gap-1 text-xs font-medium text-gray-800 mt-0.5">
                      {match.awayLogo && <img src={match.awayLogo} alt="" className="w-4 h-4" />}
                      <span className="truncate">{match.away}</span>
                    </div>
                  </div>
                  <div className="text-right flex-shrink-0 ml-2">
                    <p className="text-[10px] text-gray-500">{match.date}</p>
                    <p className="text-xs font-bold text-blue-600">{match.time}</p>
                  </div>
                </div>
              ))}
            </div>
            {lastUpdate && (
              <div className="px-3 pb-2">
                <p className="text-[10px] text-gray-400 text-right">
                  Son güncelleme: {lastUpdate}
                </p>
              </div>
            )}
          </div>
        )}
      </div>
    );
  }

  // Default
  return null;
}
