'use client';

import React, { Suspense, useEffect, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { apiRequest } from '../../../lib/api';
import { CLIENT_TTL, clientCacheGet } from '../../../lib/clientCache';
import { MatchCard } from '../../../components/MatchCard';
import { EmptyBlock, ErrorBlock, LoadingBlock } from '../../../components/StateBlock';

const TABS = [
  { id: 'live', status: 'LIVE', label: 'Live' },
  { id: 'completed', status: 'COMPLETED', label: 'Completed' },
] as const;

function MatchesInner() {
  const params = useSearchParams();
  const initial = params.get('tab') === 'completed' ? 'completed' : 'live';
  const [tab, setTab] = useState<(typeof TABS)[number]['id']>(initial);
  const [matches, setMatches] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const load = async () => {
    const status = TABS.find((t) => t.id === tab)?.status || 'LIVE';
    setLoading(true);
    setError('');
    try {
      const ttl = status === 'LIVE' ? CLIENT_TTL.liveMatches : CLIENT_TTL.matchesList;
      const res = await clientCacheGet(`matches:list:${status}`, ttl, () =>
        apiRequest(`/matches?status=${status}`)
      );
      setMatches(res.data || []);
    } catch (e: any) {
      setError(e.message || 'Failed to load matches');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tab]);

  return (
    <div className="app-page">
      <div className="d11-segment">
        <div className="flex">
          {TABS.map((t) => (
            <button
              key={t.id}
              type="button"
              onClick={() => setTab(t.id)}
              className={`d11-tab ${tab === t.id ? 'd11-tab-active' : ''}`}
            >
              {t.label}
            </button>
          ))}
        </div>
      </div>

      {loading && <LoadingBlock />}
      {error && <ErrorBlock message={error} onRetry={load} />}
      {!loading && !error && matches.length === 0 && (
        <EmptyBlock
          title={tab === 'live' ? 'No live matches' : 'No completed matches'}
          hint="Upcoming fixtures are on Home."
        />
      )}
      {!loading && !error && (
        <div className="space-y-2">
          {matches.map((m) => (
            <MatchCard key={m._id} match={m} />
          ))}
        </div>
      )}
    </div>
  );
}

export default function MatchesPage() {
  return (
    <Suspense fallback={<LoadingBlock />}>
      <MatchesInner />
    </Suspense>
  );
}
