import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { useToast } from '../context/ToastContext';
import { Plus, Leaf, ClipboardCheck, AlertTriangle, Activity, Droplet, Salad, Bug, Eye, ArrowRight } from 'lucide-react';
import TouchPointModal from '../components/touchpoints/TouchPointModal';
import TasksDueTodayWidget from '../components/tasks/TasksDueTodayWidget';
import { SmartAlerts } from '../components/dashboard/SmartAlerts';
import { touchPointsApi } from '../lib/touchPointsApi';
import { analyticsApi, AnalyticsOverview } from '../lib/analyticsApi';
import { PullToRefresh } from '../components/ui/PullToRefresh';

export default function DashboardPage() {
    const { user } = useAuth();
    const { addToast } = useToast();
    const [isTouchModalOpen, setIsTouchModalOpen] = useState(false);
    const [recentActivity, setRecentActivity] = useState<any[]>([]);
    const [overview, setOverview] = useState<AnalyticsOverview | null>(null);
    const [loading, setLoading] = useState(true);
    const [activityLoading, setActivityLoading] = useState(true);

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

    const loadData = async () => {
        setLoading(true);
        setActivityLoading(true);
        try {
            const [overviewData, activityData] = await Promise.all([
                analyticsApi.getOverview(),
                touchPointsApi.getAll()
            ]);
            setOverview(overviewData);
            setRecentActivity(activityData.slice(0, 5));
        } catch (e) {
            console.error(e);
            addToast('Failed to load dashboard data', 'error');
        } finally {
            setLoading(false);
            setActivityLoading(false);
        }
    };

    const handleActivityLogged = () => {
        loadData();
        addToast('Activity logged successfully', 'success');
    };

    const getActivityIcon = (type: string) => {
        const iconClass = "transition-transform duration-fast";
        switch (type) {
            case 'WATER': return <Droplet size={14} className={`text-blue-500 ${iconClass}`} />;
            case 'FEED': return <Salad size={14} className={`text-success ${iconClass}`} />;
            case 'IPM': return <Bug size={14} className={`text-destructive ${iconClass}`} />;
            case 'INSPECT': return <Eye size={14} className={`text-accent ${iconClass}`} />;
            default: return <Activity size={14} className={`text-tertiary ${iconClass}`} />;
        }
    };

    const metrics = overview ? [
        { label: 'Active Batches', value: overview.activeBatches.toString(), icon: Leaf, accent: 'accent', link: '/batches' },
        { label: 'Total Plants', value: overview.totalPlants.toString(), icon: Leaf, accent: 'success', link: '/batches' },
        { label: 'Tasks Completed', value: overview.tasksCompletedThisWeek.toString(), icon: ClipboardCheck, accent: 'accent', link: '/tasks' },
        { label: 'Tasks Pending', value: overview.tasksPending.toString(), icon: AlertTriangle, accent: 'warning', link: '/tasks' },
        { label: 'Touch Points', value: overview.touchPointsToday.toString(), icon: Activity, accent: 'accent', link: '/touch-points' },
        { label: 'Rooms', value: overview.totalRooms.toString(), icon: Leaf, accent: 'neutral', link: '/rooms' },
    ] : [];

    const handlePullRefresh = async () => {
        await loadData();
    };

    const getAccentClasses = (accent: string) => {
        switch (accent) {
            case 'success': return 'bg-success-muted text-success';
            case 'warning': return 'bg-warning-muted text-warning';
            case 'destructive': return 'bg-destructive-muted text-destructive';
            case 'accent': return 'bg-accent-muted text-accent';
            default: return 'bg-tertiary text-secondary';
        }
    };

    return (
        <PullToRefresh onRefresh={handlePullRefresh} disabled={loading}>
            <div className="space-y-6 pb-20 animate-in">
                {/* Header */}
                <header className="flex justify-between items-start">
                    <div>
                        <h1 className="text-2xl font-semibold text-primary tracking-tight">
                            Welcome back, {user?.name || user?.email?.split('@')[0]}
                        </h1>
                        <p className="text-secondary text-sm mt-1">
                            {new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })}
                        </p>
                    </div>
                    <div className="flex items-center gap-2 px-3 py-1.5 bg-success-muted text-success rounded-md text-xs font-medium">
                        <div className="w-1.5 h-1.5 bg-success rounded-full animate-pulse" />
                        Online
                    </div>
                </header>

                {/* Smart Alerts */}
                <SmartAlerts />

                {/* Metrics Grid */}
                <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3">
                    {loading ? (
                        Array.from({ length: 6 }).map((_, i) => (
                            <div key={i} className="card p-4 space-y-3">
                                <div className="skeleton w-8 h-8 rounded-md" />
                                <div className="skeleton w-12 h-6" />
                                <div className="skeleton w-20 h-3" />
                            </div>
                        ))
                    ) : (
                        metrics.map((m, i) => (
                            <Link
                                key={i}
                                to={m.link}
                                className="card card-interactive p-4 group"
                                style={{ animationDelay: `${i * 50}ms` }}
                            >
                                <div className="flex items-start justify-between mb-3">
                                    <div className={`w-8 h-8 rounded-md flex items-center justify-center ${getAccentClasses(m.accent)}`}>
                                        <m.icon size={16} />
                                    </div>
                                    <ArrowRight size={12} className="text-tertiary opacity-0 group-hover:opacity-100 transition-opacity duration-fast" />
                                </div>
                                <p className="text-2xl font-semibold text-primary tracking-tight">
                                    {m.value}
                                </p>
                                <p className="text-xs text-tertiary mt-1">
                                    {m.label}
                                </p>
                            </Link>
                        ))
                    )}
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                    {/* Tasks Widget */}
                    <TasksDueTodayWidget userId={user?.id || ''} />

                    {/* Recent Activity */}
                    <div className="card p-5">
                        <div className="flex justify-between items-center mb-4">
                            <h3 className="text-sm font-medium text-primary">Recent Activity</h3>
                            <button
                                onClick={() => setIsTouchModalOpen(true)}
                                className="btn btn-ghost text-xs h-8 px-3 gap-1 text-accent hover:text-accent"
                            >
                                <Plus size={14} />
                                Log
                            </button>
                        </div>

                        {activityLoading ? (
                            <div className="space-y-2">
                                {Array.from({ length: 3 }).map((_, i) => (
                                    <div key={i} className="flex gap-3 p-3 rounded-md">
                                        <div className="skeleton w-8 h-8 rounded-full" />
                                        <div className="flex-1 space-y-2">
                                            <div className="skeleton w-3/4 h-4" />
                                            <div className="skeleton w-1/2 h-3" />
                                        </div>
                                    </div>
                                ))}
                            </div>
                        ) : recentActivity.length === 0 ? (
                            <div className="text-center py-8">
                                <Activity size={32} className="mx-auto text-quaternary mb-3" />
                                <p className="text-tertiary text-sm">No recent activity</p>
                                <button
                                    onClick={() => setIsTouchModalOpen(true)}
                                    className="btn btn-secondary mt-4 h-9"
                                >
                                    Log First Activity
                                    <ArrowRight size={14} />
                                </button>
                            </div>
                        ) : (
                            <div className="space-y-1">
                                {recentActivity.map((activity: any) => (
                                    <div
                                        key={activity.id}
                                        className="flex items-start gap-3 p-3 rounded-md hover:bg-tertiary transition-colors duration-fast group"
                                    >
                                        <div className={`
                                            w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0
                                            ${activity.type === 'WATER' ? 'bg-blue-500/10' :
                                                activity.type === 'FEED' ? 'bg-success-muted' :
                                                    activity.type === 'IPM' ? 'bg-destructive-muted' :
                                                        activity.type === 'INSPECT' ? 'bg-accent-muted' :
                                                            'bg-tertiary'
                                            }
                                        `}>
                                            {getActivityIcon(activity.type)}
                                        </div>
                                        <div className="flex-1 min-w-0">
                                            <p className="text-sm text-primary truncate">
                                                <span className="font-medium">{activity.type}</span>
                                                <span className="text-tertiary"> — </span>
                                                {activity.batch?.name || 'Unknown Batch'}
                                            </p>
                                            <p className="text-xs text-tertiary mt-0.5">
                                                {activity.user?.name || 'User'} · {new Date(activity.createdAt).toLocaleString()}
                                            </p>
                                            {activity.notes && (
                                                <p className="text-xs text-secondary mt-1 truncate">
                                                    "{activity.notes}"
                                                </p>
                                            )}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>
                </div>

                {/* Floating Action Button (Mobile) */}
                <button
                    onClick={() => setIsTouchModalOpen(true)}
                    className="md:hidden fixed bottom-20 right-4 w-12 h-12 btn-primary rounded-full shadow-lg flex items-center justify-center z-30"
                    style={{ backgroundColor: 'var(--color-accent)' }}
                    aria-label="Log Activity"
                >
                    <Plus size={24} />
                </button>

                <TouchPointModal
                    isOpen={isTouchModalOpen}
                    onClose={() => setIsTouchModalOpen(false)}
                    onSuccess={handleActivityLogged}
                />
            </div>
        </PullToRefresh>
    );
}
