"use client";

import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import { useParams } from "next/navigation";
import Link from "next/link";
import { api } from "@/lib/api";
import { 
  Cpu, Wifi, WifiOff, Plus, Search, Filter, X, ChevronRight,
  Thermometer, Droplets, Sun, Battery, RefreshCw, Activity
} from "lucide-react";

interface DeviceMetadata {
  readings?: {
    temperature?: number;
    humidity?: number;
    illuminance?: number;
    battery?: number;
  };
  last_sync?: string;
}

interface Device {
  id: string;
  name: string;
  name_ar?: string;
  device_type: string;
  device_model?: string;
  lifesmart_device_id: string;
  is_online: boolean;
  last_seen?: string;
  device_metadata?: DeviceMetadata;
  location?: string;
}

export default function DevicesPage() {
  const t = useTranslations("devices");
  const params = useParams();
  const locale = params.locale as string;
  const [devices, setDevices] = useState<Device[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [filterType, setFilterType] = useState<string>("all");
  const [filterStatus, setFilterStatus] = useState<string>("all");
  const [showAddModal, setShowAddModal] = useState(false);
  const [newDevice, setNewDevice] = useState({
    name: "",
    name_ar: "",
    device_type: "environment_sensor",
    lifesmart_device_id: "",
  });
  const [saving, setSaving] = useState(false);

  const fetchDevices = async () => {
    try {
      api.loadToken();
      const data = await api.getDevices();
      setDevices(data.items || []);
    } catch (error) {
      console.error("Failed to fetch devices:", error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => {
    fetchDevices();
  }, []);

  const handleRefresh = () => {
    setRefreshing(true);
    fetchDevices();
  };

  const filteredDevices = devices.filter((device) => {
    const matchesSearch = device.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      device.device_type.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesType = filterType === "all" || device.device_type === filterType;
    const matchesStatus = filterStatus === "all" || 
      (filterStatus === "online" && device.is_online) ||
      (filterStatus === "offline" && !device.is_online);
    return matchesSearch && matchesType && matchesStatus;
  });

  const onlineCount = devices.filter(d => d.is_online).length;
  const offlineCount = devices.filter(d => !d.is_online).length;

  const getDeviceTypeLabel = (type: string) => {
    const types: Record<string, string> = {
      environment_sensor: "حساس بيئة",
      motion_sensor: "حساس حركة",
      door_sensor: "حساس باب",
      water_leak_sensor: "حساس تسريب",
      gas_sensor: "حساس غاز",
      switch_1gang: "مفتاح 1",
      switch_2gang: "مفتاح 2",
      switch_3gang: "مفتاح 3",
    };
    return types[type] || type;
  };

  const handleAddDevice = async () => {
    if (!newDevice.name || !newDevice.lifesmart_device_id) return;
    
    setSaving(true);
    try {
      const created = await api.createDevice(newDevice);
      setDevices([...devices, created]);
      setShowAddModal(false);
      setNewDevice({
        name: "",
        name_ar: "",
        device_type: "environment_sensor",
        lifesmart_device_id: "",
      });
    } catch (error) {
      console.error("Failed to create device:", error);
      alert("فشل في إضافة الجهاز");
    } finally {
      setSaving(false);
    }
  };

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

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">
            {t("title")}
          </h1>
          <p className="text-gray-500 dark:text-gray-400">{t("subtitle")}</p>
        </div>
        <div className="flex gap-2">
          <button 
            onClick={handleRefresh}
            disabled={refreshing}
            className="flex items-center gap-2 px-4 py-2 border border-gray-200 dark:border-gray-700 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
          >
            <RefreshCw className={`w-5 h-5 ${refreshing ? 'animate-spin' : ''}`} />
            تحديث
          </button>
          <button 
            onClick={() => setShowAddModal(true)}
            className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors"
          >
            <Plus className="w-5 h-5" />
            {t("addDevice")}
          </button>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-lg bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center">
              <Cpu className="w-5 h-5 text-blue-600" />
            </div>
            <div>
              <p className="text-2xl font-bold text-gray-900 dark:text-white">{devices.length}</p>
              <p className="text-sm text-gray-500">إجمالي الأجهزة</p>
            </div>
          </div>
        </div>
        <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-lg bg-green-100 dark:bg-green-900/30 flex items-center justify-center">
              <Wifi className="w-5 h-5 text-green-600" />
            </div>
            <div>
              <p className="text-2xl font-bold text-green-600">{onlineCount}</p>
              <p className="text-sm text-gray-500">متصل</p>
            </div>
          </div>
        </div>
        <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-4">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-lg bg-red-100 dark:bg-red-900/30 flex items-center justify-center">
              <WifiOff className="w-5 h-5 text-red-600" />
            </div>
            <div>
              <p className="text-2xl font-bold text-red-600">{offlineCount}</p>
              <p className="text-sm text-gray-500">غير متصل</p>
            </div>
          </div>
        </div>
      </div>

      {/* Add Device Modal */}
      {showAddModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center">
          <div className="absolute inset-0 bg-black/50" onClick={() => setShowAddModal(false)} />
          <div className="relative bg-white dark:bg-gray-800 rounded-xl shadow-xl w-full max-w-md mx-4 p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white">{t("addDevice")}</h2>
              <button onClick={() => setShowAddModal(false)} className="p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded">
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium mb-1">اسم الجهاز (إنجليزي) *</label>
                <input
                  type="text"
                  value={newDevice.name}
                  onChange={(e) => setNewDevice({ ...newDevice, name: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-900"
                  placeholder="Device Name"
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1">اسم الجهاز (عربي)</label>
                <input
                  type="text"
                  value={newDevice.name_ar}
                  onChange={(e) => setNewDevice({ ...newDevice, name_ar: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-900"
                  placeholder="اسم الجهاز"
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1">نوع الجهاز *</label>
                <select
                  value={newDevice.device_type}
                  onChange={(e) => setNewDevice({ ...newDevice, device_type: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-900"
                >
                  <option value="environment_sensor">حساس بيئة</option>
                  <option value="motion_sensor">حساس حركة</option>
                  <option value="door_lock">قفل باب</option>
                  <option value="smart_plug">مقبس ذكي</option>
                  <option value="switch">مفتاح</option>
                  <option value="curtain_motor">محرك ستائر</option>
                  <option value="rgb_light">إضاءة RGB</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium mb-1">معرف الجهاز (LifeSmart ID) *</label>
                <input
                  type="text"
                  value={newDevice.lifesmart_device_id}
                  onChange={(e) => setNewDevice({ ...newDevice, lifesmart_device_id: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-900"
                  placeholder="LS-XXXX-XXXX"
                />
              </div>
            </div>
            <div className="flex gap-3 mt-6">
              <button
                onClick={() => setShowAddModal(false)}
                className="flex-1 px-4 py-2 border border-gray-200 dark:border-gray-700 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
              >
                إلغاء
              </button>
              <button
                onClick={handleAddDevice}
                disabled={saving || !newDevice.name || !newDevice.lifesmart_device_id}
                className="flex-1 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {saving ? "جاري الحفظ..." : "إضافة"}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Search & Filter */}
      <div className="flex flex-col sm:flex-row gap-4">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
          <input
            type="text"
            placeholder={t("searchPlaceholder")}
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2 border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800 focus:ring-2 focus:ring-primary focus:border-transparent"
          />
        </div>
        <select
          value={filterType}
          onChange={(e) => setFilterType(e.target.value)}
          className="px-4 py-2 border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800"
        >
          <option value="all">جميع الأنواع</option>
          <option value="environment_sensor">حساس بيئة</option>
          <option value="motion_sensor">حساس حركة</option>
          <option value="door_sensor">حساس باب</option>
        </select>
        <select
          value={filterStatus}
          onChange={(e) => setFilterStatus(e.target.value)}
          className="px-4 py-2 border border-gray-200 dark:border-gray-700 rounded-lg bg-white dark:bg-gray-800"
        >
          <option value="all">جميع الحالات</option>
          <option value="online">متصل</option>
          <option value="offline">غير متصل</option>
        </select>
      </div>

      {/* Devices Grid */}
      {filteredDevices.length === 0 ? (
        <div className="text-center py-12 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700">
          <Cpu className="w-12 h-12 text-gray-400 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
            {t("noDevices")}
          </h3>
          <p className="text-gray-500 dark:text-gray-400">{t("noDevicesDesc")}</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filteredDevices.map((device) => {
            const readings = device.device_metadata?.readings;
            return (
              <Link
                key={device.id}
                href={`/${locale}/dashboard/devices/${device.id}`}
                className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-5 hover:shadow-xl hover:border-primary/50 transition-all cursor-pointer block group"
              >
                {/* Header */}
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-center gap-3">
                    <div className={`w-12 h-12 rounded-xl flex items-center justify-center ${
                      device.is_online 
                        ? "bg-gradient-to-br from-green-400 to-green-600" 
                        : "bg-gradient-to-br from-gray-300 to-gray-500"
                    }`}>
                      <Activity className="w-6 h-6 text-white" />
                    </div>
                    <div>
                      <h3 className="font-semibold text-gray-900 dark:text-white group-hover:text-primary transition-colors">
                        {device.name}
                      </h3>
                      <p className="text-sm text-gray-500 dark:text-gray-400">
                        {getDeviceTypeLabel(device.device_type)}
                      </p>
                    </div>
                  </div>
                  <span className={`flex items-center gap-1 text-xs px-2.5 py-1 rounded-full font-medium ${
                    device.is_online
                      ? "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400"
                      : "bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400"
                  }`}>
                    <span className={`w-2 h-2 rounded-full ${device.is_online ? 'bg-green-500 animate-pulse' : 'bg-red-500'}`}></span>
                    {device.is_online ? "متصل" : "غير متصل"}
                  </span>
                </div>

                {/* Readings Grid */}
                {readings && (
                  <div className="grid grid-cols-2 gap-3 mb-4">
                    {readings.temperature !== undefined && (
                      <div className="bg-orange-50 dark:bg-orange-900/20 rounded-lg p-3">
                        <div className="flex items-center gap-2 mb-1">
                          <Thermometer className="w-4 h-4 text-orange-500" />
                          <span className="text-xs text-gray-500">الحرارة</span>
                        </div>
                        <p className="text-lg font-bold text-gray-900 dark:text-white">
                          {readings.temperature}°C
                        </p>
                      </div>
                    )}
                    {readings.humidity !== undefined && (
                      <div className="bg-blue-50 dark:bg-blue-900/20 rounded-lg p-3">
                        <div className="flex items-center gap-2 mb-1">
                          <Droplets className="w-4 h-4 text-blue-500" />
                          <span className="text-xs text-gray-500">الرطوبة</span>
                        </div>
                        <p className="text-lg font-bold text-gray-900 dark:text-white">
                          {readings.humidity}%
                        </p>
                      </div>
                    )}
                    {readings.illuminance !== undefined && (
                      <div className="bg-yellow-50 dark:bg-yellow-900/20 rounded-lg p-3">
                        <div className="flex items-center gap-2 mb-1">
                          <Sun className="w-4 h-4 text-yellow-500" />
                          <span className="text-xs text-gray-500">الإضاءة</span>
                        </div>
                        <p className="text-lg font-bold text-gray-900 dark:text-white">
                          {readings.illuminance} lux
                        </p>
                      </div>
                    )}
                    {readings.battery !== undefined && (
                      <div className="bg-green-50 dark:bg-green-900/20 rounded-lg p-3">
                        <div className="flex items-center gap-2 mb-1">
                          <Battery className="w-4 h-4 text-green-500" />
                          <span className="text-xs text-gray-500">البطارية</span>
                        </div>
                        <p className="text-lg font-bold text-gray-900 dark:text-white">
                          {readings.battery}%
                        </p>
                      </div>
                    )}
                  </div>
                )}

                {/* Footer */}
                <div className="flex items-center justify-between pt-3 border-t border-gray-100 dark:border-gray-700">
                  <span className="text-xs text-gray-400">
                    ID: {device.lifesmart_device_id}
                  </span>
                  <div className="flex items-center text-xs text-primary font-medium">
                    عرض التفاصيل
                    <ChevronRight className="w-4 h-4 mr-1 group-hover:translate-x-1 transition-transform" />
                  </div>
                </div>
              </Link>
            );
          })}
        </div>
      )}
    </div>
  );
}
