'use client'

import React, { useEffect, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from "recharts";
import { AlertTriangle, CheckCircle, CalendarDays } from "lucide-react";

// Elegant RDM/RDB Dashboard — PLTU Tanjung Jadi B
// Combines predictive alert, KPI metrics, and calendar popup for RDM/RDB view.

const MOCK_RDM = (() => {
  const today = new Date();
  return Array.from({ length: 14 }).map((_, i) => {
    const d = new Date(today);
    d.setDate(today.getDate() + i);
    const failed = today.getDate() + i == today.getDate() + 6;
    return {
      date: d.toISOString().slice(0, 10),
      daya_mw: Math.round(280 + 15 * Math.sin(i / 2) + Math.random() * 6),
      failed,
      note: failed ? "Gagal mencapai RDM (perbaikan unit)" : "Rencana tercapai",
    };
  });
})();

const MOCK_RDB = (() => {
  const today = new Date();
  return Array.from({ length: 8 }).map((_, i) => {
    const d = new Date(today);
    d.setDate(today.getDate() + i * 7);
    const failed = (today.getDate() + i) * 7 == (today.getDate() + 6) * 7;
    return {
      week: i + 1,
      startDate: d.toISOString().slice(0, 10),
      daya_mw: Math.round(285 + 10 * Math.cos(i / 2) + Math.random() * 8),
      failed,
      note: failed ? "RDB tidak tercapai (maintenance)" : "RDB tercapai",
    };
  });
})();

const MOCK_ALERT = {
  exists: true,
  type: "Predictive Failure",
  component: "Boiler Feed Pump 2",
  days_to_failure: 7,
  severity: "High",
  recommended_actions: [
    "Jadwalkan maintenance 2 hari ke depan",
    "Siapkan spare part dan inspeksi getaran",
    "Pantau tekanan sistem harian hingga perbaikan",
  ],
};

export default function DashboardRdmRdbElegant() {
  const [mode, setMode] = useState("rdm"); // 'rdm' or 'rdb'
  const [rdmData, setRdmData] = useState(MOCK_RDM);
  const [rdbData, setRdbData] = useState(MOCK_RDB);
  const [alert, setAlert] = useState(MOCK_ALERT);
  const [showCalendar, setShowCalendar] = useState(false);
  const [selectedItem, setSelectedItem] = useState(null);

  const data = mode === "rdm" ? rdmData : rdbData;
  const maxDaya = Math.max(...data.map((d) => d.daya_mw));

  const avgDaya = Math.round(
    data.reduce((sum, d) => sum + d.daya_mw, 0) / data.length
  );
  const successRate = Math.round(
    (data.filter((d) => !d.failed).length / data.length) * 100
  );

  return (
    <div className="p-6 bg-slate-50 min-h-screen text-slate-800">
      {/* HEADER */}
      <header className="flex justify-between items-center mb-6">
        <div>
          <h1 className="text-2xl font-semibold">Dashboard Daya Mampu — PLTU Tanjung Jati B</h1>
          <p className="text-sm text-slate-500">Prediksi Thermodinamika & HHV Batubara</p>
        </div>
        <div className="flex gap-3">
          <button
            onClick={() => setMode("rdm")}
            className={`px-3 py-1 rounded ${mode === "rdm" ? "bg-sky-600 text-white" : "bg-white border"}`}>
            RDM (2 Minggu)
          </button>
          <button
            onClick={() => setMode("rdb")}
            className={`px-3 py-1 rounded ${mode === "rdb" ? "bg-sky-600 text-white" : "bg-white border"}`}>
            RDB (2 Bulan)
          </button>
          <button
            onClick={() => setShowCalendar(true)}
            className="flex items-center gap-2 px-3 py-1 rounded bg-white border">
            <CalendarDays size={16} /> Detail {mode.toUpperCase()}
          </button>
        </div>
      </header>

      {/* ALERT PANEL */}
      {alert && alert.exists && (
        <div className="bg-amber-50 border-l-4 border-amber-400 p-4 rounded shadow-sm mb-6">
          <div className="flex justify-between items-start">
            <div>
              <h3 className="font-semibold">Prediksi Kerusakan — {alert.component}</h3>
              <p className="text-sm text-slate-600">Keparahan: <span className="font-medium">{alert.severity}</span></p>
              <ul className="mt-2 text-sm list-disc ml-5 text-slate-700">
                {alert.recommended_actions.map((a, i) => <li key={i}>{a}</li>)}
              </ul>
            </div>
            <div className="text-right">
              <p className="text-xl font-bold">{alert.days_to_failure} hari</p>
              <p className="text-xs text-slate-500">hingga estimasi kegagalan</p>
            </div>
          </div>
        </div>
      )}

      {/* GRAFIK */}
      <section className="bg-white p-4 rounded shadow-sm mb-6">
        <div className="flex justify-between items-center mb-3">
          <h2 className="font-semibold">Grafik Daya Mampu — {mode.toUpperCase()}</h2>
          <span className="text-sm text-slate-500">Maksimum: {maxDaya} MW</span>
        </div>
        <div style={{ height: 300 }}>
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart data={data}>
              <defs>
                <linearGradient id="daya" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#0284c7" stopOpacity={0.8} />
                  <stop offset="95%" stopColor="#0284c7" stopOpacity={0.05} />
                </linearGradient>
              </defs>
              <XAxis dataKey={mode === "rdm" ? "date" : "week"} tick={{ fontSize: 10 }} />
              <YAxis />
              <CartesianGrid strokeDasharray="3 3" />
              <Tooltip formatter={(value) => `${value} MW`} />
              <Area type="monotone" dataKey="daya_mw" stroke="#0284c7" fill="url(#daya)" name="Daya (MW)" />
            </AreaChart>
          </ResponsiveContainer>
        </div>
      </section>

      {/* KPI METRICS */}
      <section className="bg-white p-4 rounded shadow-sm mb-6">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div className="p-3 bg-sky-50 rounded text-center">
            <div className="text-xs text-slate-500">Kapasitas Terpasang</div>
            <div className="text-xl font-bold">320 MW</div>
          </div>
          <div className="p-3 bg-emerald-50 rounded text-center">
            <div className="text-xs text-slate-500">Rata-rata Daya</div>
            <div className="text-xl font-bold">{avgDaya} MW</div>
          </div>
          <div className="p-3 bg-rose-50 rounded text-center">
            <div className="text-xs text-slate-500">Tingkat Keberhasilan</div>
            <div className="text-xl font-bold">{successRate}%</div>
          </div>
          <div className="p-3 bg-white rounded border text-center">
            <div className="text-xs text-slate-500">Terakhir Sinkronisasi</div>
            <div className="text-sm">{new Date().toLocaleString()}</div>
          </div>
        </div>
      </section>

      {/* POPUP CALENDAR MODAL */}
      <AnimatePresence>
        {showCalendar && (
          <motion.div
            className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center z-50"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}>
            <motion.div
              className="bg-white rounded-lg shadow-xl p-6 w-[90%] max-w-4xl relative"
              initial={{ scale: 0.9, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.9, opacity: 0 }}>
              <button
                onClick={() => setShowCalendar(false)}
                className="absolute top-3 right-3 text-slate-500 hover:text-slate-700">
                ✕
              </button>
              <h3 className="text-lg font-semibold mb-4 text-center">{mode === "rdm" ? "Rencana Daya Mampu (2 Minggu)" : "Rencana Daya Bulanan (8 Minggu)"}</h3>

              <div className={`grid ${mode === "rdm" ? "grid-cols-7" : "grid-cols-4"} gap-3`}>
                {data.map((d, i) => (
                  <div
                    key={i}
                    onClick={() => setSelectedItem(d)}
                    className={`p-3 rounded border text-center cursor-pointer transition-all hover:shadow-md ${d.failed ? "bg-rose-50 border-rose-300" : "bg-emerald-50 border-emerald-300"}`}>
                    <div className="font-medium">
                      {mode === "rdm" ? new Date(d.date).getDate() : `Minggu ${d.week}`}
                    </div>
                    <div className="mt-1 flex justify-center">
                      {d.failed ? <AlertTriangle size={16} className="text-rose-500" /> : <CheckCircle size={16} className="text-emerald-500" />}
                    </div>
                    <div className="text-xs mt-1 text-slate-600">{d.daya_mw} MW</div>
                  </div>
                ))}
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* ITEM DETAIL POPUP */}
      <AnimatePresence>
        {selectedItem && (
          <motion.div
            className="fixed inset-0 bg-black/50 flex items-center justify-center z-50"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}>
            <motion.div
              className="bg-white rounded-lg p-6 w-96 relative shadow-xl"
              initial={{ scale: 0.9, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.9, opacity: 0 }}>
              <button onClick={() => setSelectedItem(null)} className="absolute top-3 right-3 text-slate-500 hover:text-slate-800">✕</button>
              <h4 className="text-lg font-semibold mb-2">Detail {mode.toUpperCase()}</h4>
              <p className="text-sm mb-1">{mode === "rdm" ? `Tanggal: ${selectedItem.date}` : `Minggu ke-${selectedItem.week}`}</p>
              <p className="text-sm mb-1">Daya: <span className="font-semibold">{selectedItem.daya_mw} MW</span></p>
              <p className="text-sm mb-3">Status: {selectedItem.failed ? <span className="text-rose-600 font-medium">{selectedItem.note}</span> : <span className="text-emerald-600 font-medium">{selectedItem.note}</span>}</p>
              <div className="flex justify-end gap-2">
                <button className="px-3 py-1 rounded bg-sky-600 text-white">Analisa</button>
                <button onClick={() => setSelectedItem(null)} className="px-3 py-1 rounded border">Tutup</button>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      <footer className="text-xs text-slate-500 mt-8 text-center">Sumber: Efficiency Heat Loss • Penyesuaian HHV Batubara • RDM & RDB PLTU Tanjung Jati B</footer>
    </div>
  );
}
