import React, { useState, useEffect } from 'react';
import { Dumbbell, Activity, Percent, Timer, ArrowRight, ArrowUp, Save, Calendar, Clock } from 'lucide-react';
import { WorkoutSet, ExerciseType, ExerciseDef, Language } from '../types';
import { t } from '../services/i18n';
import { formatSetMetrics } from '../utils/setFormatting';
import { SideSheet } from './ui/SideSheet';
import { Button } from './ui/Button';

interface EditSetModalProps {
    isOpen: boolean;
    onClose: () => void;
    set: WorkoutSet;
    exerciseDef?: ExerciseDef;
    onSave: (updatedSet: WorkoutSet) => Promise<void> | void;
    lang: Language;
}

const EditSetModal: React.FC<EditSetModalProps> = ({
    isOpen,
    onClose,
    set: initialSet,
    exerciseDef,
    onSave,
    lang
}) => {
    const [set, setSet] = useState<WorkoutSet>(initialSet);

    // Reset state when modal opens with a new set
    useEffect(() => {
        setSet(initialSet);
    }, [initialSet, isOpen]);

    const handleUpdate = (field: keyof WorkoutSet, value: any) => {
        setSet(prev => ({ ...prev, [field]: value }));
    };

    const handleSave = async () => {
        await onSave(set);
        onClose();
    };

    // Date/Time handling
    const setDate = new Date(set.timestamp);
    const dateStr = dateStrFromDate(setDate);
    const timeStr = timeStrFromDate(setDate);

    function dateStrFromDate(d: Date) {
        // YYYY-MM-DD
        const pad = (n: number) => n < 10 ? '0' + n : n;
        return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
    }

    function timeStrFromDate(d: Date) {
        // HH:mm
        const pad = (n: number) => n < 10 ? '0' + n : n;
        return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
    }

    const handleDateChange = (newDateStr: string) => {
        // Keep time, change date
        const current = new Date(set.timestamp);
        const [y, m, d] = newDateStr.split('-').map(Number);
        const newDate = new Date(y, m - 1, d, current.getHours(), current.getMinutes(), current.getSeconds());
        handleUpdate('timestamp', newDate.getTime());
    };

    const handleTimeChange = (newTimeStr: string) => {
        // Keep date, change time
        const current = new Date(set.timestamp);
        const [h, min] = newTimeStr.split(':').map(Number);
        const newDate = new Date(current.getFullYear(), current.getMonth(), current.getDate(), h, min, current.getSeconds());
        handleUpdate('timestamp', newDate.getTime());
    };

    // Determine functionality based on resolved type
    // Fallback: Check feature availability based on Type String or Prop existence
    const type = (exerciseDef?.type || set.type) as string;

    const hasWeight = ['STRENGTH', 'BODYWEIGHT', 'STATIC', 'Strength', 'Bodyweight', 'Static'].includes(type) || set.weight !== null;
    const hasReps = ['STRENGTH', 'BODYWEIGHT', 'PLYOMETRIC', 'Strength', 'Bodyweight', 'Plyometric'].includes(type) || set.reps !== null;
    const hasBwPercent = ['BODYWEIGHT', 'STATIC', 'Bodyweight', 'Static'].includes(type) || set.bodyWeightPercentage !== null;
    const hasTime = ['CARDIO', 'STATIC', 'Cardio', 'Static'].includes(type) || set.durationSeconds !== null;
    const hasDist = ['CARDIO', 'LONG_JUMP', 'Cardio', 'Long Jump'].includes(type) || set.distanceMeters !== null;
    const hasHeight = ['HIGH_JUMP', 'High Jump'].includes(type) || set.height !== null;

    return (
        <SideSheet
            isOpen={isOpen}
            onClose={onClose}
            title={t('edit_set', lang) || 'Edit Set'}
            width="md"
        >
            <div className="space-y-6">
                <div>
                    <h3 className="text-lg font-medium text-on-surface mb-1">
                        {set.exerciseName}
                    </h3>
                    <p className="text-sm text-on-surface-variant mb-2">
                        {exerciseDef?.type || set.type}
                    </p>
                    {set.side && (
                        <div className="flex items-center gap-2 bg-surface-container rounded-full p-1 w-fit">
                            <button
                                onClick={() => handleUpdate('side', 'LEFT')}
                                title={t('left', lang)}
                                className={`px-3 py-1.5 rounded-full text-xs font-medium transition-colors ${set.side === 'LEFT' ? 'bg-primary-container text-on-primary-container' : 'text-on-surface-variant hover:bg-surface-container-high'
                                    }`}
                            >
                                L
                            </button>
                            <button
                                onClick={() => handleUpdate('side', 'ALTERNATELY')}
                                title={t('alternately', lang)}
                                className={`px-3 py-1.5 rounded-full text-xs font-medium transition-colors ${set.side === 'ALTERNATELY' ? 'bg-tertiary-container text-on-tertiary-container' : 'text-on-surface-variant hover:bg-surface-container-high'
                                    }`}
                            >
                                A
                            </button>
                            <button
                                onClick={() => handleUpdate('side', 'RIGHT')}
                                title={t('right', lang)}
                                className={`px-3 py-1.5 rounded-full text-xs font-medium transition-colors ${set.side === 'RIGHT' ? 'bg-secondary-container text-on-secondary-container' : 'text-on-surface-variant hover:bg-surface-container-high'
                                    }`}
                            >
                                R
                            </button>
                        </div>
                    )}
                </div>

                {/* Date & Time */}
                <div className="grid grid-cols-2 gap-4">
                    <div className="bg-surface-container-high rounded px-3 py-2">
                        <label className="text-[10px] text-on-surface-variant font-bold flex gap-1 items-center mb-1">
                            <Calendar size={10} /> {t('date', lang) || 'Date'}
                        </label>
                        <input
                            type="date"
                            value={dateStr}
                            onChange={(e) => handleDateChange(e.target.value)}
                            className="w-full bg-transparent text-sm text-on-surface focus:outline-none"
                        />
                    </div>
                    <div className="bg-surface-container-high rounded px-3 py-2">
                        <label className="text-[10px] text-on-surface-variant font-bold flex gap-1 items-center mb-1">
                            <Clock size={10} /> {t('time', lang) || 'Time'}
                        </label>
                        <input
                            type="time"
                            value={timeStr}
                            onChange={(e) => handleTimeChange(e.target.value)}
                            className="w-full bg-transparent text-sm text-on-surface focus:outline-none"
                        />
                    </div>
                </div>

                {/* Metrics */}
                <div className="grid grid-cols-2 gap-3">
                    {hasWeight && (
                        <div className="bg-surface-container-high rounded px-3 py-2">
                            <label className="text-[10px] text-on-surface-variant flex gap-1 items-center mb-1"><Dumbbell size={10} /> {t('weight_kg', lang)}</label>
                            <input
                                type="number"
                                className="w-full bg-transparent text-lg text-on-surface focus:outline-none"
                                value={set.weight === 0 ? '' : (set.weight ?? '')}
                                onChange={(e) => handleUpdate('weight', parseFloat(e.target.value))}
                                placeholder="0"
                            />
                        </div>
                    )}
                    {hasReps && (
                        <div className="bg-surface-container-high rounded px-3 py-2">
                            <label className="text-[10px] text-on-surface-variant flex gap-1 items-center mb-1"><Activity size={10} /> {t('reps', lang)}</label>
                            <input
                                type="number"
                                className="w-full bg-transparent text-lg text-on-surface focus:outline-none"
                                value={set.reps === 0 ? '' : (set.reps ?? '')}
                                onChange={(e) => handleUpdate('reps', parseInt(e.target.value))}
                                placeholder="0"
                            />
                        </div>
                    )}
                    {hasBwPercent && (
                        <div className="bg-surface-container-high rounded px-3 py-2">
                            <label className="text-[10px] text-on-surface-variant flex gap-1 items-center mb-1"><Percent size={10} /> {t('body_weight_percent', lang)}</label>
                            <input
                                type="number"
                                className="w-full bg-transparent text-lg text-on-surface focus:outline-none"
                                value={set.bodyWeightPercentage === 0 ? '' : (set.bodyWeightPercentage ?? 100)}
                                onChange={(e) => handleUpdate('bodyWeightPercentage', parseFloat(e.target.value))}
                                placeholder="100"
                            />
                        </div>
                    )}
                    {hasTime && (
                        <div className="bg-surface-container-high rounded px-3 py-2">
                            <label className="text-[10px] text-on-surface-variant flex gap-1 items-center mb-1"><Timer size={10} /> {t('time_sec', lang)}</label>
                            <input
                                type="number"
                                className="w-full bg-transparent text-lg text-on-surface focus:outline-none"
                                value={set.durationSeconds === 0 ? '' : (set.durationSeconds ?? '')}
                                onChange={(e) => handleUpdate('durationSeconds', parseFloat(e.target.value))}
                                placeholder="0"
                            />
                        </div>
                    )}
                    {hasDist && (
                        <div className="bg-surface-container-high rounded px-3 py-2">
                            <label className="text-[10px] text-on-surface-variant flex gap-1 items-center mb-1"><ArrowRight size={10} /> {t('dist_m', lang)}</label>
                            <input
                                type="number"
                                className="w-full bg-transparent text-lg text-on-surface focus:outline-none"
                                value={set.distanceMeters === 0 ? '' : (set.distanceMeters ?? '')}
                                onChange={(e) => handleUpdate('distanceMeters', parseFloat(e.target.value))}
                                placeholder="0"
                            />
                        </div>
                    )}
                    {hasHeight && (
                        <div className="bg-surface-container-high rounded px-3 py-2">
                            <label className="text-[10px] text-on-surface-variant flex gap-1 items-center mb-1"><ArrowUp size={10} /> {t('height_cm', lang)}</label>
                            <input
                                type="number"
                                className="w-full bg-transparent text-lg text-on-surface focus:outline-none"
                                value={set.height === 0 ? '' : (set.height ?? '')}
                                onChange={(e) => handleUpdate('height', parseFloat(e.target.value))}
                                placeholder="0"
                            />
                        </div>
                    )}
                </div>

                <div className="flex justify-end pt-4 border-t border-outline-variant">
                    <Button onClick={handleSave}>
                        <Save size={16} className="mr-2" />
                        {t('save', lang)}
                    </Button>
                </div>
            </div>
        </SideSheet>
    );
};

export default EditSetModal;
