"use client";

import { useRouter } from "next/navigation";
import React, { useEffect, useState } from "react";
import { apiClient } from "@/lib/api/client";

/* ------------------------------------------------------------------ */
/* Types                                                               */
/* ------------------------------------------------------------------ */

interface EquipmentItem {
  id: string;
  equipment_code: string;
  equipment_name: string;
  equipment_type?: string;
  status?: string;
}

interface KpiData {
  total: number;
  active: number;
  idle: number;
  inspect: number;
  rate: string;
}

/* ------------------------------------------------------------------ */
/* Menu                                                                */
/* ------------------------------------------------------------------ */

const MENU_ITEMS = [
  {
    id: "management",
    title: "설비관리",
    gradient: "linear-gradient(135deg,#8b5cf6,#6d28d9)",
    shadowColor: "rgba(139,92,246,.3)",
    icon: (
      <svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" d="M11.42 15.17l-5.65-5.65a8 8 0 1111.31 0l-5.65 5.65z" />
      </svg>
    ),
    href: "/pop/equipment/management",
  },
  {
    id: "inspection",
    title: "설비점검",
    gradient: "linear-gradient(135deg,#f59e0b,#d97706)",
    shadowColor: "rgba(245,158,11,.3)",
    icon: (
      <svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={1.5} viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" d="M21.75 6.75a4.5 4.5 0 01-4.884 4.484c-1.076-.091-2.264.071-2.95.904l-7.152 8.684a2.548 2.548 0 11-3.586-3.586l8.684-7.152c.833-.686.995-1.874.904-2.95a4.5 4.5 0 016.336-4.486l-3.276 3.276a3.004 3.004 0 002.25 2.25l3.276-3.276c.256.565.398 1.192.398 1.852z" />
      </svg>
    ),
    href: "/pop/equipment/inspection",
  },
];

/* ------------------------------------------------------------------ */
/* Component                                                           */
/* ------------------------------------------------------------------ */

export function EquipmentHome() {
  const router = useRouter();

  const [kpi, setKpi] = useState<KpiData>({
    total: 0,
    active: 0,
    idle: 0,
    inspect: 0,
    rate: "0%",
  });
  const [recentItems, setRecentItems] = useState<EquipmentItem[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const res = await apiClient.get("/data/equipment_mng", {
          params: { pageSize: 500 },
        });
        const data = res.data?.data?.data ?? res.data?.data ?? [];
        const items = Array.isArray(data) ? data : [];
        const total = items.length;
        const active = items.filter((i: EquipmentItem) => !i.status || i.status === "가동" || i.status === "정상").length;
        const idle = items.filter((i: EquipmentItem) => i.status === "대기").length;
        const inspect = items.filter((i: EquipmentItem) => i.status === "점검").length;
        const rate = total > 0 ? `${Math.round((active / total) * 100)}%` : "0%";
        setKpi({ total, active, idle, inspect, rate });
        setRecentItems(items.slice(0, 5));
      } catch { /* */ }
      setLoading(false);
    };
    fetchData();
  }, []);

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <div className="bg-white px-5 pt-5 pb-4">
        <div className="flex items-center gap-3 mb-3">
          <button onClick={() => router.back()} className="w-9 h-9 rounded-xl bg-gray-100 flex items-center justify-center hover:bg-gray-200 transition-colors">
            <svg className="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M15.75 19.5L8.25 12l7.5-7.5" />
            </svg>
          </button>
          <div>
            <h1 className="text-xl font-bold text-gray-900">설비</h1>
            <p className="text-sm text-gray-500">설비 현황 및 점검 관리</p>
          </div>
        </div>

        {/* KPI */}
        <div className="bg-white rounded-2xl border border-gray-200 p-4">
          <div className="grid grid-cols-5 text-center divide-x divide-gray-100">
            {[
              { value: loading ? "-" : kpi.total, label: "전체", color: "text-gray-900" },
              { value: loading ? "-" : kpi.active, label: "가동", color: "text-green-600" },
              { value: loading ? "-" : kpi.idle, label: "대기", color: "text-blue-600" },
              { value: loading ? "-" : kpi.inspect, label: "점검", color: "text-red-600" },
              { value: loading ? "-" : kpi.rate, label: "가동률", color: "text-purple-600" },
            ].map((item) => (
              <div key={item.label} className="px-2">
                <p className={`text-2xl font-extrabold ${item.color}`}>{item.value}</p>
                <p className="text-xs text-gray-400 mt-0.5">{item.label}</p>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Menu Icons */}
      <div className="px-5 pt-5">
        <h2 className="flex items-center gap-2 text-sm font-bold text-gray-700 mb-3">
          <span className="w-1 h-4 bg-purple-500 rounded" />
          설비 관리
        </h2>
        <div className="flex gap-4">
          {MENU_ITEMS.map((item) => (
            <button
              key={item.id}
              onClick={() => router.push(item.href)}
              className="flex flex-col items-center gap-2 active:scale-95 transition-transform"
            >
              <div
                className="w-14 h-14 rounded-2xl flex items-center justify-center"
                style={{
                  background: item.gradient,
                  boxShadow: `0 4px 12px ${item.shadowColor}`,
                }}
              >
                {item.icon}
              </div>
              <span className="text-xs font-semibold text-gray-700">{item.title}</span>
            </button>
          ))}
        </div>
      </div>

      {/* Recent Equipment */}
      <div className="px-5 pt-6 pb-24">
        <div className="bg-white rounded-2xl border border-gray-200 overflow-hidden">
          <div className="flex items-center justify-between px-4 py-3 border-b border-gray-100">
            <h3 className="font-bold text-gray-900">최근 설비</h3>
            <span className="text-xs text-gray-400">최근 5건</span>
          </div>
          {loading ? (
            <div className="flex justify-center py-12">
              <div className="w-6 h-6 border-3 border-purple-500 border-t-transparent rounded-full animate-spin" />
            </div>
          ) : recentItems.length === 0 ? (
            <div className="text-center py-12 text-gray-400 text-sm">등록된 설비가 없습니다</div>
          ) : (
            <div className="divide-y divide-gray-50">
              {recentItems.map((item) => (
                <div key={item.id} className="flex items-center justify-between px-4 py-3">
                  <div>
                    <p className="text-sm font-semibold text-gray-900">{item.equipment_name || "-"}</p>
                    <p className="text-xs text-gray-400">{item.equipment_code} {item.equipment_type ? `· ${item.equipment_type}` : ""}</p>
                  </div>
                  <span className={`text-xs px-2 py-0.5 rounded-full font-semibold ${
                    item.status === "정지" || item.status === "비가동"
                      ? "bg-red-50 text-red-600"
                      : item.status === "점검"
                        ? "bg-amber-50 text-amber-600"
                        : "bg-green-50 text-green-600"
                  }`}>
                    {item.status || "정상"}
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
