// frontend/src/components/Tournament/ScoreModal.tsx

import { type SetData } from '../../types';
import { Clock, Eraser, Trophy, Loader2 } from 'lucide-react';
import { useState } from 'react';
import Modal from '../UI/Modal';
import WhistleIcon from "../../assets/whistle.svg?react"
import CourtIcon from '../../assets/court.svg?react';

interface MatchData {
    id: string | number;
    number: number;
    time: string;
    court: string;
    p1?: string;
    p1_label?: string;
    p2?: string;
    p2_label?: string;
    ref_label?: string;
    ref_team?: { name: string };
    isFinished: boolean;
    sets?: SetData[];
}

interface ScoreFormProps {
    match: MatchData;
    isAuthenticated: boolean;
    onSubmit: (id: string | number, sets: SetData[], code: string) => Promise<void>;
    onClear: (id: string | number, code: string) => Promise<void>;
}

const ScoreForm = ({ match, isAuthenticated, onSubmit, onClear }: ScoreFormProps) => {
    const [sets, setSets] = useState<SetData[]>(match.sets && match.sets.length ? match.sets : [{ p1: '', p2: '' }]);
    const [code, setCode] = useState<string>('');
    const [error, setError] = useState<string | null>(null);
    const [isSubmitting, setIsSubmitting] = useState<boolean>(false); // <-- NEW: Lock state

    const refName = match.ref_team?.name || match.ref_label;

    const handleSubmit = async () => {
        if (isSubmitting) return; // Prevent double-execution
        setIsSubmitting(true);
        setError(null);

        try {
            await onSubmit(match.id, sets, code);
        } catch (err: unknown) {
            const error = err as { detail?: string };
            setError(typeof error?.detail === 'string' ? error.detail : "Check code or scores");
            setIsSubmitting(false); // Only re-enable the button if it failed (if it succeeds, modal closes)
        }
    };

    const handleClear = async () => {
        if (isSubmitting) return; // Prevent double-execution
        setIsSubmitting(true);
        setError(null);

        try {
            await onClear(match.id, code);
        } catch (err: unknown) {
            const error = err as { detail?: string };
            setError(typeof error?.detail === 'string' ? error.detail : "Failed to clear score");
            setIsSubmitting(false); // Re-enable on error
        }
    };

    const removeSet = (idx: number) => {
        if (sets.length > 1) setSets(sets.filter((_, i) => i !== idx));
    };

    const updateSet = (idx: number, field: keyof SetData, val: string) => {
        const n = [...sets];
        n[idx][field] = parseInt(val) || 0;
        setSets(n);
    };

    return (
        <div className="space-y-6">
            <div className="flex flex-col gap-2">
                {/* Time & Court Row */}
                <div className="flex justify-center items-center gap-4 bg-zinc-50 dark:bg-zinc-950 p-3 rounded-lg border border-gray-200 dark:border-zinc-800 shadow-sm transition-colors">
                    <div className="flex items-center gap-2 text-sm font-mono text-zinc-600 dark:text-zinc-300">
                        <Clock className="text-orange-500" size={16} />
                        <span>{match.time || "10:00"}</span>
                    </div>
                    <div className="h-4 w-px bg-zinc-300 dark:bg-zinc-800" />
                    <div className="flex items-center gap-2 text-sm font-mono text-zinc-900 dark:text-white">
                        <CourtIcon className="text-orange-500" width={16} height={16} />
                        <span>{match.court || "TBD"}</span>
                    </div>
                </div>

                {/* Dedicated Ref Row (Always visible) */}
                {refName && (
                    <div className={`flex justify-center items-center gap-2 p-2.5 rounded-lg border transition-colors ${match.ref_team
                        ? 'bg-orange-50 dark:bg-orange-900/10 border-orange-100 dark:border-orange-900/30'
                        : 'bg-zinc-50 dark:bg-zinc-950 border-gray-200 dark:border-zinc-800'
                        }`}>
                        <WhistleIcon className={`${match.ref_team ? 'text-orange-500' : 'text-zinc-400 dark:text-zinc-600'} shrink-0`} width={14} height={14} />
                        <span className={`truncate ${match.ref_team
                            ? 'text-xs font-bold text-orange-700 dark:text-orange-500 uppercase tracking-wide'
                            : 'text-sm italic text-zinc-500 dark:text-zinc-400 font-medium'
                            }`}>
                            {refName}
                        </span>
                    </div>
                )}
            </div>

            {error && (
                <div className="text-xs text-red-500 dark:text-red-400 text-center bg-red-50 dark:bg-red-900/10 p-2 rounded border border-red-200 dark:border-red-900/30">
                    {error}
                </div>
            )}

            {!isAuthenticated && (
                <div className="bg-zinc-50 dark:bg-zinc-950 p-4 rounded-lg border border-gray-200 dark:border-zinc-800">
                    <label className="block text-xs font-bold text-orange-500 uppercase mb-2">Tournament Code</label>
                    <input
                        type="password"
                        value={code}
                        onChange={e => setCode(e.target.value)}
                        placeholder="•••••"
                        autoComplete="off"
                        className="w-full bg-white dark:bg-zinc-900 border border-gray-300 dark:border-zinc-700 rounded p-3 text-center text-lg tracking-[0.5em] focus:ring-1 focus:ring-orange-500 outline-none transition text-zinc-900 dark:text-white shadow-sm"
                    />
                </div>
            )}

            <div className="grid grid-cols-3 gap-2 text-center font-bold text-zinc-700 dark:text-zinc-200 items-center px-2">
                <div className="wrap-break-word text-sm leading-tight uppercase">{match.p1 || match.p1_label}</div>
                <div className="text-zinc-400 dark:text-zinc-600 text-[10px] font-bold uppercase bg-zinc-100 dark:bg-zinc-950 px-3 py-1 rounded-full w-fit mx-auto shadow-sm">VS</div>
                <div className="wrap-break-word text-sm leading-tight uppercase">{match.p2 || match.p2_label}</div>
            </div>

            <div className="space-y-2 max-h-48 overflow-y-auto pr-1">
                {sets.map((s, i) => (
                    <div key={i} className="animate-in slide-in-from-top-1 px-1">
                        <div className="flex items-center justify-center gap-2">
                            <div className="grid grid-cols-3 gap-2 items-center justify-items-center w-full">
                                <input
                                    type="number"
                                    min="0"
                                    pattern="[0-9]*"
                                    value={s.p1}
                                    onChange={(e) => updateSet(i, "p1", e.target.value)}
                                    className="w-full bg-gray-50 dark:bg-zinc-950 border border-gray-300 dark:border-zinc-800 p-2 rounded text-center focus:border-orange-500 outline-none text-zinc-900 dark:text-white"
                                />

                                {sets.length > 1 ? (
                                    <button
                                        onClick={() => removeSet(i)}
                                        title="Remove Set"
                                        className="mx-auto p-2 text-zinc-300 hover:text-red-500 transition shrink-0 group"
                                    >
                                        <Eraser
                                            size={18}
                                            className="group-hover:scale-110 transition-transform"
                                        />
                                    </button>
                                ) : (
                                    <span className="text-zinc-400 dark:text-zinc-600 text-center font-bold">
                                        -
                                    </span>
                                )}

                                <input
                                    type="number"
                                    min="0"
                                    pattern="[0-9]*"
                                    value={s.p2}
                                    onChange={(e) => updateSet(i, "p2", e.target.value)}
                                    className="w-full bg-gray-50 dark:bg-zinc-950 border border-gray-300 dark:border-zinc-800 p-2 rounded text-center focus:border-orange-500 outline-none text-zinc-900 dark:text-white"
                                />
                            </div>
                        </div>
                    </div>
                ))}
            </div>

            <button onClick={() => setSets([...sets, { p1: '', p2: '' }])} className="w-full py-2 border border-dashed border-zinc-300 dark:border-zinc-700 text-zinc-500 dark:text-zinc-400 text-sm hover:border-orange-500 hover:text-orange-500 transition rounded">+ Add Set</button>

            <div className="flex gap-2">
                {match.isFinished && (
                    <button
                        onClick={handleClear}
                        disabled={isSubmitting}
                        className={`w-1/3 bg-red-100 dark:bg-red-900/50 hover:bg-red-200 dark:hover:bg-red-900 text-red-600 dark:text-red-300 py-3 rounded-lg font-bold transition text-sm flex justify-center items-center ${isSubmitting ? 'opacity-50 cursor-not-allowed' : ''}`}
                    >
                        {isSubmitting ? <Loader2 size={16} className="animate-spin" /> : 'Clear'}
                    </button>
                )}
                <button
                    onClick={handleSubmit}
                    disabled={isSubmitting}
                    className={`${match.isFinished ? 'w-2/3' : 'w-full'} bg-orange-600 hover:bg-orange-500 py-3 rounded-lg font-bold shadow-lg shadow-orange-900/20 transition text-white active:scale-95 flex justify-center items-center gap-2 ${isSubmitting ? 'opacity-70 cursor-not-allowed' : ''}`}
                >
                    {isSubmitting ? (
                        <>
                            <Loader2 size={18} className="animate-spin" />
                            <span>Saving...</span>
                        </>
                    ) : 'Submit Result'}
                </button>
            </div>
        </div>
    );
};

interface ScoreModalProps {
    isOpen: boolean;
    onClose: () => void;
    match: MatchData | null;
    isAuthenticated: boolean;
    onSubmit: (id: string | number, sets: SetData[], code: string) => Promise<void>;
    onClear: (id: string | number, code: string) => Promise<void>;
}

export default function ScoreModal({ isOpen, onClose, match, isAuthenticated, onSubmit, onClear }: ScoreModalProps) {
    if (!isOpen || !match) return null;

    return (
        <Modal isOpen={isOpen} onClose={onClose} title={`Match #${match.number}`} icon={Trophy}>
            <ScoreForm
                match={match}
                isAuthenticated={isAuthenticated}
                onSubmit={async (id, sets, code) => {
                    await onSubmit(id, sets, code);
                    onClose();
                }}
                onClear={async (id, code) => {
                    await onClear(id, code);
                    onClose();
                }}
            />
        </Modal>
    );
}