import { useState, useEffect } from 'react';
import { X, Camera, Save, Sprout, Droplets, Scissors, Search, Bug } from 'lucide-react';
import { touchPointsApi, TouchType } from '../../lib/touchPointsApi';
import api from '../../lib/api';

interface Batch {
    id: string;
    name: string;
    strain: string;
}

interface TouchPointModalProps {
    isOpen: boolean;
    onClose: () => void;
    preselectedBatchId?: string;
    onSuccess?: () => void;
}

const TOUCH_TYPES: { type: TouchType; label: string; icon: any; color: string }[] = [
    { type: 'WATER', label: 'Water', icon: Droplets, color: 'bg-blue-100 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400' },
    { type: 'FEED', label: 'Feed', icon: Sprout, color: 'bg-emerald-100 text-[var(--color-primary)] dark:bg-emerald-900/30 dark:text-emerald-400' },
    { type: 'PRUNE', label: 'Prune', icon: Scissors, color: 'bg-orange-100 text-orange-600 dark:bg-orange-900/30 dark:text-orange-400' },
    { type: 'TRAIN', label: 'Train', icon: Search, color: 'bg-purple-100 text-purple-600 dark:bg-purple-900/30 dark:text-purple-400' },
    { type: 'IPM', label: 'IPM / Pest', icon: Bug, color: 'bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400' },
    { type: 'INSPECT', label: 'Inspect', icon: Search, color: 'bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-[var(--color-text-tertiary)]' },
];

export default function TouchPointModal({ isOpen, onClose, preselectedBatchId, onSuccess }: TouchPointModalProps) {
    const [batches, setBatches] = useState<Batch[]>([]);
    const [selectedBatchId, setSelectedBatchId] = useState<string>(preselectedBatchId || '');
    const [selectedType, setSelectedType] = useState<TouchType | null>(null);
    const [notes, setNotes] = useState('');
    const [isLoading, setIsLoading] = useState(false);

    // Load batches if not preselected
    useEffect(() => {
        if (isOpen && !preselectedBatchId) {
            api.get('/batches').then(res => setBatches(res.data));
        }
    }, [isOpen, preselectedBatchId]);

    useEffect(() => {
        if (preselectedBatchId) setSelectedBatchId(preselectedBatchId);
    }, [preselectedBatchId]);

    const handleSubmit = async () => {
        if (!selectedBatchId || !selectedType) return;

        setIsLoading(true);
        try {
            await touchPointsApi.create({
                batchId: selectedBatchId,
                type: selectedType,
                notes
            });
            onSuccess?.();
            onClose();
            // Reset form
            setSelectedType(null);
            setNotes('');
        } catch (error) {
            console.error('Failed to log touch point', error);
            alert('Failed to save. Please try again.');
        } finally {
            setIsLoading(false);
        }
    };

    if (!isOpen) return null;

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm animate-in fade-in duration-200">
            <div className="bg-[var(--color-bg-elevated)] w-full max-w-md rounded-2xl shadow-xl overflow-hidden flex flex-col max-h-[90vh]">

                {/* Header */}
                <div className="p-4 border-b border-[var(--color-border-subtle)] flex justify-between items-center">
                    <h2 className="text-xl font-bold text-[var(--color-text-primary)]">Log Plant Touch</h2>
                    <button onClick={onClose} className="p-2 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-full">
                        <X size={20} className="text-[var(--color-text-tertiary)]" />
                    </button>
                </div>

                {/* Content */}
                <div className="p-4 overflow-y-auto space-y-6">

                    {/* Batch Selection (if not preselected) */}
                    {!preselectedBatchId && (
                        <div>
                            <label className="block text-sm font-medium text-[var(--color-text-secondary)] mb-2">
                                Select Batch
                            </label>
                            <select
                                value={selectedBatchId}
                                onChange={(e) => setSelectedBatchId(e.target.value)}
                                className="w-full p-3 bg-[var(--color-bg-tertiary)] border-none rounded-xl text-[var(--color-text-primary)] focus:ring-2 focus:ring-emerald-500"
                            >
                                <option value="">-- Select Batch --</option>
                                {batches.map(b => (
                                    <option key={b.id} value={b.id}>{b.name} ({b.strain})</option>
                                ))}
                            </select>
                        </div>
                    )}

                    {/* Touch Type Grid */}
                    <div>
                        <label className="block text-sm font-medium text-[var(--color-text-secondary)] mb-2">
                            Action Type
                        </label>
                        <div className="grid grid-cols-3 gap-3">
                            {TOUCH_TYPES.map(({ type, label, icon: Icon, color }) => (
                                <button
                                    key={type}
                                    onClick={() => setSelectedType(type)}
                                    className={`flex flex-col items-center justify-center p-3 rounded-xl gap-2 transition-all ${selectedType === type
                                        ? 'ring-2 ring-emerald-500 ring-offset-2 ring-offset-[var(--color-bg-primary)] bg-[var(--color-bg-tertiary)]'
                                        : 'hover:bg-[var(--color-bg-tertiary)] border border-[var(--color-border-subtle)]'
                                        }`}
                                >
                                    <div className={`p-2 rounded-full ${color}`}>
                                        <Icon size={20} />
                                    </div>
                                    <span className="text-xs font-medium text-slate-600 dark:text-[var(--color-text-tertiary)]">{label}</span>
                                </button>
                            ))}
                        </div>
                    </div>

                    {/* Notes */}
                    <div>
                        <label className="block text-sm font-medium text-[var(--color-text-secondary)] mb-2">
                            Notes
                        </label>
                        <textarea
                            value={notes}
                            onChange={(e) => setNotes(e.target.value)}
                            placeholder="Details about the action..."
                            className="w-full p-3 bg-[var(--color-bg-tertiary)] border-none rounded-xl text-[var(--color-text-primary)] focus:ring-2 focus:ring-emerald-500 min-h-[100px] resize-none"
                        />
                    </div>

                    {/* Photo Placeholder */}
                    <button className="w-full p-4 border-2 border-dashed border-[var(--color-border-default)] rounded-xl text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-tertiary)] flex items-center justify-center gap-2">
                        <Camera size={20} />
                        <span>Add Photo (Optional)</span>
                    </button>

                </div>

                {/* Footer */}
                <div className="p-4 border-t border-[var(--color-border-subtle)]">
                    <button
                        onClick={handleSubmit}
                        disabled={!selectedBatchId || !selectedType || isLoading}
                        className="w-full py-4 bg-[var(--color-primary)] hover:bg-[var(--color-primary-hover)] disabled:opacity-50 disabled:cursor-not-allowed text-white font-bold rounded-xl flex items-center justify-center gap-2 transition-all active:scale-[0.98]"
                    >
                        {isLoading ? (
                            <span>Saving...</span>
                        ) : (
                            <>
                                <Save size={20} />
                                <span>Log Touch Point</span>
                            </>
                        )}
                    </button>
                </div>
            </div>
        </div>
    );
}
