import { useState, useEffect } from 'react';
import { X, History, AlertTriangle, CheckCircle, Bug, Droplet } from 'lucide-react';
import { Batch } from '../../lib/batchesApi';
import { touchPointsApi, PlantTouchPoint } from '../../lib/touchPointsApi';

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

export default function BatchHealthHistoryModal({ batch, onClose }: BatchHealthHistoryModalProps) {
    const [history, setHistory] = useState<PlantTouchPoint[]>([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        touchPointsApi.getByBatch(batch.id).then(data => {
            // Filter for relevant health/IPM events
            const relevant = data.filter(tp =>
                ['INSPECT', 'IPM', 'FEED', 'WATER'].includes(tp.type)
            );
            setHistory(relevant);
            setLoading(false);
        }).catch(err => {
            console.error(err);
            setLoading(false);
        });
    }, [batch.id]);

    const getIcon = (type: string, issuesObserved?: boolean) => {
        if (type === 'INSPECT') {
            return issuesObserved ? <AlertTriangle className="text-red-500" /> : <CheckCircle className="text-[var(--color-primary)]" />;
        }
        if (type === 'IPM') return <Bug className="text-orange-500" />;
        if (type === 'WATER' || type === 'FEED') return <Droplet className="text-[var(--color-accent)]" />;
        return <History className="text-[var(--color-text-tertiary)]" />;
    };

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm animate-fade-in">
            <div className="bg-[var(--color-bg-elevated)] w-full max-w-2xl rounded-2xl shadow-2xl overflow-hidden animate-scale-in flex flex-col max-h-[90vh]">
                <div className="p-6 border-b border-[var(--color-border-default)] flex justify-between items-center shrink-0">
                    <div className="flex items-center gap-2">
                        <History className="text-[var(--color-text-tertiary)]" size={24} />
                        <h2 className="text-xl font-bold dark:text-white">Batch Health History</h2>
                    </div>
                    <button onClick={onClose} className="text-[var(--color-text-tertiary)] hover:text-slate-700 dark:hover:text-slate-300">
                        <X size={24} />
                    </button>
                </div>

                <div className="p-4 bg-[var(--color-bg-tertiary)] border-b border-[var(--color-border-default)] shrink-0">
                    <h3 className="font-bold text-[var(--color-text-primary)]">{batch.name}</h3>
                    <p className="text-sm text-[var(--color-text-tertiary)]">{batch.strain} &bull; {batch.room?.name || 'No Room'}</p>
                </div>

                <div className="overflow-y-auto p-6 space-y-6">
                    {loading ? (
                        <div className="text-center text-[var(--color-text-tertiary)] py-10">Loading history...</div>
                    ) : history.length === 0 ? (
                        <div className="text-center text-[var(--color-text-tertiary)] py-10 italic">No health or maintenance records found.</div>
                    ) : (
                        <div className="relative border-l-2 border-[var(--color-border-default)] ml-4 space-y-8">
                            {history.map((record) => (
                                <div key={record.id} className="relative pl-8">
                                    <div className={`absolute -left-[9px] top-0 w-4 h-4 rounded-full border-2 border-white dark:border-slate-900 ${record.issuesObserved ? 'bg-red-500' :
                                            record.type === 'IPM' ? 'bg-orange-400' : 'bg-slate-300 dark:bg-slate-600'
                                        }`} />

                                    <div className="bg-[var(--color-bg-elevated)] p-4 rounded-xl border border-slate-100 dark:border-slate-700 shadow-sm">
                                        <div className="flex justify-between items-start mb-2">
                                            <div className="flex items-center gap-2">
                                                {getIcon(record.type, record.issuesObserved)}
                                                <span className="font-bold text-[var(--color-text-primary)]">
                                                    {record.type === 'INSPECT' ? 'Scouting Report' :
                                                        record.type === 'IPM' ? 'IPM Application' : record.type}
                                                </span>
                                            </div>
                                            <span className="text-xs text-[var(--color-text-tertiary)]">
                                                {new Date(record.createdAt).toLocaleString()}
                                            </span>
                                        </div>

                                        {record.notes && (
                                            <p className="text-slate-600 dark:text-slate-300 text-sm italic mb-2">
                                                "{record.notes}"
                                            </p>
                                        )}

                                        {record.type === 'IPM' && record.ipmProduct && (
                                            <div className="text-xs bg-orange-50 dark:bg-orange-900/20 text-orange-800 dark:text-orange-200 px-2 py-1 rounded inline-block">
                                                Applied: {record.ipmProduct} {record.ipmDosage && `(${record.ipmDosage})`}
                                            </div>
                                        )}

                                        {record.issuesObserved && (
                                            <div className="flex gap-2 mt-2">
                                                <span className="text-xs font-bold bg-red-100 text-red-700 px-2 py-1 rounded">
                                                    ISSUE DETECTED
                                                </span>
                                                {record.issueType && (
                                                    <span className="text-xs bg-[var(--color-bg-tertiary)] text-slate-600 dark:text-slate-300 px-2 py-1 rounded">
                                                        {record.issueType}
                                                    </span>
                                                )}
                                            </div>
                                        )}

                                        <p className="text-xs text-[var(--color-text-tertiary)] mt-2">
                                            Logged by {record.user?.name || 'Unknown'}
                                        </p>
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}
