"use client";

import { useEffect, useState } from "react";
import axios from "axios";
import { Zap, Check, X, Info, Activity } from "lucide-react";

export default function AdminDashboard() {
  const [pendingBookings, setPendingBookings] = useState<any[]>([]);
  const [roomStats, setRoomStats] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  
  // STATE BARU: Penampung total daya asli khusus Kelas D101
  const [d101Power, setD101Power] = useState<number>(0);

  useEffect(() => {
    fetchAdminData();
    fetchD101Power(); // Panggil fungsi daya saat pertama kali render
    
    // Refresh data ruangan setiap 10 detik
    const intervalAdmin = setInterval(fetchAdminData, 10000);
    // Refresh data konsumsi daya D101 lebih cepat (tiap 5 detik) agar sangat responsif
    const intervalPower = setInterval(fetchD101Power, 5000); 
    
    return () => {
      clearInterval(intervalAdmin);
      clearInterval(intervalPower);
    };
  }, []);

  // FUNGSI BARU: Mengambil data asli dari Smart Meter via Golang API
  const fetchD101Power = async () => {
    try {
      const res = await axios.get("http://172.17.172.17:8080/api/power-status");
      // Kalkulasi total seluruh alat (Lampu/Proyektor + AC 1 + AC 2)
      const totalWatt = (res.data.umum || 0) + (res.data.ac1 || 0) + (res.data.ac2 || 0);
      setD101Power(parseFloat(totalWatt.toFixed(1)));
    } catch (err) {
      console.error("Gagal mengambil data daya aktual D101", err);
    }
  };

  const fetchAdminData = async () => {
    try {
      const token = localStorage.getItem("token");
      
      // 1. Ambil SEMUA booking
      const bookRes = await axios.get("http://172.17.172.17:8080/api/bookings", { 
        headers: { Authorization: `Bearer ${token}` } 
      });
      
      const allBookings = bookRes.data.data || [];
      const pendingOnly = allBookings.filter((b: any) => b.status === "Pending" || !b.status);
      setPendingBookings(pendingOnly);

      // 2. Ambil daftar ruangan
      const roomRes = await axios.get("http://172.17.172.17:8080/api/rooms", { 
        headers: { Authorization: `Bearer ${token}` } 
      });
      
      const roomsWithDummyPower = (roomRes.data.data || []).map((room: any) => ({
        ...room,
        // Berikan simulasi dummy HANYA untuk ruangan SELAIN D101
        power_consumption: room.name === "Kelas D101" ? 0 : Math.floor(Math.random() * 15) 
      }));
      setRoomStats(roomsWithDummyPower);

    } catch (err) {
      console.error("Gagal ambil data admin", err);
    } finally {
      setLoading(false);
    }
  };

  const handleAction = async (id: string, status: string) => {
    try {
      const token = localStorage.getItem("token");
      await axios.put(`http://172.17.172.17:8080/api/bookings/${id}/status`, 
        { status: status }, 
        { headers: { Authorization: `Bearer ${token}` } }
      );
      alert(`Permintaan berhasil di-${status}`);
      fetchAdminData(); 
    } catch (err: any) {
      console.error(err);
      alert("Gagal memproses pendaftaran.");
    }
  };

  if (loading) return <div className="p-10 font-medium text-gray-500">Memasuki Mode Admin...</div>;

  return (
    <div className="space-y-8">
      {/* SECTION 1: POWER MONITORING CARDS */}
      <div>
        <h2 className="text-xl font-bold text-gray-800 mb-4 flex items-center gap-2">
          <Activity className="text-blue-500" /> Real-time Room Energy
        </h2>
       <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          {[...roomStats]
            .sort((a, b) => a.name.localeCompare(b.name))
            .map((room) => {
              // LOGIKA INJEKSI DATA ASLI: Cek apakah kelas ini adalah D101
              const isD101 = room.name === "Kelas D101";
              const displayedPower = isD101 ? d101Power : room.power_consumption;
              const isPowerActive = displayedPower > 0;

              return (
                <div key={room.room_id} 
                  className={`bg-white p-5 rounded-xl border shadow-sm transition-all
                  ${isD101 ? 'border-blue-200 border-l-4 border-l-blue-500 bg-blue-50/10' : 'border-gray-100'}`}>
                  
                  <div className="flex justify-between items-start mb-3">
                    <span className={`text-sm font-bold uppercase tracking-tight ${isD101 ? 'text-blue-700' : 'text-gray-400'}`}>
                      {room.name} {isD101 && <span className="ml-1 text-[9px] bg-blue-100 text-blue-700 px-2 py-0.5 rounded-full">SENSOR ASLI</span>}
                    </span>
                    <div className={`h-3 w-3 rounded-full ${isPowerActive ? (isD101 ? 'bg-green-500 animate-pulse' : 'bg-orange-500 animate-pulse') : 'bg-gray-300'}`} />
                  </div>
                  
                  <div className="flex items-end gap-2">
                    <span className={`text-3xl font-black ${isD101 ? 'text-blue-700' : 'text-gray-800'}`}>
                      {displayedPower}
                    </span>
                    <span className="text-gray-500 font-bold mb-1">Watts</span>
                  </div>
                  
                  <p className="text-[10px] text-gray-400 mt-2 font-medium">Last updated: Just now</p>
                </div>
              );
          })}
        </div>
      </div>

      {/* SECTION 2: APPROVAL TABLE */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <div className="p-6 border-b border-gray-50 flex justify-between items-center">
          <h2 className="text-xl font-bold text-gray-800">Pending Approvals</h2>
          <span className="bg-blue-100 text-blue-700 px-3 py-1 rounded-full text-xs font-bold">
            {pendingBookings.length} Requests
          </span>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead className="bg-gray-50 text-gray-500 text-xs font-bold uppercase">
              <tr>
                <th className="p-4">Peminjam</th>
                <th className="p-4">Ruangan</th>
                <th className="p-4">Tanggal & Waktu</th>
                <th className="p-4">Keperluan</th>
                <th className="p-4 text-center">Tindakan</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-50">
              {pendingBookings.map((b) => (
                <tr key={b.booking_id} className="hover:bg-gray-50/50 transition-colors">
                  <td className="p-4 font-bold text-gray-800 text-sm">{b.user?.full_name || "Tanpa Nama"}</td>
                  <td className="p-4 text-sm font-medium text-gray-600">{b.room?.name || "Ruangan Tidak Diketahui"}</td>
                  
                  <td className="p-4 text-sm text-gray-600">
                    <div className="font-bold">
                      {new Date(b.start_time).toLocaleTimeString('id-ID', {hour: '2-digit', minute:'2-digit'})} - {new Date(b.end_time).toLocaleTimeString('id-ID', {hour: '2-digit', minute:'2-digit'})}
                    </div>
                    <div className="text-xs text-gray-400">
                      {new Date(b.start_time).toLocaleDateString('id-ID')}
                    </div>
                  </td>

                  <td className="p-4 text-sm text-gray-600 truncate max-w-60">{b.purpose}</td>
                  <td className="p-4">
                    <div className="flex justify-center gap-2">
                      <button 
                        onClick={() => handleAction(b.booking_id, 'Approved')} 
                        className="p-2 bg-green-50 text-green-600 rounded-lg hover:bg-green-100 transition-colors"
                      >
                        <Check size={18} />
                      </button>
                      <button 
                        onClick={() => handleAction(b.booking_id, 'Rejected')} 
                        className="p-2 bg-red-50 text-red-600 rounded-lg hover:bg-red-100 transition-colors"
                      >
                        <X size={18} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
              {pendingBookings.length === 0 && (
                <tr>
                  <td colSpan={5} className="p-10 text-center text-gray-400 text-sm italic">Tidak ada permintaan menunggu.</td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}