'use client';

import React, { useEffect, useMemo, useState } from 'react';
import { apiRequest, getCurrentUser } from '../../lib/api';
import { getPublicConfig } from '../../lib/publicConfig';
import { CLIENT_TTL, clientCacheGet } from '../../lib/clientCache';
import { MatchCard } from '../../components/MatchCard';
import { HeroSlider } from '../../components/HeroSlider';
import { SignupBonusModal } from '../../components/SignupBonusModal';
import { EmptyBlock, ErrorBlock, LoadingBlock } from '../../components/StateBlock';

type Tab = 'upcoming' | 'live' | 'completed';

/** Match lobby — app-first play path. */
export default function HomePage() {
  const [tab, setTab] = useState<Tab>('upcoming');
  const [live, setLive] = useState<any[]>([]);
  const [upcoming, setUpcoming] = useState<any[]>([]);
  const [completed, setCompleted] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [slides, setSlides] = useState<any[]>([]);
  const [bonus, setBonus] = useState<{ show: boolean; amount: number }>({ show: false, amount: 0 });

  const load = async () => {
    setLoading(true);
    setError('');
    try {
      const [l, u, c] = await Promise.all([
        clientCacheGet('matches:list:LIVE', CLIENT_TTL.liveMatches, () =>
          apiRequest('/matches?status=LIVE')
        ),
        clientCacheGet('matches:list:SCHEDULED', CLIENT_TTL.matchesList, () =>
          apiRequest('/matches?status=SCHEDULED')
        ),
        clientCacheGet('matches:list:COMPLETED', CLIENT_TTL.matchesList, () =>
          apiRequest('/matches?status=COMPLETED')
        ),
      ]);
      setLive(l.data || []);
      setUpcoming(u.data || []);
      setCompleted(c.data || []);
      if ((l.data || []).length > 0) setTab('live');
    } catch (e: any) {
      setError(e.message || 'Failed to load matches');
    } finally {
      setLoading(false);
    }

    try {
      const cfg = await getPublicConfig(true);
      const hero = cfg.data?.heroSlider;
      // Only admin-uploaded / CMS slides (already filtered active + imageUrl by API)
      const remote = Array.isArray(hero?.slides)
        ? hero.slides.filter((s: any) => s?.imageUrl)
        : [];
      setSlides(hero?.enabled === false ? [] : remote);

      const user = getCurrentUser();
      const sb = cfg.data?.signupBonus;
      if (user && user.role === 'CUSTOMER' && sb?.enabled && sb.amount > 0) {
        try {
          const me = await apiRequest('/auth/me');
          if (!me.data?.signupBonusClaimed) {
            setBonus({ show: true, amount: sb.amount });
          }
        } catch {
          /* ignore */
        }
      }
    } catch {
      setSlides([]);
    }
  };

  useEffect(() => {
    load();
  }, []);

  const items = useMemo(() => {
    if (tab === 'live') return live;
    if (tab === 'completed') return completed;
    return upcoming;
  }, [tab, live, upcoming, completed]);

  return (
    <div className="app-page">
      {bonus.show && (
        <SignupBonusModal
          amount={bonus.amount}
          onClose={() => setBonus((b) => ({ ...b, show: false }))}
          onClaimed={() => setBonus({ show: false, amount: 0 })}
        />
      )}

      {slides.length > 0 && (
        <div className="px-1 py-1 sm:px-1.5 sm:py-1.5">
          <HeroSlider slides={slides} />
        </div>
      )}

      <div className="d11-segment">
        <div className="flex">
          {(
            [
              { id: 'upcoming' as const, label: 'Upcoming', count: upcoming.length },
              { id: 'live' as const, label: 'Live', count: live.length },
              { id: 'completed' as const, label: 'Completed', count: completed.length },
            ] as const
          ).map((t) => (
            <button
              key={t.id}
              type="button"
              onClick={() => setTab(t.id)}
              className={`d11-tab ${tab === t.id ? 'd11-tab-active' : ''}`}
            >
              {t.label}
              {t.count > 0 && (
                <span
                  className={`ml-1 inline-flex min-w-[1.1rem] items-center justify-center rounded-full px-1 text-[9px] font-extrabold ${
                    tab === t.id ? 'bg-d11-soft text-d11-red' : 'bg-gray-100 text-d11-muted'
                  }`}
                >
                  {t.count}
                </span>
              )}
            </button>
          ))}
        </div>
      </div>

      {loading && <LoadingBlock label="Loading matches…" />}
      {error && <ErrorBlock message={error} onRetry={load} />}

      {!loading && !error && items.length === 0 && (
        <EmptyBlock
          title={`No ${tab} matches`}
          hint={tab === 'upcoming' ? 'New fixtures appear here when published.' : 'Check back soon.'}
        />
      )}

      {!loading && !error && (
        <div className="space-y-2">
          {items.map((m) => (
            <MatchCard key={m._id} match={m} />
          ))}
        </div>
      )}
    </div>
  );
}
