import { motion } from 'framer-motion';
import { Thermometer, Droplets, Wind, CloudFog, Activity, ChevronRight, TrendingUp, TrendingDown, Minus } from 'lucide-react';
import { cn } from '../../lib/utils';
import { useNavigate } from 'react-router-dom';
import { AreaChart, Area, ResponsiveContainer, ReferenceLine } from 'recharts';

interface PulseSensorCardProps {
    reading: {
        deviceId: string;
        deviceName: string;
        temperature: number;
        humidity: number;
        vpd: number;
        dewpoint: number;
        timestamp: Date;
    };
    history?: {
        temperature: number[];
        humidity?: number[];
        vpd?: number[];
    };
    thresholds?: {
        temperature?: { min: number; max: number };
        humidity?: { min: number; max: number };
        vpd?: { min: number; max: number };
    };
    onClick?: () => void;
}

export function PulseSensorCard({ reading, history, thresholds, onClick }: PulseSensorCardProps) {
    const navigate = useNavigate();

    // Determine offline status (older than 15 mins)
    const now = new Date();
    const readingTime = new Date(reading.timestamp);
    const diffMinutes = (now.getTime() - readingTime.getTime()) / 1000 / 60;
    const isOffline = diffMinutes > 15;

    // Get trend for temperature
    const getTrend = (data?: number[]) => {
        if (!data || data.length < 3) return 'stable';
        const recent = data.slice(-3);
        const avg = recent.reduce((a, b) => a + b, 0) / recent.length;
        const first = recent[0];
        if (avg > first + 0.5) return 'up';
        if (avg < first - 0.5) return 'down';
        return 'stable';
    };

    const tempTrend = getTrend(history?.temperature);

    // Determine if values are in warning range
    const isTempWarning = thresholds?.temperature
        ? reading.temperature > thresholds.temperature.max || reading.temperature < thresholds.temperature.min
        : reading.temperature > 82 || reading.temperature < 65;

    const isVpdWarning = thresholds?.vpd
        ? reading.vpd > thresholds.vpd.max || reading.vpd < thresholds.vpd.min
        : reading.vpd > 1.2 || reading.vpd < 0.8;

    // Convert history to chart data
    const chartData = history?.temperature?.map((temp, i) => ({
        value: temp,
        index: i
    })) || [];

    const handleClick = () => {
        if (onClick) onClick();
        else navigate(`/pulse`);
    };

    const TrendIcon = tempTrend === 'up' ? TrendingUp : tempTrend === 'down' ? TrendingDown : Minus;
    const trendColor = tempTrend === 'up' ? 'text-red-400' : tempTrend === 'down' ? 'text-blue-400' : 'text-slate-400';

    return (
        <motion.div
            whileHover={{ y: -4, scale: 1.01 }}
            onClick={handleClick}
            className={cn(
                "group relative overflow-hidden rounded-2xl cursor-pointer transition-all",
                "bg-white dark:bg-zinc-900/80",
                "border border-gray-200 dark:border-zinc-700/50 hover:border-emerald-500/50",
                "shadow-sm dark:shadow-xl hover:shadow-md dark:hover:shadow-2xl hover:shadow-emerald-500/10"
            )}
        >
            {/* Header */}
            <div className="p-5 pb-3">
                <div className="flex justify-between items-start">
                    <div className="flex gap-3 items-center">
                        <div className={cn(
                            "p-3 rounded-xl",
                            isOffline
                                ? "bg-gray-100 dark:bg-zinc-800 text-gray-500 dark:text-zinc-500"
                                : isTempWarning || isVpdWarning
                                    ? "bg-amber-100 dark:bg-amber-500/20 text-amber-600 dark:text-amber-400"
                                    : "bg-emerald-100 dark:bg-emerald-500/20 text-emerald-600 dark:text-emerald-400"
                        )}>
                            <Activity size={22} />
                        </div>
                        <div>
                            <h3 className="text-sm font-bold text-slate-900 dark:text-white tracking-wide">
                                {reading.deviceName}
                            </h3>
                            <p className="text-xs text-slate-500 dark:text-slate-500">Pulse Grow Sensor</p>
                        </div>
                    </div>

                    <div className={cn(
                        "flex items-center gap-1.5 text-xs font-bold px-2.5 py-1 rounded-full border",
                        isOffline
                            ? "text-red-600 dark:text-red-400 bg-red-50 dark:bg-red-500/10 border-red-200 dark:border-red-500/30"
                            : "text-emerald-600 dark:text-emerald-400 bg-emerald-50 dark:bg-emerald-500/10 border-emerald-200 dark:border-emerald-500/30"
                    )}>
                        <div className={cn("w-1.5 h-1.5 rounded-full", isOffline ? "bg-red-500 dark:bg-red-400" : "bg-emerald-500 dark:bg-emerald-400 animate-pulse")} />
                        {isOffline ? 'OFFLINE' : 'LIVE'}
                    </div>
                </div>
            </div>

            {/* Sparkline Chart */}
            {chartData.length > 2 && !isOffline && (
                <div className="h-16 px-2 -mb-2">
                    <ResponsiveContainer width="100%" height="100%">
                        <AreaChart data={chartData}>
                            <defs>
                                <linearGradient id={`gradient-${reading.deviceId}`} x1="0" y1="0" x2="0" y2="1">
                                    <stop offset="5%" stopColor={isTempWarning ? "#f59e0b" : "#10b981"} stopOpacity={0.4} />
                                    <stop offset="95%" stopColor={isTempWarning ? "#f59e0b" : "#10b981"} stopOpacity={0} />
                                </linearGradient>
                            </defs>
                            <Area
                                type="monotone"
                                dataKey="value"
                                stroke={isTempWarning ? "#f59e0b" : "#10b981"}
                                fill={`url(#gradient-${reading.deviceId})`}
                                strokeWidth={2}
                            />
                        </AreaChart>
                    </ResponsiveContainer>
                </div>
            )}

            {/* Metrics Grid */}
            <div className="p-5 pt-3">
                <div className="grid grid-cols-3 gap-4">
                    {/* Temperature */}
                    <div className={cn(
                        "p-3 rounded-xl transition-colors",
                        isTempWarning ? "bg-amber-50 dark:bg-amber-500/10" : "bg-slate-50 dark:bg-slate-800/50"
                    )}>
                        <div className="flex items-center justify-between mb-1">
                            <div className="flex items-center gap-1.5 text-gray-500 dark:text-zinc-400">
                                <Thermometer size={14} />
                                <span className="text-[10px] font-bold uppercase tracking-wider">Temp</span>
                            </div>
                            <TrendIcon size={12} className={trendColor} />
                        </div>
                        <p className={cn(
                            "text-2xl font-bold",
                            isOffline ? "text-gray-400 dark:text-zinc-600" : isTempWarning ? "text-amber-600 dark:text-amber-400" : "text-gray-900 dark:text-white"
                        )}>
                            {reading.temperature.toFixed(1)}°
                        </p>
                    </div>

                    {/* Humidity */}
                    <div className="p-3 rounded-xl bg-gray-50 dark:bg-zinc-800/50">
                        <div className="flex items-center gap-1.5 mb-1 text-gray-500 dark:text-zinc-400">
                            <Droplets size={14} />
                            <span className="text-[10px] font-bold uppercase tracking-wider">RH</span>
                        </div>
                        <p className={cn(
                            "text-2xl font-bold",
                            isOffline ? "text-gray-400 dark:text-zinc-600" : "text-blue-600 dark:text-blue-400"
                        )}>
                            {reading.humidity.toFixed(0)}%
                        </p>
                    </div>

                    {/* VPD */}
                    <div className={cn(
                        "p-3 rounded-xl transition-colors",
                        isVpdWarning ? "bg-purple-50 dark:bg-purple-500/10" : "bg-gray-50 dark:bg-zinc-800/50"
                    )}>
                        <div className="flex items-center gap-1.5 mb-1 text-gray-500 dark:text-zinc-400">
                            <CloudFog size={14} />
                            <span className="text-[10px] font-bold uppercase tracking-wider">VPD</span>
                        </div>
                        <p className={cn(
                            "text-2xl font-bold",
                            isOffline ? "text-gray-400 dark:text-zinc-600" : isVpdWarning ? "text-purple-600 dark:text-purple-400" : "text-emerald-600 dark:text-emerald-400"
                        )}>
                            {reading.vpd.toFixed(2)}
                        </p>
                    </div>
                </div>

                {/* Dewpoint Row */}
                <div className="mt-3 flex items-center justify-between px-1">
                    <div className="flex items-center gap-2 text-gray-500 dark:text-zinc-500">
                        <Wind size={12} />
                        <span className="text-xs">Dewpoint: <span className="text-gray-700 dark:text-zinc-300">{reading.dewpoint.toFixed(1)}°F</span></span>
                    </div>
                    <div className="flex items-center gap-1 text-gray-400 dark:text-zinc-500 group-hover:text-emerald-500 group-hover:dark:text-emerald-400 transition-colors">
                        <span className="text-xs font-medium">View Details</span>
                        <ChevronRight size={14} className="group-hover:translate-x-0.5 transition-transform" />
                    </div>
                </div>
            </div>

            {/* Timestamp Footer */}
            <div className="px-5 pb-4">
                <div className="flex items-center justify-between text-xs text-gray-400 dark:text-zinc-500 pt-3 border-t border-gray-100 dark:border-zinc-700/50">
                    <span>Last reading</span>
                    <span className={isOffline ? "text-red-500 dark:text-red-400" : ""}>
                        {readingTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                    </span>
                </div>
            </div>
        </motion.div>
    );
}
