"use client";

import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import { api } from "@/lib/api";
import {
  TemperatureChart,
  HumidityChart,
  MultiReadingChart,
  DeviceStatusPieChart,
  AlertsBarChart,
  RealTimeGauge,
} from "@/components/charts/DeviceCharts";
import {
  Download,
  FileText,
  FileSpreadsheet,
  RefreshCw,
  TrendingUp,
  Thermometer,
  Droplets,
  Activity,
  Calendar,
} from "lucide-react";

interface Device {
  id: string;
  name: string;
  device_metadata?: any;
  is_online: boolean;
}

interface AnalyticsData {
  deviceStats: { online: number; offline: number; total: number };
  readings: { time: string; temperature: number; humidity: number }[];
  alertsWeekly: { day: string; critical: number; warning: number; info: number }[];
  avgTemperature: number;
  avgHumidity: number;
}

export default function AnalyticsPage() {
  const API_URL = process.env.NEXT_PUBLIC_API_URL || "https://smart-life.online";
  const t = useTranslations("analytics");
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [period, setPeriod] = useState<"day" | "week" | "month">("week");
  const [devices, setDevices] = useState<Device[]>([]);
  const [selectedDevices, setSelectedDevices] = useState<string[]>([]);
  const [deviceFilter, setDeviceFilter] = useState<"all" | "selected">("all");
  const [data, setData] = useState<AnalyticsData>({
    deviceStats: { online: 0, offline: 0, total: 0 },
    readings: [],
    alertsWeekly: [],
    avgTemperature: 0,
    avgHumidity: 0,
  });

  const fetchData = async () => {
    try {
      api.loadToken();
      const [statsData, devicesData] = await Promise.all([
        api.getDashboardStats(),
        api.getDevices({ page_size: 100 }),
      ]);

      // حفظ قائمة الأجهزة
      const allDevices = devicesData.items || [];
      setDevices(allDevices);
      
      // تصفية الأجهزة حسب الفلتر
      const filteredDevices = deviceFilter === "all" || selectedDevices.length === 0
        ? allDevices
        : allDevices.filter((d: Device) => selectedDevices.includes(d.id));
      
      let totalTemp = 0;
      let totalHumid = 0;
      let tempCount = 0;
      let humidCount = 0;

      filteredDevices.forEach((device: any) => {
        const readings = device.device_metadata?.readings;
        if (readings?.temperature) {
          totalTemp += readings.temperature;
          tempCount++;
        }
        if (readings?.humidity) {
          totalHumid += readings.humidity;
          humidCount++;
        }
      });

      // إنشاء بيانات وهمية للرسوم البيانية (يمكن استبدالها ببيانات حقيقية لاحقاً)
      const now = new Date();
      const readings = [];
      for (let i = 23; i >= 0; i--) {
        const time = new Date(now.getTime() - i * 60 * 60 * 1000);
        readings.push({
          time: time.toLocaleTimeString("ar-SA", { hour: "2-digit", minute: "2-digit" }),
          temperature: 22 + Math.random() * 8,
          humidity: 40 + Math.random() * 30,
        });
      }

      const days = ["السبت", "الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة"];
      const alertsWeekly = days.map((day) => ({
        day,
        critical: Math.floor(Math.random() * 5),
        warning: Math.floor(Math.random() * 10),
        info: Math.floor(Math.random() * 15),
      }));

      setData({
        deviceStats: {
          online: statsData?.devices?.online || 0,
          offline: statsData?.devices?.offline || 0,
          total: statsData?.devices?.total || 0,
        },
        readings,
        alertsWeekly,
        avgTemperature: tempCount > 0 ? Math.round(totalTemp / tempCount) : 25,
        avgHumidity: humidCount > 0 ? Math.round(totalHumid / humidCount) : 50,
      });
    } catch (error) {
      console.error("Failed to fetch analytics:", error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => {
    fetchData();
    const interval = setInterval(fetchData, 60000);
    return () => clearInterval(interval);
  }, [period, deviceFilter, selectedDevices]);

  const handleExport = async (type: "pdf" | "excel", report: "devices" | "alerts") => {
    try {
      api.loadToken();
      const endpoint = `/reports/${report}/${type}`;
      const response = await fetch(`${API_URL}/api/v1${endpoint}`, {
        headers: {
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      });
      
      if (response.ok) {
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = `${report}_report.${type === "pdf" ? "pdf" : "xlsx"}`;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        a.remove();
      }
    } catch (error) {
      console.error("Export failed:", error);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">التحليلات والتقارير</h1>
          <p className="text-gray-500 dark:text-gray-400 mt-1">
            عرض إحصائيات النظام وتصدير التقارير
          </p>
        </div>
        <div className="flex items-center gap-3 flex-wrap">
          {/* Device Filter */}
          <div className="flex items-center gap-2">
            <select
              value={deviceFilter}
              onChange={(e) => setDeviceFilter(e.target.value as "all" | "selected")}
              className="px-3 py-2 text-sm border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800"
            >
              <option value="all">كل الأجهزة</option>
              <option value="selected">أجهزة محددة</option>
            </select>
            
            {deviceFilter === "selected" && (
              <select
                multiple
                value={selectedDevices}
                onChange={(e) => setSelectedDevices(Array.from(e.target.selectedOptions, opt => opt.value))}
                className="px-3 py-2 text-sm border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800 max-h-24"
              >
                {devices.map(device => (
                  <option key={device.id} value={device.id}>{device.name}</option>
                ))}
              </select>
            )}
          </div>
          
          {/* Period Selector */}
          <div className="flex items-center gap-1 bg-gray-100 dark:bg-gray-800 rounded-lg p-1">
            {(["day", "week", "month"] as const).map((p) => (
              <button
                key={p}
                onClick={() => setPeriod(p)}
                className={`px-3 py-1.5 text-sm rounded-md transition-colors ${
                  period === p
                    ? "bg-white dark:bg-gray-700 shadow text-primary"
                    : "text-gray-600 dark:text-gray-400 hover:text-gray-900"
                }`}
              >
                {p === "day" ? "يوم" : p === "week" ? "أسبوع" : "شهر"}
              </button>
            ))}
          </div>
          
          <button
            onClick={() => {
              setRefreshing(true);
              fetchData();
            }}
            disabled={refreshing}
            className="flex items-center gap-2 px-4 py-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
          >
            <RefreshCw className={`w-4 h-4 ${refreshing ? "animate-spin" : ""}`} />
            تحديث
          </button>
        </div>
      </div>

      {/* Export Buttons */}
      <div className="flex flex-wrap gap-3">
        <button
          onClick={() => handleExport("pdf", "devices")}
          className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors"
        >
          <FileText className="w-4 h-4" />
          تصدير الأجهزة PDF
        </button>
        <button
          onClick={() => handleExport("excel", "devices")}
          className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
        >
          <FileSpreadsheet className="w-4 h-4" />
          تصدير الأجهزة Excel
        </button>
        <button
          onClick={() => handleExport("pdf", "alerts")}
          className="flex items-center gap-2 px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700 transition-colors"
        >
          <FileText className="w-4 h-4" />
          تصدير التنبيهات PDF
        </button>
        <button
          onClick={() => handleExport("excel", "alerts")}
          className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
        >
          <FileSpreadsheet className="w-4 h-4" />
          تصدير التنبيهات Excel
        </button>
      </div>

      {/* Real-time Gauges */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-white dark:bg-gray-800 rounded-xl p-4 border border-gray-200 dark:border-gray-700">
          <RealTimeGauge
            value={data.avgTemperature}
            max={50}
            unit="°C"
            label="متوسط الحرارة"
            color="#ef4444"
          />
        </div>
        <div className="bg-white dark:bg-gray-800 rounded-xl p-4 border border-gray-200 dark:border-gray-700">
          <RealTimeGauge
            value={data.avgHumidity}
            max={100}
            unit="%"
            label="متوسط الرطوبة"
            color="#3b82f6"
          />
        </div>
        <div className="bg-white dark:bg-gray-800 rounded-xl p-4 border border-gray-200 dark:border-gray-700">
          <RealTimeGauge
            value={data.deviceStats.online}
            max={data.deviceStats.total || 1}
            unit=""
            label="أجهزة متصلة"
            color="#22c55e"
          />
        </div>
        <div className="bg-white dark:bg-gray-800 rounded-xl p-4 border border-gray-200 dark:border-gray-700">
          <RealTimeGauge
            value={Math.round((data.deviceStats.online / (data.deviceStats.total || 1)) * 100)}
            max={100}
            unit="%"
            label="نسبة الاتصال"
            color="#8b5cf6"
          />
        </div>
      </div>

      {/* Charts Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <MultiReadingChart data={data.readings} />
        <DeviceStatusPieChart
          online={data.deviceStats.online}
          offline={data.deviceStats.offline}
        />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <TemperatureChart data={data.readings} />
        <HumidityChart data={data.readings} />
      </div>

      <AlertsBarChart data={data.alertsWeekly} />
    </div>
  );
}
