import { useState, useMemo, useEffect } from "react";
import { AreaChart, Area, ResponsiveContainer } from "recharts";

function generateSparkline(mac) {
  const seed = mac ? mac.split(":").reduce((a, b) => a + parseInt(b, 16), 0) : 42;
  const data = [];
  let val = 30 + (seed % 40);
  for (let i = 0; i < 12; i++) {
    val = Math.max(5, Math.min(95, val + (Math.sin(seed + i) * 20)));
    data.push({ v: Math.round(val) });
  }
  return data;
}

function DeviceIcon({ name }) {
  const n = (name || "").toLowerCase();
  if (n.includes("ipad") || n.includes("tablet")) {
    return (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
        <rect x="4" y="2" width="16" height="20" rx="2" />
        <line x1="12" y1="18" x2="12.01" y2="18" />
      </svg>
    );
  }
  if (n.includes("phone") || n.includes("iphone") || n.includes("android")) {
    return (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
        <rect x="5" y="2" width="14" height="20" rx="2" />
        <line x1="12" y1="18" x2="12.01" y2="18" />
      </svg>
    );
  }
  if (n.includes("laptop") || n.includes("macbook") || n.includes("notebook")) {
    return (
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
        <path d="M20 16V7a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v9m16 0H4m16 0 1.28 2.55a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45L4 16" />
      </svg>
    );
  }
  return (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <rect x="2" y="3" width="20" height="14" rx="2" />
      <path d="M8 21h8" />
      <path d="M12 17v4" />
    </svg>
  );
}

export default function DeviceCard({ device, onNuke, onUnnuke }) {
  const [loading, setLoading] = useState(false);
  const [profile, setProfile] = useState("Default");
  
  const name = device.name || device.hostname || device.oui || "Unknown Device";
  const isOnline = device.is_wired !== undefined || device._uptime_by_ugw !== undefined;
  const isBlocked = device.blocked === true;

  const sparkData = useMemo(() => generateSparkline(device.mac), [device.mac]);

  useEffect(() => {
    const saved = localStorage.getItem(`profile-${device.mac}`);
    if (saved) setProfile(saved);
  }, [device.mac]);

  const handleProfileChange = (e) => {
    const newProfile = e.target.value;
    setProfile(newProfile);
    localStorage.setItem(`profile-${device.mac}`, newProfile);
  };

  return (
    <div className={`glass-card p-5 flex flex-col gap-4 relative overflow-hidden transition-all duration-500 ${
      isBlocked ? "border-blockRed/40 bg-blockRed/5" : ""
    }`}>
      <div className="flex items-start justify-between z-10">
        <div className="flex items-center gap-4 min-w-0">
          <div className={`w-12 h-12 rounded-2xl flex items-center justify-center transition-colors ${
            isBlocked ? "bg-blockRed/20 text-blockRed" : "bg-gold/10 text-gold"
          }`}>
            <DeviceIcon name={name} />
          </div>
          <div className="min-w-0">
            <h3 className="text-cream text-sm font-bold truncate tracking-wide">{name}</h3>
            <div className="flex items-center gap-2 mt-1">
              <div className={`w-1.5 h-1.5 rounded-full ${isOnline ? "bg-manor-green animate-glow-online" : "bg-cream-dark/30"}`} />
              <span className={`text-[0.6rem] uppercase tracking-widest font-bold ${isOnline ? "text-manor-green" : "text-cream-dark opacity-50"}`}>
                {isOnline ? "CONNECTED" : "OFFLINE"}
              </span>
            </div>
          </div>
        </div>
        
        <div className="text-right">
            <div className="text-cream-dark text-[0.6rem] font-mono opacity-40 leading-tight">{device.mac}</div>
            <div className="text-gold/60 text-[0.6rem] font-mono leading-tight mt-0.5">{device.ip || "NO IP"}</div>
        </div>
      </div>

      <div className="h-10 -mx-2 opacity-30 pointer-events-none">
        <ResponsiveContainer width="100%" height="100%">
          <AreaChart data={sparkData}>
            <defs>
              <linearGradient id={`grad-${device.mac}`} x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor={isBlocked ? "#BE123C" : "#D4AF37"} stopOpacity={0.4} />
                <stop offset="100%" stopColor={isBlocked ? "#BE123C" : "#D4AF37"} stopOpacity={0} />
              </linearGradient>
            </defs>
            <Area
              type="monotone"
              dataKey="v"
              stroke={isBlocked ? "#BE123C" : "#D4AF37"}
              strokeWidth={1}
              fill={`url(#grad-${device.mac})`}
              dot={false}
              isAnimationActive={false}
            />
          </AreaChart>
        </ResponsiveContainer>
      </div>

      <div className="z-10 flex flex-col gap-2">
        <select 
          value={profile} 
          onChange={handleProfileChange}
          className="manor-input w-full text-[0.65rem] py-1.5 px-2 bg-viridian/50 border-viridian-light text-cream/80"
        >
          <option value="Default">Profile: Default</option>
          <option value="Kids">Profile: Kids</option>
          <option value="Parents">Profile: Parents</option>
          <option value="IoT">Profile: IoT</option>
          <option value="Guests">Profile: Guests</option>
        </select>

        {isBlocked ? (
          <button
            className="w-full bg-manor-green/20 hover:bg-manor-green/30 text-manor-green border border-manor-green/30 py-2.5 rounded-xl text-[0.65rem] font-bold tracking-[0.2em] uppercase transition-all"
            onClick={onUnnuke}
            disabled={loading}
          >
            RESTORE ACCESS
          </button>
        ) : (
          <button
            className="w-full bg-blockRed/10 hover:bg-blockRed/20 text-blockRed border border-blockRed/30 py-2.5 rounded-xl text-[0.65rem] font-bold tracking-[0.2em] uppercase transition-all"
            onClick={onNuke}
            disabled={loading}
          >
            NUKE DEVICE
          </button>
        )}
      </div>
    </div>
  );
}
