import React, { useEffect, useState } from 'react';
import { Activity, Thermometer, Droplets, Wind, Wifi, WifiOff, RefreshCw, Bell, TrendingUp, Clock, ChevronRight } from 'lucide-react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Area, AreaChart, ReferenceLine } from 'recharts';
import { useNotifications } from '../hooks/useNotifications';
import { motion } from 'framer-motion';
import api from '../lib/api';

interface PulseDevice {
    id: string;
    name: string;
    type: string;
    isOnline: boolean;
}

interface PulseReading {
    deviceId: string;
    deviceName: string;
    temperature: number;
    humidity: number;
    vpd: number;
    dewpoint: number;
    light?: number;
    co2?: number;
    timestamp: Date;
}

interface PulseStatus {
    connected: boolean;
    deviceCount: number;
    error?: string;
}

interface HistoryPoint {
    timestamp: string;
    temperature: number;
    humidity: number;
    vpd: number;
}

export default function PulseTestPage() {
    const { connected: wsConnected, alerts, unreadCount } = useNotifications();

    const [status, setStatus] = useState<PulseStatus | null>(null);
    const [devices, setDevices] = useState<PulseDevice[]>([]);
    const [readings, setReadings] = useState<PulseReading[]>([]);
    const [history, setHistory] = useState<HistoryPoint[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [lastUpdate, setLastUpdate] = useState<Date | null>(null);
    const [selectedDevice, setSelectedDevice] = useState<string | null>(null);
    const [historyHours, setHistoryHours] = useState(6);

    const fetchData = async () => {
        setLoading(true);
        setError(null);

        try {
            // Fetch status
            const statusRes = await api.get('/pulse/status');
            setStatus(statusRes.data);

            if (statusRes.data.connected) {
                // Fetch devices
                const devicesRes = await api.get('/pulse/devices');
                setDevices(devicesRes.data.devices || []);

                // Fetch readings
                const readingsRes = await api.get('/pulse/readings');
                setReadings(readingsRes.data.readings || []);

                // Set first device as selected if none selected
                if (!selectedDevice && readingsRes.data.readings?.length > 0) {
                    setSelectedDevice(readingsRes.data.readings[0].deviceId);
                }
            }

            setLastUpdate(new Date());
        } catch (err: any) {
            setError(err.message || 'Failed to fetch data');
        } finally {
            setLoading(false);
        }
    };

    const fetchHistory = async () => {
        if (!selectedDevice) return;

        try {
            const res = await api.get(`/pulse/devices/${selectedDevice}/history?hours=${historyHours}`);
            const points = (res.data.readings || []).map((r: any) => ({
                timestamp: new Date(r.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
                temperature: r.temperature,
                humidity: r.humidity,
                vpd: r.vpd
            }));
            setHistory(points);
        } catch (err) {
            console.error('Failed to fetch history:', err);
        }
    };

    useEffect(() => {
        fetchData();
        const interval = setInterval(fetchData, 30000);
        return () => clearInterval(interval);
    }, []);

    useEffect(() => {
        fetchHistory();
    }, [selectedDevice, historyHours]);

    const getStatusColor = (connected: boolean) =>
        connected ? 'text-green-500' : 'text-red-500';

    const getVpdColor = (vpd: number) => {
        if (vpd < 0.8) return 'text-blue-500';
        if (vpd > 1.2) return 'text-amber-500';
        if (vpd > 1.6) return 'text-red-500';
        return 'text-green-500';
    };

    const getTempColor = (temp: number) => {
        if (temp < 65) return 'text-blue-500';
        if (temp > 82) return 'text-amber-500';
        if (temp > 90) return 'text-red-500';
        return 'text-green-500';
    };

    const currentReading = readings.find(r => r.deviceId === selectedDevice) || readings[0];

    return (
        <div className="min-h-screen bg-gray-50 dark:bg-zinc-950 p-6 transition-colors duration-300">
            <div className="max-w-7xl mx-auto space-y-6">
                {/* Header */}
                <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                    <div>
                        <h1 className="text-3xl font-bold text-gray-900 dark:text-white flex items-center gap-3">
                            <div className="p-2.5 rounded-xl bg-gradient-to-br from-emerald-500 to-teal-600 shadow-lg shadow-emerald-500/25 text-white">
                                <Activity className="w-6 h-6" />
                            </div>
                            Pulse Sensor Analytics (v3)
                        </h1>
                        <p className="text-gray-500 dark:text-zinc-400 ml-14 mt-1">
                            Real-time environmental monitoring with historical trends
                        </p>
                    </div>
                    <div className="flex items-center gap-4">
                        {/* WebSocket Status */}
                        <div className="flex items-center gap-2 px-3 py-1.5 rounded-full bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 shadow-sm">
                            {wsConnected ? (
                                <Wifi className="w-4 h-4 text-emerald-500" />
                            ) : (
                                <WifiOff className="w-4 h-4 text-red-500" />
                            )}
                            <span className="text-xs font-medium text-gray-600 dark:text-zinc-300">
                                {wsConnected ? 'Live' : 'Offline'}
                            </span>
                            {unreadCount > 0 && (
                                <span className="flex items-center gap-1 text-red-500">
                                    <Bell className="w-3 h-3" />
                                    {unreadCount}
                                </span>
                            )}
                        </div>

                        {/* Refresh Button */}
                        <button
                            onClick={fetchData}
                            disabled={loading}
                            className="p-2.5 rounded-xl bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 hover:bg-gray-50 dark:hover:bg-zinc-800 transition-colors disabled:opacity-50 shadow-sm text-gray-500 dark:text-zinc-400"
                        >
                            <RefreshCw className={`w-5 h-5 ${loading ? 'animate-spin' : ''}`} />
                        </button>
                    </div>
                </div>

                {/* Error Message */}
                {error && (
                    <div className="p-4 rounded-xl bg-red-50 dark:bg-red-500/10 border border-red-200 dark:border-red-500/30 text-red-600 dark:text-red-400">
                        {error}
                    </div>
                )}

                {/* Main Content Grid */}
                <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
                    {/* Live Readings Panel */}
                    <div className="lg:col-span-1 space-y-4">
                        <h2 className="text-sm font-semibold text-gray-500 dark:text-zinc-400 uppercase tracking-wider">Live Sensors</h2>

                        {readings.map((reading) => (
                            <motion.div
                                key={reading.deviceId}
                                whileHover={{ scale: 1.02 }}
                                onClick={() => setSelectedDevice(reading.deviceId)}
                                className={`p-4 rounded-xl cursor-pointer transition-all shadow-sm ${selectedDevice === reading.deviceId
                                    ? 'bg-emerald-50 dark:bg-emerald-500/20 border-2 border-emerald-500/50'
                                    : 'bg-white dark:bg-zinc-900/50 border border-gray-200 dark:border-zinc-800 hover:border-gray-300 dark:hover:border-zinc-700'
                                    }`}
                            >
                                <div className="flex items-center justify-between mb-3">
                                    <h3 className="font-semibold text-gray-900 dark:text-white text-sm">{reading.deviceName}</h3>
                                    <div className="flex items-center gap-1.5">
                                        <div className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
                                        <span className="text-xs text-emerald-600 dark:text-emerald-400 font-medium">LIVE</span>
                                    </div>
                                </div>

                                <div className="grid grid-cols-3 gap-2">
                                    <div>
                                        <p className="text-xs text-gray-500 dark:text-zinc-400 mb-0.5">Temp</p>
                                        <p className={`text-lg font-bold ${getTempColor(reading.temperature)}`}>
                                            {reading.temperature.toFixed(1)}°
                                        </p>
                                    </div>
                                    <div>
                                        <p className="text-xs text-gray-500 dark:text-zinc-400 mb-0.5">RH</p>
                                        <p className="text-lg font-bold text-blue-500 dark:text-blue-400">
                                            {reading.humidity.toFixed(0)}%
                                        </p>
                                    </div>
                                    <div>
                                        <p className="text-xs text-gray-500 dark:text-zinc-400 mb-0.5">VPD</p>
                                        <p className={`text-lg font-bold ${getVpdColor(reading.vpd)}`}>
                                            {reading.vpd.toFixed(2)}
                                        </p>
                                    </div>
                                </div>
                            </motion.div>
                        ))}

                        {readings.length === 0 && !loading && (
                            <div className="p-6 text-center rounded-xl bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 shadow-sm">
                                <Activity className="w-8 h-8 mx-auto mb-2 text-gray-400 dark:text-zinc-500" />
                                <p className="text-gray-500 dark:text-zinc-400 text-sm">No sensors connected</p>
                            </div>
                        )}
                    </div>

                    {/* Charts Section */}
                    <div className="lg:col-span-3 space-y-6">
                        {/* Current Stats */}
                        {currentReading && (
                            <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
                                <motion.div
                                    initial={{ opacity: 0, y: 20 }}
                                    animate={{ opacity: 1, y: 0 }}
                                    className="p-5 rounded-2xl bg-white dark:bg-zinc-900 border border-red-100 dark:border-red-500/10 shadow-sm dark:shadow-none"
                                >
                                    <div className="flex items-center gap-2 mb-2">
                                        <Thermometer className="w-5 h-5 text-red-500 dark:text-red-400" />
                                        <span className="text-sm text-gray-500 dark:text-zinc-400">Temperature</span>
                                    </div>
                                    <p className={`text-3xl lg:text-4xl font-bold ${getTempColor(currentReading.temperature)}`}>
                                        {currentReading.temperature.toFixed(1)}°F
                                    </p>
                                </motion.div>

                                <motion.div
                                    initial={{ opacity: 0, y: 20 }}
                                    animate={{ opacity: 1, y: 0 }}
                                    transition={{ delay: 0.1 }}
                                    className="p-5 rounded-2xl bg-white dark:bg-zinc-900 border border-blue-100 dark:border-blue-500/10 shadow-sm dark:shadow-none"
                                >
                                    <div className="flex items-center gap-2 mb-2">
                                        <Droplets className="w-5 h-5 text-blue-500 dark:text-blue-400" />
                                        <span className="text-sm text-gray-500 dark:text-zinc-400">Humidity</span>
                                    </div>
                                    <p className="text-3xl lg:text-4xl font-bold text-blue-500 dark:text-blue-400">
                                        {currentReading.humidity.toFixed(0)}%
                                    </p>
                                </motion.div>

                                <motion.div
                                    initial={{ opacity: 0, y: 20 }}
                                    animate={{ opacity: 1, y: 0 }}
                                    transition={{ delay: 0.2 }}
                                    className="p-5 rounded-2xl bg-white dark:bg-zinc-900 border border-purple-100 dark:border-purple-500/10 shadow-sm dark:shadow-none"
                                >
                                    <div className="flex items-center gap-2 mb-2">
                                        <Wind className="w-5 h-5 text-purple-500 dark:text-purple-400" />
                                        <span className="text-sm text-gray-500 dark:text-zinc-400">VPD</span>
                                    </div>
                                    <p className={`text-3xl lg:text-4xl font-bold ${getVpdColor(currentReading.vpd)}`}>
                                        {currentReading.vpd.toFixed(2)}
                                    </p>
                                    <p className="text-xs text-gray-500 dark:text-zinc-500 mt-1">kPa</p>
                                </motion.div>

                                <motion.div
                                    initial={{ opacity: 0, y: 20 }}
                                    animate={{ opacity: 1, y: 0 }}
                                    transition={{ delay: 0.3 }}
                                    className="p-5 rounded-2xl bg-white dark:bg-zinc-900 border border-cyan-100 dark:border-cyan-500/10 shadow-sm dark:shadow-none"
                                >
                                    <div className="flex items-center gap-2 mb-2">
                                        <Droplets className="w-5 h-5 text-cyan-500 dark:text-cyan-400" />
                                        <span className="text-sm text-gray-500 dark:text-zinc-400">Dewpoint</span>
                                    </div>
                                    <p className="text-3xl lg:text-4xl font-bold text-cyan-500 dark:text-cyan-400">
                                        {currentReading.dewpoint.toFixed(1)}°F
                                    </p>
                                </motion.div>
                            </div>
                        )}

                        {/* Time Range Selector */}
                        <div className="flex items-center justify-between pt-4">
                            <h2 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                                <TrendingUp className="w-5 h-5 text-emerald-500 dark:text-emerald-400" />
                                Historical Trends
                            </h2>
                            <div className="flex items-center gap-2">
                                <Clock className="w-4 h-4 text-gray-400" />
                                <select
                                    value={historyHours}
                                    onChange={(e) => setHistoryHours(Number(e.target.value))}
                                    className="bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 rounded-lg px-3 py-1.5 text-sm text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-emerald-500 shadow-sm"
                                >
                                    <option value={1}>Last hour</option>
                                    <option value={6}>Last 6 hours</option>
                                    <option value={12}>Last 12 hours</option>
                                    <option value={24}>Last 24 hours</option>
                                    <option value={48}>Last 48 hours</option>
                                </select>
                            </div>
                        </div>

                        {/* Temperature Chart */}
                        <div className="p-6 rounded-2xl bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 shadow-sm">
                            <h3 className="text-sm font-medium text-slate-500 dark:text-slate-400 mb-4 flex items-center gap-2">
                                <Thermometer className="w-4 h-4 text-red-500 dark:text-red-400" />
                                Temperature History
                            </h3>
                            <div className="h-64">
                                <ResponsiveContainer width="100%" height="100%">
                                    <AreaChart data={history}>
                                        <defs>
                                            <linearGradient id="tempGradient" x1="0" y1="0" x2="0" y2="1">
                                                <stop offset="5%" stopColor="#ef4444" stopOpacity={0.3} />
                                                <stop offset="95%" stopColor="#ef4444" stopOpacity={0} />
                                            </linearGradient>
                                        </defs>
                                        <CartesianGrid strokeDasharray="3 3" stroke="#94a3b8" strokeOpacity={0.2} />
                                        <XAxis dataKey="timestamp" stroke="#94a3b8" fontSize={11} tickMargin={10} />
                                        <YAxis stroke="#94a3b8" fontSize={11} domain={['auto', 'auto']} />
                                        <Tooltip
                                            contentStyle={{ backgroundColor: 'var(--color-bg-secondary)', borderColor: 'var(--color-border-subtle)', borderRadius: '8px', color: 'var(--color-text-primary)' }}
                                            itemStyle={{ color: 'var(--color-text-primary)' }}
                                        />
                                        <ReferenceLine y={82} stroke="#f59e0b" strokeDasharray="5 5" />
                                        <ReferenceLine y={65} stroke="#3b82f6" strokeDasharray="5 5" />
                                        <Area type="monotone" dataKey="temperature" stroke="#ef4444" fill="url(#tempGradient)" strokeWidth={2} />
                                    </AreaChart>
                                </ResponsiveContainer>
                            </div>
                        </div>

                        {/* Humidity & VPD Charts */}
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div className="p-6 rounded-2xl bg-white dark:bg-slate-800/50 border border-slate-200 dark:border-slate-700/50 shadow-sm">
                                <h3 className="text-sm font-medium text-slate-500 dark:text-slate-400 mb-4 flex items-center gap-2">
                                    <Droplets className="w-4 h-4 text-blue-500 dark:text-blue-400" />
                                    Humidity History
                                </h3>
                                <div className="h-48">
                                    <ResponsiveContainer width="100%" height="100%">
                                        <AreaChart data={history}>
                                            <defs>
                                                <linearGradient id="humidityGradient" x1="0" y1="0" x2="0" y2="1">
                                                    <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.3} />
                                                    <stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
                                                </linearGradient>
                                            </defs>
                                            <CartesianGrid strokeDasharray="3 3" stroke="#94a3b8" strokeOpacity={0.2} />
                                            <XAxis dataKey="timestamp" stroke="#94a3b8" fontSize={10} tickMargin={10} />
                                            <YAxis stroke="#94a3b8" fontSize={10} domain={[0, 100]} />
                                            <Tooltip
                                                contentStyle={{ backgroundColor: 'var(--color-bg-secondary)', borderColor: 'var(--color-border-subtle)', borderRadius: '8px' }}
                                            />
                                            <Area type="monotone" dataKey="humidity" stroke="#3b82f6" fill="url(#humidityGradient)" strokeWidth={2} />
                                        </AreaChart>
                                    </ResponsiveContainer>
                                </div>
                            </div>

                            <div className="p-6 rounded-2xl bg-white dark:bg-slate-800/50 border border-slate-200 dark:border-slate-700/50 shadow-sm">
                                <h3 className="text-sm font-medium text-slate-500 dark:text-slate-400 mb-4 flex items-center gap-2">
                                    <Wind className="w-4 h-4 text-purple-500 dark:text-purple-400" />
                                    VPD History
                                </h3>
                                <div className="h-48">
                                    <ResponsiveContainer width="100%" height="100%">
                                        <AreaChart data={history}>
                                            <defs>
                                                <linearGradient id="vpdGradient" x1="0" y1="0" x2="0" y2="1">
                                                    <stop offset="5%" stopColor="#a855f7" stopOpacity={0.3} />
                                                    <stop offset="95%" stopColor="#a855f7" stopOpacity={0} />
                                                </linearGradient>
                                            </defs>
                                            <CartesianGrid strokeDasharray="3 3" stroke="#94a3b8" strokeOpacity={0.2} />
                                            <XAxis dataKey="timestamp" stroke="#94a3b8" fontSize={10} tickMargin={10} />
                                            <YAxis stroke="#94a3b8" fontSize={10} domain={[0, 4]} />
                                            <Tooltip
                                                contentStyle={{ backgroundColor: 'var(--color-bg-secondary)', borderColor: 'var(--color-border-subtle)', borderRadius: '8px' }}
                                            />
                                            <Area type="monotone" dataKey="vpd" stroke="#a855f7" fill="url(#vpdGradient)" strokeWidth={2} />
                                        </AreaChart>
                                    </ResponsiveContainer>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                {/* Recent Alerts */}
                {alerts.length > 0 && (
                    <div className="p-6 rounded-2xl bg-white dark:bg-slate-800/50 border border-slate-200 dark:border-slate-700/50 shadow-sm">
                        <h3 className="font-semibold text-slate-900 dark:text-white mb-4 flex items-center gap-2">
                            <Bell className="w-5 h-5 text-amber-500 dark:text-amber-400" />
                            Recent Alerts ({alerts.length})
                        </h3>
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                            {alerts.slice(0, 6).map((alert, index) => (
                                <div
                                    key={alert.id || index}
                                    className="p-4 rounded-xl bg-red-500/10 border border-red-500/20"
                                >
                                    <p className="font-medium text-red-400 text-sm">{alert.sensorName}</p>
                                    <p className="text-slate-400 text-sm">
                                        {alert.type}: {alert.value.toFixed(1)} (threshold: {alert.threshold.toFixed(1)})
                                    </p>
                                    <p className="text-xs text-slate-500 mt-2">
                                        {new Date(alert.timestamp).toLocaleTimeString()}
                                    </p>
                                </div>
                            ))}
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}
