import { useState, useEffect } from 'react';
import { X, Save, Bug, Calendar, Check } from 'lucide-react';
import { Batch } from '../lib/batchesApi';
import { ipmSchedulesApi, IPMSchedule } from '../lib/ipmSchedulesApi';

interface IPMScheduleModalProps {
    batch: Batch;
    onClose: () => void;
}

export default function IPMScheduleModal({ batch, onClose }: IPMScheduleModalProps) {
    const [schedule, setSchedule] = useState<IPMSchedule | null>(null);
    const [product, setProduct] = useState('');
    const [intervalDays, setIntervalDays] = useState(7);
    const [lastTreatment, setLastTreatment] = useState('');
    const [isActive, setIsActive] = useState(true);
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);

    useEffect(() => {
        loadSchedule();
    }, [batch.id]);

    const loadSchedule = async () => {
        try {
            const data = await ipmSchedulesApi.get(batch.id);
            if (data) {
                setSchedule(data);
                setProduct(data.product);
                setIntervalDays(data.intervalDays);
                setLastTreatment(data.lastTreatment ? data.lastTreatment.split('T')[0] : '');
                setIsActive(data.isActive);
            }
        } catch (error) {
            console.error(error);
        } finally {
            setLoading(false);
        }
    };

    const handleSave = async (e: React.FormEvent) => {
        e.preventDefault();
        setSaving(true);
        try {
            await ipmSchedulesApi.upsert(batch.id, {
                product,
                intervalDays,
                lastTreatment: lastTreatment || null,
                isActive
            });
            onClose();
        } catch (error) {
            console.error(error);
            alert('Failed to save schedule');
        } finally {
            setSaving(false);
        }
    };

    const calculateNextDate = () => {
        if (!lastTreatment) return 'Not scheduled';
        const date = new Date(lastTreatment);
        date.setDate(date.getDate() + intervalDays);
        return date.toLocaleDateString();
    };

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm animate-in">
            <div className="bg-elevated w-full max-w-md rounded-lg shadow-xl border border-default overflow-hidden animate-scale-in">
                {/* Header */}
                <div className="px-5 py-4 border-b border-default flex justify-between items-center">
                    <h2 className="text-lg font-semibold text-primary flex items-center gap-2">
                        <Bug size={18} className="text-destructive" />
                        IPM Schedule
                    </h2>
                    <button onClick={onClose} className="p-2 hover:bg-tertiary rounded-md transition-colors duration-fast">
                        <X size={16} className="text-secondary" />
                    </button>
                </div>

                {/* Batch Info */}
                <div className="px-5 py-3 bg-tertiary border-b border-subtle">
                    <h3 className="font-medium text-primary text-sm">{batch.name}</h3>
                    <p className="text-xs text-tertiary">{batch.strain} • {batch.room?.name || 'No Room'}</p>
                </div>

                {loading ? (
                    <div className="p-8 text-center text-secondary">Loading schedule...</div>
                ) : (
                    <form onSubmit={handleSave} className="p-5 space-y-5">
                        <div>
                            <label className="block text-sm font-medium text-secondary mb-1.5">Preventative Product</label>
                            <input
                                type="text"
                                value={product}
                                onChange={(e) => setProduct(e.target.value)}
                                className="input w-full"
                                placeholder="e.g. Pyganic 5.0, Lost Coast Plant Therapy"
                                required
                            />
                        </div>

                        <div className="grid grid-cols-2 gap-4">
                            <div>
                                <label className="block text-sm font-medium text-secondary mb-1.5">Interval (Days)</label>
                                <input
                                    type="number"
                                    min="1"
                                    value={intervalDays}
                                    onChange={(e) => setIntervalDays(parseInt(e.target.value) || 1)}
                                    className="input w-full"
                                />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-secondary mb-1.5">Last Treatment</label>
                                <input
                                    type="date"
                                    value={lastTreatment}
                                    onChange={(e) => setLastTreatment(e.target.value)}
                                    className="input w-full"
                                />
                            </div>
                        </div>

                        {lastTreatment && (
                            <div className="p-3 bg-accent-muted rounded-md flex items-center gap-3">
                                <Calendar size={16} className="text-accent" />
                                <div>
                                    <p className="text-[10px] font-medium text-accent uppercase">Next Treatment</p>
                                    <p className="text-sm font-medium text-primary">{calculateNextDate()}</p>
                                </div>
                            </div>
                        )}

                        {/* Active Toggle */}
                        <button
                            type="button"
                            onClick={() => setIsActive(!isActive)}
                            className={`w-full flex items-center justify-between p-4 rounded-md border transition-colors duration-fast ${isActive
                                    ? 'bg-success-muted border-success/30'
                                    : 'bg-tertiary border-subtle'
                                }`}
                        >
                            <span className="font-medium text-primary">Schedule Active</span>
                            <div className={`w-6 h-6 rounded-md flex items-center justify-center ${isActive ? 'bg-success text-white' : 'bg-subtle'
                                }`}>
                                {isActive && <Check size={14} />}
                            </div>
                        </button>

                        <div className="flex gap-3 pt-2">
                            <button type="button" onClick={onClose} className="btn btn-secondary flex-1">
                                Cancel
                            </button>
                            <button type="submit" disabled={saving} className="btn btn-primary flex-1">
                                <Save size={16} />
                                {saving ? 'Saving...' : 'Save'}
                            </button>
                        </div>
                    </form>
                )}
            </div>
        </div>
    );
}
