import React, { useState } from 'react';
import { toTitleCase } from '../utils/text';
import { Dumbbell, User, Flame, Timer as TimerIcon, ArrowUp, ArrowRight, Footprints, Ruler, Percent } from 'lucide-react';
import { ExerciseDef, ExerciseType, Language } from '../types';
import { t } from '../services/i18n';
import { generateId } from '../utils/uuid';
import FilledInput from './FilledInput';
import { Modal } from './ui/Modal';
import { Button } from './ui/Button';

interface ExerciseModalProps {
    isOpen: boolean;
    onClose: () => void;
    onSave: (exercise: ExerciseDef) => Promise<void> | void;
    lang: Language;
    existingExercises?: ExerciseDef[];
}

const ExerciseModal: React.FC<ExerciseModalProps> = ({ isOpen, onClose, onSave, lang, existingExercises = [] }) => {
    const [newName, setNewName] = useState('');
    const [newType, setNewType] = useState<ExerciseType>(ExerciseType.STRENGTH);
    const [newBwPercentage, setNewBwPercentage] = useState<string>('100');
    const [isUnilateral, setIsUnilateral] = useState(false);
    const [error, setError] = useState<string>('');

    const exerciseTypeLabels: Record<ExerciseType, string> = {
        [ExerciseType.STRENGTH]: t('type_strength', lang),
        [ExerciseType.BODYWEIGHT]: t('type_bodyweight', lang),
        [ExerciseType.CARDIO]: t('type_cardio', lang),
        [ExerciseType.STATIC]: t('type_static', lang),
        [ExerciseType.HIGH_JUMP]: t('type_height', lang),
        [ExerciseType.LONG_JUMP]: t('type_dist', lang),
        [ExerciseType.PLYOMETRIC]: t('type_jump', lang),
    };

    const handleCreateExercise = async () => {
        if (!newName.trim()) return;

        // Check for duplicate name (case-insensitive)
        const trimmedName = newName.trim();
        const isDuplicate = existingExercises.some(
            ex => ex.name.toLowerCase() === trimmedName.toLowerCase()
        );

        if (isDuplicate) {
            setError(t('exercise_name_exists', lang) || 'An exercise with this name already exists');
            return;
        }

        const newEx: ExerciseDef = {
            id: generateId(),
            name: trimmedName,
            type: newType,
            isUnilateral,
            ...(newType === ExerciseType.BODYWEIGHT && { bodyWeightPercentage: parseFloat(newBwPercentage) || 100 })
        };
        await onSave(newEx);
        setNewName('');
        setNewType(ExerciseType.STRENGTH);
        setNewBwPercentage('100');
        setIsUnilateral(false);
        setError('');
        onClose(); // Modal controls its own open state usually, but here checking prop
    };

    return (
        <Modal
            isOpen={isOpen}
            onClose={() => {
                console.log('ExerciseModal onClose');
                onClose();
            }}
            title={t('create_exercise', lang)}
            maxWidth="sm"
        >
            {console.log('ExerciseModal Rendering. isOpen:', isOpen)}
            <div className="space-y-6">
                <div>
                    <FilledInput
                        label={t('ex_name', lang)}
                        value={newName}
                        onChange={(e: any) => {
                            setNewName(e.target.value);
                            setError(''); // Clear error when user types
                        }}
                        type="text"
                        autoFocus
                        autocapitalize="words"
                        onBlur={() => setNewName(toTitleCase(newName))}
                    />
                    {error && (
                        <p className="text-xs text-error mt-2 ml-3">{error}</p>
                    )}
                </div>

                <div>
                    <label className="block text-xs text-on-surface-variant font-medium mb-3">{t('ex_type', lang)}</label>
                    <div className="flex flex-wrap gap-2">
                        {[
                            { id: ExerciseType.STRENGTH, label: exerciseTypeLabels[ExerciseType.STRENGTH], icon: Dumbbell },
                            { id: ExerciseType.BODYWEIGHT, label: exerciseTypeLabels[ExerciseType.BODYWEIGHT], icon: User },
                            { id: ExerciseType.CARDIO, label: exerciseTypeLabels[ExerciseType.CARDIO], icon: Flame },
                            { id: ExerciseType.STATIC, label: exerciseTypeLabels[ExerciseType.STATIC], icon: TimerIcon },
                            { id: ExerciseType.HIGH_JUMP, label: exerciseTypeLabels[ExerciseType.HIGH_JUMP], icon: ArrowUp },
                            { id: ExerciseType.LONG_JUMP, label: exerciseTypeLabels[ExerciseType.LONG_JUMP], icon: Ruler },
                            { id: ExerciseType.PLYOMETRIC, label: exerciseTypeLabels[ExerciseType.PLYOMETRIC], icon: Footprints },
                        ].map((type) => (
                            <button
                                key={type.id}
                                onClick={() => setNewType(type.id)}
                                className={`px-4 py-2 rounded-lg flex items-center gap-2 text-xs font-medium border transition-all ${newType === type.id
                                    ? 'bg-secondary-container text-on-secondary-container border-transparent'
                                    : 'bg-transparent text-on-surface-variant border-outline hover:border-on-surface-variant'
                                    }`}
                            >
                                <type.icon size={14} /> {type.label}
                            </button>
                        ))}
                    </div>
                </div>

                {newType === ExerciseType.BODYWEIGHT && (
                    <FilledInput
                        label={t('body_weight_percent', lang)}
                        value={newBwPercentage}
                        onChange={(e: any) => setNewBwPercentage(e.target.value)}
                        icon={<Percent size={12} />}
                    />
                )}

                <div className="flex items-center gap-3 px-1">
                    <input
                        type="checkbox"
                        id="isUnilateral"
                        checked={isUnilateral}
                        onChange={(e) => setIsUnilateral(e.target.checked)}
                        className="w-5 h-5 rounded border-2 border-outline bg-surface-container-high checked:bg-primary checked:border-primary cursor-pointer"
                    />
                    <label htmlFor="isUnilateral" className="text-sm text-on-surface cursor-pointer">
                        {t('unilateral_exercise', lang) || 'Unilateral exercise (separate left/right tracking)'}
                    </label>
                </div>

                <div className="flex justify-end mt-4 pt-4">
                    <Button
                        onClick={handleCreateExercise}
                        fullWidth
                    >
                        {t('create_btn', lang)}
                    </Button>
                </div>
            </div>
        </Modal>
    );
};

export default ExerciseModal;
