"use client";

import { useState, useEffect } from "react";
import {
  LineChart,
  Line,
  AreaChart,
  Area,
  BarChart,
  Bar,
  PieChart,
  Pie,
  Cell,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from "recharts";
import { Thermometer, Droplets, Sun, Battery, TrendingUp } from "lucide-react";

interface ReadingData {
  time: string;
  temperature?: number;
  humidity?: number;
  illuminance?: number;
  battery?: number;
}

interface DeviceChartProps {
  data: ReadingData[];
  type: "temperature" | "humidity" | "illuminance" | "battery" | "all";
  height?: number;
}

const COLORS = {
  temperature: "#ef4444",
  humidity: "#3b82f6",
  illuminance: "#eab308",
  battery: "#22c55e",
};

export function TemperatureChart({ data, height = 300 }: { data: ReadingData[]; height?: number }) {
  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl p-4 border border-gray-200 dark:border-gray-700">
      <div className="flex items-center gap-2 mb-4">
        <Thermometer className="w-5 h-5 text-red-500" />
        <h3 className="font-semibold text-gray-900 dark:text-white">درجة الحرارة</h3>
      </div>
      <ResponsiveContainer width="100%" height={height}>
        <AreaChart data={data}>
          <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="#e5e7eb" />
          <XAxis dataKey="time" tick={{ fontSize: 12 }} stroke="#9ca3af" />
          <YAxis unit="°C" tick={{ fontSize: 12 }} stroke="#9ca3af" />
          <Tooltip
            contentStyle={{
              backgroundColor: "#1f2937",
              border: "none",
              borderRadius: "8px",
              color: "#fff",
            }}
            formatter={(value: number) => [`${value}°C`, "الحرارة"]}
          />
          <Area
            type="monotone"
            dataKey="temperature"
            stroke="#ef4444"
            strokeWidth={2}
            fill="url(#tempGradient)"
          />
        </AreaChart>
      </ResponsiveContainer>
    </div>
  );
}

export function HumidityChart({ data, height = 300 }: { data: ReadingData[]; height?: number }) {
  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl p-4 border border-gray-200 dark:border-gray-700">
      <div className="flex items-center gap-2 mb-4">
        <Droplets className="w-5 h-5 text-blue-500" />
        <h3 className="font-semibold text-gray-900 dark:text-white">الرطوبة</h3>
      </div>
      <ResponsiveContainer width="100%" height={height}>
        <AreaChart data={data}>
          <defs>
            <linearGradient id="humidGradient" 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="#e5e7eb" />
          <XAxis dataKey="time" tick={{ fontSize: 12 }} stroke="#9ca3af" />
          <YAxis unit="%" tick={{ fontSize: 12 }} stroke="#9ca3af" domain={[0, 100]} />
          <Tooltip
            contentStyle={{
              backgroundColor: "#1f2937",
              border: "none",
              borderRadius: "8px",
              color: "#fff",
            }}
            formatter={(value: number) => [`${value}%`, "الرطوبة"]}
          />
          <Area
            type="monotone"
            dataKey="humidity"
            stroke="#3b82f6"
            strokeWidth={2}
            fill="url(#humidGradient)"
          />
        </AreaChart>
      </ResponsiveContainer>
    </div>
  );
}

export function MultiReadingChart({ data, height = 350 }: { data: ReadingData[]; height?: number }) {
  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl p-4 border border-gray-200 dark:border-gray-700">
      <div className="flex items-center gap-2 mb-4">
        <TrendingUp className="w-5 h-5 text-primary" />
        <h3 className="font-semibold text-gray-900 dark:text-white">القراءات الحية</h3>
      </div>
      <ResponsiveContainer width="100%" height={height}>
        <LineChart data={data}>
          <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
          <XAxis dataKey="time" tick={{ fontSize: 12 }} stroke="#9ca3af" />
          <YAxis yAxisId="temp" orientation="left" unit="°C" tick={{ fontSize: 12 }} stroke="#ef4444" />
          <YAxis yAxisId="humid" orientation="right" unit="%" tick={{ fontSize: 12 }} stroke="#3b82f6" />
          <Tooltip
            contentStyle={{
              backgroundColor: "#1f2937",
              border: "none",
              borderRadius: "8px",
              color: "#fff",
            }}
          />
          <Legend />
          <Line
            yAxisId="temp"
            type="monotone"
            dataKey="temperature"
            name="الحرارة (°C)"
            stroke="#ef4444"
            strokeWidth={2}
            dot={{ r: 3 }}
            activeDot={{ r: 5 }}
          />
          <Line
            yAxisId="humid"
            type="monotone"
            dataKey="humidity"
            name="الرطوبة (%)"
            stroke="#3b82f6"
            strokeWidth={2}
            dot={{ r: 3 }}
            activeDot={{ r: 5 }}
          />
        </LineChart>
      </ResponsiveContainer>
    </div>
  );
}

