import React, { useState, useEffect } from 'react';
import { Timer, Play, Pause, RotateCcw, Edit2, Plus, Minus, X, Check } from 'lucide-react';
import { useRestTimer } from '../../hooks/useRestTimer';

interface RestTimerFABProps {
    timer: ReturnType<typeof useRestTimer>;
    onDurationChange?: (newDuration: number) => void;
}

const RestTimerFAB: React.FC<RestTimerFABProps> = ({ timer, onDurationChange }) => {
    const { timeLeft, status, start, pause, reset, setDuration } = timer;

    // Render Helpers (moved up for initial state calculation)
    const formatSeconds = (sec: number) => {
        const m = Math.floor(sec / 60);
        const s = sec % 60;
        return `${m}:${s.toString().padStart(2, '0')}`;
    };

    const [isExpanded, setIsExpanded] = useState(false);
    const [isEditing, setIsEditing] = useState(false);
    const [editValue, setEditValue] = useState(120);
    const [inputValue, setInputValue] = useState(formatSeconds(120));

    // Auto-expand when running if not already expanded? No, requirement says "when time is running, show digits of the countdown on the enlarged timer FAB even if the menu is collapsed".
    // So the FAB itself grows.

    // Effects
    useEffect(() => {
        if (status === 'FINISHED') {
            setIsExpanded(false);
            setIsEditing(false);
        }
    }, [status]);

    useEffect(() => {
        // Sync input value when editValue changes (externally or via +/- buttons)
        setInputValue(formatSeconds(editValue));
    }, [editValue]);

    const handleToggle = () => {
        if (isEditing) return; // Don't toggle if editing
        setIsExpanded(!isExpanded);
    };

    const handleStartPause = (e: React.MouseEvent) => {
        e.stopPropagation();
        if (status === 'RUNNING') pause();
        else start();
    };

    const handleReset = (e: React.MouseEvent) => {
        e.stopPropagation();
        reset();
    };

    const handleEdit = (e: React.MouseEvent) => {
        e.stopPropagation();
        const initialVal = timeLeft > 0 ? timeLeft : 120;
        setEditValue(initialVal);
        setInputValue(formatSeconds(initialVal));
        setIsEditing(true);
        setIsExpanded(true); // Keep expanded
    };

    const saveEdit = (e: React.MouseEvent) => {
        e.stopPropagation();
        // Ensure we capture any pending input value on save
        // (Though blur usually handles it, explicit save should too)
        let finalVal = editValue;

        // Try parsing current input just in case
        if (inputValue.includes(':')) {
            const [m, s] = inputValue.split(':').map(Number);
            if (!isNaN(m) && !isNaN(s)) finalVal = m * 60 + s;
        } else if (/^\d+$/.test(inputValue)) {
            const v = parseInt(inputValue, 10);
            if (!isNaN(v)) finalVal = v;
        }

        reset(finalVal);
        if (onDurationChange) onDurationChange(finalVal);
        setIsEditing(false);
        setIsExpanded(true); // Keep expanded per user request
    };

    const adjustEdit = (curr: number, delta: number) => {
        return Math.max(0, curr + delta);
    };

    const isRunningOrPaused = status === 'RUNNING' || status === 'PAUSED';
    const isFinished = status === 'FINISHED';

    // Base classes
    const fabBaseClasses = `fixed bottom-24 right-6 shadow-elevation-3 transition-all duration-300 z-50 flex items-center justify-center font-medium`;

    // Dimensions and Colors
    let fabClasses = fabBaseClasses;
    let content = null;

    const handleInputBlur = () => {
        let val = 0;
        if (inputValue.includes(':')) {
            const [m, s] = inputValue.split(':').map(Number);
            if (!isNaN(m) && !isNaN(s)) val = m * 60 + s;
        } else {
            val = parseInt(inputValue, 10);
        }

        if (!isNaN(val)) {
            setEditValue(val);
            setInputValue(formatSeconds(val)); // Re-format to standardized look
        } else {
            setInputValue(formatSeconds(editValue)); // Revert if invalid
        }
    };

    if (isFinished) {
        fabClasses += ` w-14 h-14 rounded-[16px] bg-error text-on-error animate-pulse`;
        content = <Timer size={24} />;
    } else if (isRunningOrPaused && !isExpanded) {
        // Requirements: "when time is running, show digits of the countdown on the enlarged timer FAB even if the menu is collapsed"
        // So it should be wide enough to show digits.
        fabClasses += ` h-14 rounded-[16px] bg-primary-container text-on-primary-container px-4 min-w-[56px] cursor-pointer hover:brightness-95`;
        content = (
            <div className="flex items-center gap-2 pointer-events-none">
                <span className="font-mono text-lg font-bold">{formatSeconds(timeLeft)}</span>
            </div>
        );
    } else if (isExpanded) {
        // Expanded: No common background, just a column of buttons right-aligned (Speed Dial)
        fabClasses += ` w-auto bg-transparent flex-col-reverse items-end justify-end pb-0 overflow-visible`;

        content = (
            <div className="flex flex-col items-end gap-3 pointer-events-auto">
                {/* Options List (Bottom to Top) */}
                {isEditing ? (
                    <div className="flex flex-col items-end gap-2 animate-in slide-in-from-bottom-4 fade-in duration-200 mb-2 mr-1">
                        <button onClick={(e) => setEditValue(v => adjustEdit(v, 5))} className="w-10 h-10 flex items-center justify-center bg-surface-container-high text-on-surface rounded-full shadow-elevation-2 hover:brightness-110"><Plus size={20} /></button>

                        {/* Manual Input Field */}
                        <div className="bg-surface-container shadow-sm rounded px-2 py-1 my-1 flex items-center justify-center">
                            <input
                                type="text"
                                className="bg-transparent text-on-surface font-mono font-bold text-lg text-right w-[5.4ch] focus:outline-none"
                                value={inputValue}
                                onChange={(e) => {
                                    let val = e.target.value;

                                    // Filter non-digits and non-colon
                                    val = val.replace(/[^0-9:]/g, '');

                                    // Limit length to 5
                                    if (val.length > 5) {
                                        val = val.substring(0, 5);
                                    }

                                    // Validate Seconds part if colon exists
                                    if (val.includes(':')) {
                                        const parts = val.split(':');
                                        if (parts.length > 1) {
                                            const minutes = parts[0];
                                            let seconds = parts[1];

                                            // Clamp seconds to 59
                                            if (seconds.length > 0) {
                                                const secNum = parseInt(seconds, 10);
                                                if (!isNaN(secNum) && secNum > 59) {
                                                    seconds = '59';
                                                }
                                            }
                                            val = `${minutes}:${seconds}`;
                                        }
                                    }

                                    setInputValue(val);
                                }}
                                onFocus={(e) => e.target.select()}
                                onBlur={handleInputBlur}
                                onKeyDown={(e) => {
                                    if (e.key === 'Enter') e.currentTarget.blur();
                                }}
                                placeholder="00:00"
                            />
                        </div>

                        <button onClick={(e) => setEditValue(v => adjustEdit(v, -5))} className="w-10 h-10 flex items-center justify-center bg-surface-container-high text-on-surface rounded-full shadow-elevation-2 hover:brightness-110"><Minus size={20} /></button>
                        <button onClick={saveEdit} className="w-10 h-10 flex items-center justify-center bg-primary text-on-primary rounded-full shadow-elevation-2 mt-1 hover:brightness-110" aria-label="Save"><Check size={20} /></button>
                    </div>
                ) : (
                    <div className="flex flex-col items-end gap-3 animate-in slide-in-from-bottom-4 fade-in duration-200 mb-4 mr-1">
                        {/* Mini FABs */}
                        <button onClick={handleEdit} className="w-10 h-10 flex items-center justify-center bg-surface-container-high text-on-surface hover:text-primary rounded-full shadow-elevation-2 hover:scale-110 transition-all" aria-label="Edit">
                            <Edit2 size={18} />
                        </button>

                        <button onClick={handleReset} className="w-10 h-10 flex items-center justify-center bg-surface-container-high text-on-surface hover:text-primary rounded-full shadow-elevation-2 hover:scale-110 transition-all" aria-label="Reset">
                            <RotateCcw size={18} />
                        </button>

                        <button onClick={handleStartPause} className="w-12 h-12 flex items-center justify-center bg-primary-container text-on-primary-container rounded-full shadow-elevation-2 hover:scale-110 transition-all" aria-label={status === 'RUNNING' ? 'Pause' : 'Start'}>
                            {status === 'RUNNING' ? <Pause size={24} /> : <Play size={24} className="ml-1" />}
                        </button>
                    </div>
                )}

                {/* Main Toggle Button (Bottom) */}
                <button
                    onClick={handleToggle}
                    className={`w-16 h-16 rounded-full flex items-center justify-center shadow-elevation-3 hover:scale-105 transition-all active:scale-95 ${isEditing
                        ? 'bg-error-container text-on-error-container hover:bg-error-container/80' // Light Red for cancel/close
                        : 'bg-primary text-on-primary'
                        }`}
                >
                    {isEditing ? <X size={28} /> : <span className="font-mono text-sm font-bold">{formatSeconds(timeLeft)}</span>}
                </button>
            </div>
        );
    } else {
        // Idle state
        fabClasses += ` w-14 h-14 rounded-[16px] bg-secondary-container text-on-secondary-container hover:brightness-95 cursor-pointer`;
        content = (
            <div className="w-full h-full flex items-center justify-center pointer-events-none">
                <Timer size={24} />
            </div>
        );

    }

    if (isExpanded) {
        // Override base classes for expanded state - remove shadow/bg from container
        fabClasses = `fixed bottom-24 right-6 z-50 flex flex-col items-end pointer-events-none`; // pointer-events-none prevents container from blocking clicks, children have pointer-events-auto
    }

    return (
        <div className={fabClasses} onClick={!isExpanded ? handleToggle : undefined}>
            {content}
        </div>
    );
};

export default RestTimerFAB;
