import { useState, useEffect } from 'react';
import { AlertTriangle, Clock, Bug, CheckCircle, X, ChevronRight } from 'lucide-react';
import { Link } from 'react-router-dom';
import { tasksApi } from '../../lib/tasksApi';
import api from '../../lib/api';

interface Alert {
    id: string;
    type: 'overdue' | 'upcoming' | 'ipm' | 'low_stock' | 'info';
    title: string;
    description: string;
    link?: string;
    priority: 'high' | 'medium' | 'low';
}

export function SmartAlerts() {
    const [alerts, setAlerts] = useState<Alert[]>([]);
    const [dismissed, setDismissed] = useState<string[]>([]);
    const [loading, setLoading] = useState(true);

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

    const loadAlerts = async () => {
        setLoading(true);
        const newAlerts: Alert[] = [];

        try {
            // Check overdue tasks
            const tasks = await tasksApi.getAll({});
            const now = new Date();
            const overdueTasks = tasks.filter(t =>
                t.status !== 'COMPLETED' &&
                t.dueDate &&
                new Date(t.dueDate) < now
            );

            if (overdueTasks.length > 0) {
                newAlerts.push({
                    id: 'overdue-tasks',
                    type: 'overdue',
                    title: `${overdueTasks.length} Overdue Task${overdueTasks.length > 1 ? 's' : ''}`,
                    description: `You have ${overdueTasks.length} task${overdueTasks.length > 1 ? 's' : ''} past due date`,
                    link: '/tasks',
                    priority: 'high'
                });
            }

            // Check tasks due today
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            const tomorrow = new Date(today);
            tomorrow.setDate(tomorrow.getDate() + 1);

            const dueTodayTasks = tasks.filter(t =>
                t.status !== 'COMPLETED' &&
                t.dueDate &&
                new Date(t.dueDate) >= today &&
                new Date(t.dueDate) < tomorrow
            );

            if (dueTodayTasks.length > 0) {
                newAlerts.push({
                    id: 'due-today',
                    type: 'upcoming',
                    title: `${dueTodayTasks.length} Task${dueTodayTasks.length > 1 ? 's' : ''} Due Today`,
                    description: 'Don\'t forget to complete these',
                    link: '/tasks',
                    priority: 'medium'
                });
            }

            // Check IPM schedules (sample - would need API endpoint)
            try {
                const batches = await api.get('/batches');
                const batchesWithIPM = batches.data.filter((b: any) => b.ipmSchedule);
                const upcomingIPM = batchesWithIPM.filter((b: any) => {
                    if (!b.ipmSchedule?.nextIpmDate) return false;
                    const nextDate = new Date(b.ipmSchedule.nextIpmDate);
                    const threeDaysFromNow = new Date();
                    threeDaysFromNow.setDate(threeDaysFromNow.getDate() + 3);
                    return nextDate <= threeDaysFromNow && nextDate >= now;
                });

                if (upcomingIPM.length > 0) {
                    newAlerts.push({
                        id: 'ipm-upcoming',
                        type: 'ipm',
                        title: 'IPM Treatment Due Soon',
                        description: `${upcomingIPM.length} batch${upcomingIPM.length > 1 ? 'es' : ''} need treatment within 3 days`,
                        link: '/ipm',
                        priority: 'medium'
                    });
                }
            } catch (e) {
                // IPM endpoint might not exist, that's ok
            }

            setAlerts(newAlerts);
        } catch (e) {
            console.error('Failed to load alerts:', e);
        } finally {
            setLoading(false);
        }
    };

    const dismissAlert = (id: string) => {
        setDismissed(prev => [...prev, id]);
    };

    const visibleAlerts = alerts.filter(a => !dismissed.includes(a.id));

    if (loading || visibleAlerts.length === 0) return null;

    const iconMap = {
        overdue: <AlertTriangle size={18} className="text-red-500" />,
        upcoming: <Clock size={18} className="text-[var(--color-warning)]" />,
        ipm: <Bug size={18} className="text-purple-500" />,
        low_stock: <AlertTriangle size={18} className="text-orange-500" />,
        info: <CheckCircle size={18} className="text-[var(--color-accent)]" />
    };

    const bgMap = {
        high: 'bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800',
        medium: 'bg-amber-50 dark:bg-amber-900/20 border-amber-200 dark:border-amber-800',
        low: 'bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800'
    };

    return (
        <div className="space-y-2">
            {visibleAlerts.map(alert => (
                <div
                    key={alert.id}
                    className={`flex items-center gap-3 p-3 rounded-xl border ${bgMap[alert.priority]} animate-fade-in`}
                >
                    <div className="flex-shrink-0">
                        {iconMap[alert.type]}
                    </div>
                    <div className="flex-1 min-w-0">
                        <p className="font-medium text-[var(--color-text-primary)] text-sm">{alert.title}</p>
                        <p className="text-xs text-[var(--color-text-tertiary)]">{alert.description}</p>
                    </div>
                    {alert.link && (
                        <Link
                            to={alert.link}
                            className="flex-shrink-0 p-1 text-[var(--color-text-tertiary)] hover:text-slate-600 dark:hover:text-slate-300"
                        >
                            <ChevronRight size={18} />
                        </Link>
                    )}
                    <button
                        onClick={() => dismissAlert(alert.id)}
                        className="flex-shrink-0 p-1 text-[var(--color-text-tertiary)] hover:text-slate-600 dark:hover:text-slate-300"
                    >
                        <X size={16} />
                    </button>
                </div>
            ))}
        </div>
    );
}