interface DeviceStatusData {
  name: string;
  value: number;
  color: string;
}

export function DeviceStatusPieChart({ online, offline }: { online: number; offline: number }) {
  const data: DeviceStatusData[] = [
    { name: "متصل", value: online, color: "#22c55e" },
    { name: "غير متصل", value: offline, color: "#ef4444" },
  ];

  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl p-4 border border-gray-200 dark:border-gray-700">
      <h3 className="font-semibold text-gray-900 dark:text-white mb-4">حالة الأجهزة</h3>
      <ResponsiveContainer width="100%" height={200}>
        <PieChart>
          <Pie
            data={data}
            cx="50%"
            cy="50%"
            innerRadius={50}
            outerRadius={70}
            paddingAngle={5}
            dataKey="value"
          >
            {data.map((entry, index) => (
              <Cell key={`cell-${index}`} fill={entry.color} />
            ))}
          </Pie>
          <Tooltip
            contentStyle={{
              backgroundColor: "#1f2937",
              border: "none",
              borderRadius: "8px",
              color: "#fff",
            }}
          />
          <Legend />
        </PieChart>
      </ResponsiveContainer>
    </div>
  );
}

export function AlertsBarChart({ data }: { data: { day: string; critical: number; warning: number; info: number }[] }) {
  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl p-4 border border-gray-200 dark:border-gray-700">
      <h3 className="font-semibold text-gray-900 dark:text-white mb-4">التنبيهات (آخر 7 أيام)</h3>
      <ResponsiveContainer width="100%" height={250}>
        <BarChart data={data}>
          <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
          <XAxis dataKey="day" tick={{ fontSize: 12 }} stroke="#9ca3af" />
          <YAxis tick={{ fontSize: 12 }} stroke="#9ca3af" />
          <Tooltip
            contentStyle={{
              backgroundColor: "#1f2937",
              border: "none",
              borderRadius: "8px",
              color: "#fff",
            }}
          />
          <Legend />
          <Bar dataKey="critical" name="حرجة" fill="#ef4444" radius={[4, 4, 0, 0]} />
          <Bar dataKey="warning" name="تحذير" fill="#f59e0b" radius={[4, 4, 0, 0]} />
          <Bar dataKey="info" name="معلومات" fill="#3b82f6" radius={[4, 4, 0, 0]} />
        </BarChart>
      </ResponsiveContainer>
    </div>
  );
}

export function BatteryGauge({ percentage }: { percentage: number }) {
  const color = percentage > 50 ? "#22c55e" : percentage > 20 ? "#f59e0b" : "#ef4444";
  
  return (
    <div className="flex items-center gap-3">
      <Battery className={`w-6 h-6`} style={{ color }} />
      <div className="flex-1">
        <div className="h-3 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
          <div
            className="h-full rounded-full transition-all duration-500"
            style={{
              width: `${percentage}%`,
              backgroundColor: color,
            }}
          />
        </div>
      </div>
      <span className="text-sm font-medium" style={{ color }}>
        {percentage}%
      </span>
    </div>
  );
}

export function RealTimeGauge({ value, max, unit, label, color }: {
  value: number;
  max: number;
  unit: string;
  label: string;
  color: string;
}) {
  const percentage = (value / max) * 100;
  const circumference = 2 * Math.PI * 45;
  const strokeDashoffset = circumference - (percentage / 100) * circumference;

  return (
    <div className="flex flex-col items-center">
      <div className="relative w-28 h-28">
        <svg className="w-full h-full transform -rotate-90">
          <circle
            cx="56"
            cy="56"
            r="45"
            fill="none"
            stroke="currentColor"
            strokeWidth="10"
            className="text-gray-200 dark:text-gray-700"
          />
          <circle
            cx="56"
            cy="56"
            r="45"
            fill="none"
            stroke={color}
            strokeWidth="10"
            strokeLinecap="round"
            strokeDasharray={circumference}
            strokeDashoffset={strokeDashoffset}
            className="transition-all duration-500"
          />
        </svg>
        <div className="absolute inset-0 flex items-center justify-center">
          <div className="text-center">
            <span className="text-xl font-bold text-gray-900 dark:text-white">{value}</span>
            <span className="text-xs text-gray-500">{unit}</span>
          </div>
        </div>
      </div>
      <span className="text-sm text-gray-600 dark:text-gray-400 mt-2">{label}</span>
    </div>
  );
}
