'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { Radio, Clock, CheckCircle2, MapPin, Calendar } from 'lucide-react';
import { apiRequest, getCurrentUser } from '../../lib/api';
import { Badge } from '../../components/Badge';
import { Button } from '../../components/Button';

function countdownLabel(startTime: string) {
  const diff = new Date(startTime).getTime() - Date.now();
  if (diff <= 0) return 'Window open';
  const mins = Math.floor(diff / 60000);
  if (mins < 60) return `${mins}m to start`;
  const hours = Math.floor(mins / 60);
  return `${hours}h ${mins % 60}m to start`;
}

function canScore(match: any) {
  if (match.status === 'COMPLETED' || match.status === 'CANCELLED' || match.status === 'ABANDONED') {
    return false;
  }
  if (match.status === 'LIVE') return true;
  // Allow scoring 30 mins before scheduled start (matches backend rule)
  return Date.now() >= new Date(match.startTime).getTime() - 30 * 60 * 1000;
}

export default function ScorerDashboardPage() {
  const [matches, setMatches] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const user = getCurrentUser();

  const loadMatches = async () => {
    try {
      setLoading(true);
      const res = await apiRequest('/matches?assignedToMe=true');
      setMatches(res.data || []);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadMatches();
    const id = setInterval(loadMatches, 30000);
    return () => clearInterval(id);
  }, []);

  const live = matches.filter((m) => m.status === 'LIVE');
  const upcoming = matches.filter((m) => m.status === 'SCHEDULED');
  const completed = matches.filter((m) => m.status === 'COMPLETED');

  const Section = ({
    title,
    icon,
    items,
    empty,
  }: {
    title: string;
    icon: React.ReactNode;
    items: any[];
    empty: string;
  }) => (
    <section className="space-y-3">
      <div className="flex items-center gap-2 text-sm font-semibold text-zinc-200">
        {icon}
        <span>{title}</span>
        <Badge variant="slate">{items.length}</Badge>
      </div>
      {items.length === 0 ? (
        <div className="text-xs text-zinc-500 bg-zinc-900/50 border border-zinc-800/60 rounded-xl px-4 py-6">
          {empty}
        </div>
      ) : (
        <div className="grid gap-3">
          {items.map((m) => {
            const scoringAllowed = canScore(m);
            return (
              <div
                key={m._id}
                className="bg-zinc-900/80 border border-zinc-800 rounded-2xl p-4 sm:p-5 flex flex-col sm:flex-row sm:items-center justify-between gap-4"
              >
                <div className="space-y-1.5 min-w-0">
                  <div className="flex items-center gap-2 flex-wrap">
                    <h3 className="font-semibold text-white text-sm truncate">{m.title}</h3>
                    <Badge
                      variant={
                        m.status === 'LIVE' ? 'rose' : m.status === 'COMPLETED' ? 'emerald' : 'amber'
                      }
                    >
                      {m.status}
                    </Badge>
                  </div>
                  <div className="text-xs text-zinc-400 flex flex-wrap gap-x-4 gap-y-1">
                    <span className="inline-flex items-center gap-1">
                      <MapPin className="w-3 h-3" />
                      {m.venue}
                    </span>
                    <span className="inline-flex items-center gap-1">
                      <Calendar className="w-3 h-3" />
                      {new Date(m.startTime).toLocaleString()}
                    </span>
                    {m.status === 'SCHEDULED' && (
                      <span className="inline-flex items-center gap-1 text-amber-400">
                        <Clock className="w-3 h-3" />
                        {countdownLabel(m.startTime)}
                      </span>
                    )}
                  </div>
                  <div className="text-xs font-mono text-zinc-300 pt-1">
                    {m.teamA?.shortName} {m.teamA?.score?.runs || 0}/{m.teamA?.score?.wickets || 0} ·{' '}
                    {m.teamB?.shortName} {m.teamB?.score?.runs || 0}/{m.teamB?.score?.wickets || 0}
                  </div>
                </div>
                <div className="shrink-0">
                  {m.status === 'COMPLETED' ? (
                    <Link href={`/scorer/${m._id}`}>
                      <Button variant="secondary" size="sm">
                        View Scorecard
                      </Button>
                    </Link>
                  ) : scoringAllowed ? (
                    <Link href={`/scorer/${m._id}`}>
                      <Button variant="amber" size="sm" className="gap-1.5">
                        <Radio className="w-3.5 h-3.5" />
                        Open Console
                      </Button>
                    </Link>
                  ) : (
                    <Button variant="ghost" size="sm" disabled title="Scoring locked until match window">
                      Locked until window
                    </Button>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </section>
  );

  return (
    <div className="max-w-4xl mx-auto w-full p-6 md:p-8 space-y-8">
      <div>
        <h1 className="text-2xl font-bold tracking-tight text-white">Scorer Console</h1>
        <p className="text-xs text-zinc-400 mt-1">
          Assigned matches only · signed in as {user?.name || 'Scorer'}
        </p>
      </div>

      {loading ? (
        <div className="text-center text-xs text-zinc-400 py-16">Loading assigned matches...</div>
      ) : (
        <>
          <Section
            title="Live"
            icon={<Radio className="w-4 h-4 text-rose-400" />}
            items={live}
            empty="No live matches assigned."
          />
          <Section
            title="Upcoming"
            icon={<Clock className="w-4 h-4 text-amber-400" />}
            items={upcoming}
            empty="No upcoming assigned matches."
          />
          <Section
            title="Completed"
            icon={<CheckCircle2 className="w-4 h-4 text-emerald-400" />}
            items={completed}
            empty="No completed matches yet."
          />
        </>
      )}
    </div>
  );
}
