import { useState, useEffect } from 'react';
import { batchesApi, Batch } from '../lib/batchesApi';
import { touchPointsApi } from '../lib/touchPointsApi';
import { AlertTriangle, CheckCircle, Calendar, Shield, X, Loader2 } from 'lucide-react';
import { PageHeader, EmptyState, CardSkeleton } from '../components/ui/LinearPrimitives';
import { useToast } from '../context/ToastContext';

export default function IPMDashboardPage() {
    const { addToast } = useToast();
    const [batches, setBatches] = useState<Batch[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [recordingBatch, setRecordingBatch] = useState<Batch | null>(null);
    const [product, setProduct] = useState('Pyganic 5.0');
    const [dosage, setDosage] = useState('');
    const [submitting, setSubmitting] = useState(false);

    useEffect(() => {
        loadData();
    }, []);

    const loadData = async () => {
        setIsLoading(true);
        try {
            const all = await batchesApi.getAll();
            setBatches(all.filter(b => b.status === 'ACTIVE'));
        } catch (e) {
            console.error(e);
        } finally {
            setIsLoading(false);
        }
    };

    const handleStartPlan = async (batchId: string) => {
        if (!confirm('Start 10-day Pyganic 5.0 Root Drench cycle?')) return;
        try {
            await touchPointsApi.saveSchedule({
                batchId,
                product: 'Pyganic 5.0',
                intervalDays: 10
            });
            addToast('IPM plan started', 'success');
            loadData();
        } catch (e) {
            addToast('Failed to start plan', 'error');
        }
    };

    const handleRecordTreatment = async () => {
        if (!recordingBatch) return;
        setSubmitting(true);
        try {
            await touchPointsApi.create({
                batchId: recordingBatch.id,
                type: 'IPM',
                ipmProduct: product,
                ipmDosage: dosage,
                notes: `Scheduled IPM Treatment: ${product}`,
            });
            setRecordingBatch(null);
            loadData();
            addToast('Treatment recorded!', 'success');
        } catch (e) {
            addToast('Failed to record', 'error');
        } finally {
            setSubmitting(false);
        }
    };

    if (isLoading) {
        return (
            <div className="space-y-6 animate-in">
                <PageHeader title="IPM Dashboard" subtitle="Integrated pest management tracking" />
                <div className="grid gap-3">
                    {Array.from({ length: 4 }).map((_, i) => <CardSkeleton key={i} />)}
                </div>
            </div>
        );
    }

    return (
        <div className="space-y-6 animate-in">
            <PageHeader
                title="IPM Dashboard"
                subtitle="Root drench schedule and pest management tracking"
            />

            {batches.length === 0 ? (
                <EmptyState
                    icon={Shield}
                    title="No active batches"
                    description="Create a batch to start IPM tracking."
                />
            ) : (
                <div className="grid gap-3">
                    {batches.map(batch => {
                        const schedule = batch.ipmSchedule;

                        if (!schedule) {
                            return (
                                <div key={batch.id} className="card p-4 flex justify-between items-center opacity-75 hover:opacity-100 transition-opacity duration-fast">
                                    <div>
                                        <h3 className="font-medium text-primary text-sm">{batch.name}</h3>
                                        <p className="text-xs text-tertiary">No Active Plan</p>
                                    </div>
                                    <button
                                        onClick={() => handleStartPlan(batch.id)}
                                        className="btn btn-secondary text-xs h-8"
                                    >
                                        Start Plan
                                    </button>
                                </div>
                            );
                        }

                        const nextDate = new Date(schedule.nextTreatment);
                        const today = new Date();
                        const diffTime = nextDate.getTime() - today.getTime();
                        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

                        let statusBadge = 'badge-success';
                        let statusText = `Due in ${diffDays} days`;
                        let StatusIcon = Calendar;

                        if (diffDays <= 0) {
                            statusBadge = 'badge-destructive';
                            statusText = diffDays === 0 ? 'DUE TODAY' : `OVERDUE (${Math.abs(diffDays)} days)`;
                            StatusIcon = AlertTriangle;
                        } else if (diffDays <= 3) {
                            statusBadge = 'badge-warning';
                        }

                        return (
                            <div key={batch.id} className="card p-4">
                                <div className="flex justify-between items-start mb-4">
                                    <div>
                                        <h3 className="font-medium text-primary text-sm">{batch.name}</h3>
                                        <p className="text-xs text-tertiary">
                                            {schedule.intervalDays}-Day Cycle ({batch.ipmSchedule?.product || 'Pyganic'})
                                        </p>
                                    </div>
                                    <span className={`badge ${statusBadge} flex items-center gap-1`}>
                                        <StatusIcon size={10} />
                                        {statusText}
                                    </span>
                                </div>

                                <button
                                    onClick={() => setRecordingBatch(batch)}
                                    className="btn btn-ghost w-full justify-center text-success hover:bg-success-muted"
                                >
                                    <CheckCircle size={16} />
                                    Record Treatment
                                </button>
                            </div>
                        );
                    })}
                </div>
            )}

            {/* Recording Modal */}
            {recordingBatch && (
                <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 animate-fade-in">
                    <div className="card w-full max-w-md p-6 space-y-4 animate-scale-in">
                        <div className="flex justify-between items-start">
                            <div>
                                <h2 className="text-lg font-semibold text-primary">Record Treatment</h2>
                                <p className="text-sm text-tertiary">{recordingBatch.name}</p>
                            </div>
                            <button
                                onClick={() => setRecordingBatch(null)}
                                className="p-2 rounded-md hover:bg-tertiary transition-colors duration-fast"
                            >
                                <X size={16} className="text-tertiary" />
                            </button>
                        </div>

                        <div>
                            <label className="block text-xs font-medium text-tertiary uppercase tracking-wider mb-2">
                                Product
                            </label>
                            <input
                                value={product}
                                onChange={e => setProduct(e.target.value)}
                                className="input w-full"
                            />
                        </div>

                        <div>
                            <label className="block text-xs font-medium text-tertiary uppercase tracking-wider mb-2">
                                Dosage
                            </label>
                            <input
                                value={dosage}
                                onChange={e => setDosage(e.target.value)}
                                placeholder="e.g. 1oz/gal"
                                className="input w-full"
                            />
                        </div>

                        <div className="flex gap-3 pt-2">
                            <button
                                onClick={() => setRecordingBatch(null)}
                                className="btn btn-secondary flex-1"
                            >
                                Cancel
                            </button>
                            <button
                                onClick={handleRecordTreatment}
                                disabled={submitting}
                                className="btn btn-primary flex-1"
                            >
                                {submitting ? <Loader2 size={16} className="animate-spin" /> : 'Confirm'}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
