'use client';

import React, { Suspense, useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { apiRequest, getCurrentUser, idempotencyKey } from '../../../lib/api';
import { CLIENT_TTL, clientCacheGet, clientCacheInvalidate } from '../../../lib/clientCache';
import { Button } from '../../../components/Button';
import { ContestCard } from '../../../components/ContestCard';
import { FantasyTeamBuilder } from '../../../components/FantasyTeamBuilder';
import { MatchCard } from '../../../components/MatchCard';
import { TeamCreatedPopup } from '../../../components/TeamCreatedPopup';
import { EmptyBlock, ErrorBlock, LoadingBlock } from '../../../components/StateBlock';
import { loginHref } from '../../../lib/authRedirect';
import { countdown } from '../../../lib/format';

function FantasyInner() {
  const router = useRouter();
  const params = useSearchParams();
  const matchIdParam = params.get('matchId') || '';
  const user = getCurrentUser();
  const userId = user?._id || user?.id || '';

  const [matches, setMatches] = useState<any[]>([]);
  const [contests, setContests] = useState<any[]>([]);
  const [matchId, setMatchId] = useState(matchIdParam);
  const [match, setMatch] = useState<any>(null);
  const [myTeams, setMyTeams] = useState<any[]>([]);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(true);
  const [step, setStep] = useState<'contests' | 'team'>(matchIdParam ? 'team' : 'contests');
  const [toast, setToast] = useState('');
  const [successOpen, setSuccessOpen] = useState(false);
  const [savedTeamName, setSavedTeamName] = useState('My XI');

  useEffect(() => {
    setMatchId(matchIdParam);
    if (matchIdParam) setStep((s) => s);
  }, [matchIdParam]);

  const boot = async () => {
    setLoading(true);
    try {
      const [mRes, cRes] = await Promise.all([
        clientCacheGet('matches:list:SCHEDULED', CLIENT_TTL.matchesList, () =>
          apiRequest('/matches?status=SCHEDULED')
        ),
        clientCacheGet('contests:list:NORMAL', CLIENT_TTL.contestsList, () =>
          apiRequest('/contests?contestType=NORMAL')
        ),
      ]);
      setMatches(mRes.data || []);
      setContests(cRes.data || []);
      if (matchIdParam) setMatchId(matchIdParam);
    } catch (e: any) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  };

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

  useEffect(() => {
    if (!matchId) {
      setMatch(null);
      setMyTeams([]);
      return;
    }
    let cancelled = false;
    (async () => {
      try {
        const res = await apiRequest(`/matches/${matchId}`);
        if (cancelled) return;
        setMatch(res.data.match);
        if (userId) {
          const teams = await apiRequest(`/fantasy/teams?matchId=${matchId}`);
          if (!cancelled) setMyTeams(teams.data || []);
        } else if (!cancelled) {
          setMyTeams([]);
        }
      } catch (e: any) {
        if (!cancelled) setError(e.message);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [matchId, userId]);

  const saveTeam = async (payload: {
    playerIds: string[];
    captainId: string;
    viceCaptainId: string;
    name: string;
  }) => {
    if (!user) {
      router.push('/login');
      return;
    }
    setBusy(true);
    setError('');
    try {
      await apiRequest('/fantasy/teams', {
        method: 'POST',
        body: JSON.stringify({ matchId, ...payload }),
      });
      const teams = await apiRequest(`/fantasy/teams?matchId=${matchId}`);
      setMyTeams(teams.data || []);
      setSavedTeamName(payload.name || 'My XI');
      setSuccessOpen(true);
      setStep('contests');
    } catch (e: any) {
      setError(e.message || 'Could not save team');
    } finally {
      setBusy(false);
    }
  };

  const join = async (contestId: string, fantasyTeamId: string) => {
    setBusy(true);
    setError('');
    try {
      await apiRequest('/contests/join', {
        method: 'POST',
        idempotencyKey: idempotencyKey('join'),
        body: JSON.stringify({ contestId, fantasyTeamId }),
      });
      clientCacheInvalidate('contests:');
      setToast('Joined contest successfully!');
    } catch (e: any) {
      setError(e.message || 'Join failed');
    } finally {
      setBusy(false);
    }
  };

  const matchContests = contests.filter((c) => {
    if (!matchId) return false;
    const mid = c.matchId?._id || c.matchId;
    return !mid || String(mid) === String(matchId);
  });

  const shortA = match?.teamA?.shortName || match?.teamA?.name || 'T1';
  const shortB = match?.teamB?.shortName || match?.teamB?.name || 'T2';

  if (loading) return <LoadingBlock label="Loading contests…" />;

  if (!matchId) {
    return (
      <div className="app-page">
        {error && <ErrorBlock message={error} onRetry={() => setError('')} />}
        {matches.length === 0 ? (
          <EmptyBlock title="No upcoming matches" hint="Check Home when fixtures are published." />
        ) : (
          <div className="space-y-2">
            {matches.map((m) => (
              <MatchCard key={m._id} match={m} />
            ))}
          </div>
        )}
      </div>
    );
  }

  return (
    <div className="app-page">
      <div className="d11-segment overflow-hidden">
        <div className="flex items-center justify-between gap-2 border-b border-gray-100 px-3.5 py-2.5">
          <div className="min-w-0">
            <p className="truncate font-display text-sm font-extrabold text-d11-ink">
              {shortA} <span className="font-medium text-d11-muted">vs</span> {shortB}
            </p>
            {match?.startTime && (
              <p className="text-[10px] font-bold text-d11-red">{countdown(match.startTime)}</p>
            )}
          </div>
          <Link
            href="/"
            className="shrink-0 rounded-full bg-d11-soft px-2.5 py-1 text-[11px] font-extrabold text-d11-red"
          >
            Change
          </Link>
        </div>

        <div className="flex">
          <button
            type="button"
            onClick={() => setStep('contests')}
            className={`d11-tab ${step === 'contests' ? 'd11-tab-active' : ''}`}
          >
            Contests
          </button>
          <button
            type="button"
            onClick={() => setStep('team')}
            className={`d11-tab ${step === 'team' ? 'd11-tab-active' : ''}`}
          >
            Create Team
          </button>
        </div>
      </div>

      {toast && (
        <div className="flex items-center justify-between gap-3 rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm font-medium text-emerald-800">
          <span>{toast}</span>
          <button
            type="button"
            onClick={() => setToast('')}
            className="text-xs font-bold uppercase text-emerald-700 hover:underline"
          >
            Dismiss
          </button>
        </div>
      )}
      {error && <ErrorBlock message={error} onRetry={() => setError('')} />}

      <TeamCreatedPopup
        open={successOpen}
        teamName={savedTeamName}
        matchTitle={match?.title}
        onClose={() => setSuccessOpen(false)}
        onJoinContests={() => {
          setSuccessOpen(false);
          setStep('contests');
          setToast('Pick a contest below and tap Join.');
        }}
      />

      {step === 'team' && match && (
        <FantasyTeamBuilder
          match={match}
          busy={busy}
          onSave={saveTeam}
          onBack={() => setStep('contests')}
        />
      )}

      {step === 'team' && !match && <LoadingBlock label="Loading squad…" />}

      {step === 'contests' && (
        <div className="space-y-2">
          {!user ? (
            <EmptyBlock
              title="Login to join contests"
              hint="Sign in, build your XI, then join."
              action={
                <Link href={loginHref(`/fantasy?matchId=${matchId}`)}>
                  <Button>Login to continue</Button>
                </Link>
              }
            />
          ) : myTeams.length === 0 ? (
            <div className="d11-card px-4 py-4 text-center">
              <p className="text-sm font-extrabold text-d11-ink">Create your fantasy XI first</p>
              <p className="mt-1 text-xs text-d11-muted">Takes under a minute — then join any contest.</p>
              <Button className="mt-3 rounded-lg" size="sm" onClick={() => setStep('team')}>
                Create Team
              </Button>
            </div>
          ) : (
            <div className="d11-card flex flex-wrap items-center justify-between gap-2 px-3 py-2.5">
              <div className="text-[13px]">
                <span className="font-extrabold text-d11-ink">{myTeams.length} team ready</span>
                <span className="text-d11-muted"> · {myTeams[0].name}</span>
              </div>
              <button
                type="button"
                onClick={() => setStep('team')}
                className="text-[11px] font-extrabold text-d11-red hover:underline"
              >
                Create another
              </button>
            </div>
          )}

          {matchContests.length === 0 ? (
            <EmptyBlock title="No contests open for this match." />
          ) : (
            matchContests.map((c) => (
              <ContestCard
                key={c._id}
                contest={c}
                busy={busy}
                canJoin={!!user && !!myTeams[0] && c.status === 'OPEN'}
                onJoin={() => join(c._id, myTeams[0]._id)}
              />
            ))
          )}
        </div>
      )}
    </div>
  );
}

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