'use client';

import { useState, useRef, useEffect, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { X, Check, Keyboard } from 'lucide-react';

interface ScrollWheelLoggerProps {
    substance: 'nicotine' | 'weed';
    onSubmit: (count: number, substance: 'nicotine' | 'weed') => void;
    onCancel: () => void;
}

export function ScrollWheelLogger({ substance, onSubmit, onCancel }: ScrollWheelLoggerProps) {
    const [selectedValue, setSelectedValue] = useState(1);
    const [showCustom, setShowCustom] = useState(false);
    const [customValue, setCustomValue] = useState('');
    const scrollRef = useRef<HTMLDivElement>(null);

    const isNicotine = substance === 'nicotine';
    const colors = isNicotine
        ? {
            border: 'border-red-500/30',
            bg: 'bg-red-500/5',
            bgMuted: 'bg-red-500/10',
            bgActive: 'bg-red-500/20',
            bgSolid: 'bg-red-600',
            bgSolidHover: 'hover:bg-red-500',
            text: 'text-red-400',
            dot: 'bg-red-500',
            shadow: 'shadow-red-500/20'
        }
        : {
            border: 'border-green-500/30',
            bg: 'bg-green-500/5',
            bgMuted: 'bg-green-500/10',
            bgActive: 'bg-green-500/20',
            bgSolid: 'bg-green-600',
            bgSolidHover: 'hover:bg-green-500',
            text: 'text-green-400',
            dot: 'bg-green-500',
            shadow: 'shadow-green-500/20'
        };

    const label = isNicotine ? 'Puffs/Cigarettes' : 'Hits';

    // Generate values 1-100
    const values = Array.from({ length: 100 }, (_, i) => i + 1);

    const handleScroll = useCallback(() => {
        if (!scrollRef.current) return;
        const container = scrollRef.current;
        const itemHeight = 60; // Expected height of each item
        const scrollTop = container.scrollTop;
        const index = Math.round(scrollTop / itemHeight);
        const value = values[Math.max(0, Math.min(index, values.length - 1))];
        if (value !== selectedValue) {
            setSelectedValue(value);
        }
    }, [selectedValue, values]);

    const selectValue = (val: number) => {
        if (!scrollRef.current) return;
        const itemHeight = 60;
        scrollRef.current.scrollTo({
            top: (val - 1) * itemHeight,
            behavior: 'smooth'
        });
        setSelectedValue(val);
    };

    const handleConfirm = () => {
        const finalValue = showCustom ? parseInt(customValue, 10) : selectedValue;
        if (!isNaN(finalValue) && finalValue > 0) {
            onSubmit(finalValue, substance);
        }
    };

    // Keyboard support for enter key
    useEffect(() => {
        const handleKeyDown = (e: KeyboardEvent) => {
            if (e.key === 'Enter') {
                handleConfirm();
            } else if (e.key === 'Escape') {
                onCancel();
            }
        };
        window.addEventListener('keydown', handleKeyDown);
        return () => window.removeEventListener('keydown', handleKeyDown);
    }, [selectedValue, customValue, showCustom, substance]);

    return (
        <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-4">
            {/* Backdrop */}
            <div
                className="absolute inset-0 bg-black/60 backdrop-blur-sm transition-opacity"
                onClick={onCancel}
            />

            {/* Modal Container */}
            <div className="relative w-full max-w-sm glass-card overflow-hidden shadow-2xl animate-in slide-in-from-bottom duration-300">
                <div className={`p-4 border-b border-white/10 flex items-center justify-between ${colors.bgMuted}`}>
                    <div className="flex items-center gap-2">
                        <div className={`w-3 h-3 rounded-full ${colors.dot} animate-pulse`} />
                        <h3 className="font-black uppercase tracking-widest text-sm opacity-80">
                            Log {substance}
                        </h3>
                    </div>
                    <button
                        onClick={onCancel}
                        className="p-1 hover:bg-white/10 rounded-full transition-colors"
                    >
                        <X className="w-5 h-5 opacity-50" />
                    </button>
                </div>

                <div className="p-8 flex flex-col items-center">
                    <p className="text-sm opacity-60 mb-6 uppercase tracking-tighter font-bold">
                        Select {label}
                    </p>

                    {!showCustom ? (
                        <div className="relative h-[180px] w-full flex items-center justify-center overflow-hidden">
                            {/* Selection Highlight */}
                            <div className={`absolute top-1/2 -translate-y-1/2 w-full h-[60px] border-y ${colors.border} ${colors.bg}`} />

                            {/* Scroll Area */}
                            <div
                                ref={scrollRef}
                                onScroll={handleScroll}
                                className="w-full h-full overflow-y-scroll overflow-x-hidden snap-y snap-mandatory no-scrollbar py-[60px]"
                            >
                                {values.map((val) => (
                                    <div
                                        key={val}
                                        onClick={() => selectValue(val)}
                                        className={`h-[60px] flex items-center justify-center snap-center cursor-pointer transition-all duration-300 ${selectedValue === val
                                            ? `text-4xl font-black ${colors.text} scale-110`
                                            : 'text-lg opacity-20 scale-90'
                                            }`}
                                    >
                                        {val}
                                    </div>
                                ))}
                            </div>
                        </div>
                    ) : (
                        <div className="h-[180px] w-full flex flex-col items-center justify-center gap-4">
                            <Input
                                type="number"
                                placeholder="0"
                                value={customValue}
                                onChange={(e) => setCustomValue(e.target.value)}
                                autoFocus
                                className={`text-center text-5xl h-24 font-black bg-transparent border-none focus-visible:ring-0 ${colors.text} placeholder:opacity-10`}
                            />
                            <p className="text-xs opacity-40">Enter custom amount</p>
                        </div>
                    )}

                    <div className="mt-8 flex items-center gap-4 w-full">
                        <Button
                            variant="ghost"
                            size="icon"
                            onClick={() => {
                                setShowCustom(!showCustom);
                                if (!showCustom) setCustomValue(selectedValue.toString());
                            }}
                            className={`rounded-full h-12 w-12 border border-white/5 transition-all ${showCustom ? `${colors.bgActive} ${colors.text} ${colors.border}` : 'hover:bg-white/5'}`}
                        >
                            <Keyboard className="w-5 h-5 " />
                        </Button>

                        <Button
                            onClick={handleConfirm}
                            className={`flex-1 h-12 rounded-full font-black uppercase tracking-widest shadow-lg ${colors.shadow} transition-all hover:scale-[1.02] active:scale-95 ${colors.bgSolid} ${colors.bgSolidHover} text-white border-none`}
                        >
                            <Check className="w-5 h-5 mr-2" />
                            Log {showCustom ? customValue || '?' : selectedValue}
                        </Button>
                    </div>
                </div>
            </div>
        </div>
    );
}
