"use client";

import React, { useState, useRef, useCallback, useEffect } from "react";
import { useRouter } from "next/navigation";
import { usePopCompanyPath } from "@/hooks/usePopCompanyPath";

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

interface ProductionMenuItem {
  id: string;
  title: string;
  gradient: string;
  shadowColor: string;
  icon: React.ReactNode;
  href: string;
}

/* ------------------------------------------------------------------ */
/* Static Data                                                         */
/* ------------------------------------------------------------------ */

const MENU_ITEMS: ProductionMenuItem[] = [
  {
    id: "process-execution",
    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="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z" />
        <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
      </svg>
    ),
    href: "/pop/production/process",
  },
];

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

function ProductionMenu() {
  const router = useRouter();
  const companyPath = usePopCompanyPath();

  /* KPI carousel */
  const [kpiIdx, setKpiIdx] = useState(0);
  const kpiTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const startKpiAuto = useCallback(() => {
    if (kpiTimerRef.current) clearInterval(kpiTimerRef.current);
    kpiTimerRef.current = setInterval(() => setKpiIdx((p) => (p + 1) % 3), 4000);
  }, []);

  useEffect(() => {
    startKpiAuto();
    return () => {
      if (kpiTimerRef.current) clearInterval(kpiTimerRef.current);
    };
  }, [startKpiAuto]);

  const handleMenuClick = (item: ProductionMenuItem) => {
    if (item.href === "#") {
      alert(`${item.title} 화면은 준비 중입니다.`);
    } else {
      router.push(companyPath(item.href));
    }
  };

  return (
    <div className="flex flex-col gap-5">
      {/* ===== Back + Title ===== */}
      <div className="flex items-center gap-3">
        <button
          onClick={() => router.push(companyPath("/pop/main"))}
          className="w-10 h-10 rounded-xl bg-white border border-gray-200 flex items-center justify-center text-gray-500 hover:bg-gray-50 active:scale-95 transition-all"
        >
          <svg className="w-5 h-5" 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 sm:text-2xl font-bold text-gray-900 tracking-tight">생산관리</h1>
          <p className="text-xs text-gray-400 mt-0.5">메뉴를 선택하세요</p>
        </div>
      </div>

      {/* ===== KPI Carousel ===== */}
      <div className="relative overflow-hidden">
        <div
          className="flex select-none"
          style={{
            transform: `translateX(-${kpiIdx * 100}%)`,
            transition: "transform 0.4s cubic-bezier(.25,.46,.45,.94)",
          }}
        >
          {/* Slide 1 */}
          <div className="min-w-full shrink-0">
            <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 sm:p-5">
              <div className="grid grid-cols-3 gap-0">
                <KpiCell value="0" label="금일 생산" color="text-amber-600" />
                <KpiCell value="0" label="진행 중" color="text-blue-600" />
                <KpiCell value="0" label="완료" color="text-green-600" />
              </div>
            </div>
          </div>
          {/* Slide 2 */}
          <div className="min-w-full shrink-0">
            <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 sm:p-5">
              <div className="grid grid-cols-3 gap-0">
                <KpiCell value="0" label="작업지시" color="text-amber-600" unit="건" />
                <KpiCell value="0" label="공정완료" color="text-green-600" unit="건" />
                <KpiCell value="0" label="불량" color="text-red-600" unit="건" />
              </div>
            </div>
          </div>
          {/* Slide 3 */}
          <div className="min-w-full shrink-0">
            <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 sm:p-5">
              <div className="grid grid-cols-3 gap-0">
                <KpiCell value="0" label="금일 수량" color="text-amber-600" unit="EA" />
                <KpiCell value="0" label="달성률" color="text-green-600" unit="%" />
                <KpiCell value="0" label="불량률" color="text-red-600" unit="%" />
              </div>
            </div>
          </div>
        </div>
        {/* Dots */}
        <div className="flex justify-center gap-2 mt-3">
          {[0, 1, 2].map((idx) => (
            <button
              key={idx}
              onClick={() => {
                setKpiIdx(idx);
                startKpiAuto();
              }}
              className="border-none p-0 transition-all duration-300 cursor-pointer"
              style={{
                width: kpiIdx === idx ? 24 : 8,
                height: 8,
                borderRadius: kpiIdx === idx ? 4 : "50%",
                background: kpiIdx === idx ? "#f59e0b" : "#D1D5DB",
              }}
              aria-label={`KPI 슬라이드 ${idx + 1}`}
            />
          ))}
        </div>
      </div>

      {/* ===== Production Menu ===== */}
      <section>
        <div className="flex items-center gap-2 mb-3">
          <div className="w-1 h-5 rounded-full bg-amber-500" />
          <h2 className="text-base sm:text-lg font-bold text-gray-900">생산 메뉴</h2>
        </div>
        <div className="flex flex-wrap justify-start gap-x-5 gap-y-4 sm:gap-x-6 sm:gap-y-5">
          {MENU_ITEMS.map((item) => (
            <MenuIcon key={item.id} item={item} onClick={handleMenuClick} />
          ))}
        </div>
      </section>

      {/* ===== Recent Activity ===== */}
      <section>
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 sm:p-5">
          <div className="flex items-center justify-between mb-4 pb-3 border-b border-gray-100">
            <h3 className="text-base sm:text-lg font-bold text-gray-900">최근 생산활동</h3>
            <span className="text-xs text-gray-400">최근 5건</span>
          </div>
          <div className="flex items-center justify-center py-8">
            <p className="text-sm text-gray-400">최근 생산활동 내역이 없습니다</p>
          </div>
        </div>
      </section>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/* Sub-components                                                      */
/* ------------------------------------------------------------------ */

function KpiCell({
  value,
  label,
  color,
  unit,
}: {
  value: string;
  label: string;
  color: string;
  unit?: string;
}) {
  return (
    <div className="flex flex-col items-center py-2">
      <div className="flex items-end gap-0.5">
        <span
          className={`text-2xl sm:text-3xl font-extrabold leading-none ${color}`}
          style={{ fontVariantNumeric: "tabular-nums", letterSpacing: "-0.02em" }}
        >
          {value}
        </span>
        {unit && <span className="text-xs text-gray-400 mb-0.5">{unit}</span>}
      </div>
      <span className="text-[11px] font-medium text-gray-400 mt-1">{label}</span>
    </div>
  );
}

function MenuIcon({
  item,
  onClick,
}: {
  item: ProductionMenuItem;
  onClick: (item: ProductionMenuItem) => void;
}) {
  return (
    <div
      className="flex flex-col items-center gap-2 w-16 sm:w-[72px] cursor-pointer group"
      style={{ WebkitTapHighlightColor: "transparent" }}
      onClick={() => onClick(item)}
    >
      <div
        className="w-14 h-14 sm:w-16 sm:h-16 rounded-2xl flex items-center justify-center transition-transform duration-150 group-hover:scale-105 group-active:scale-[0.93]"
        style={{ background: item.gradient, boxShadow: `0 4px 12px ${item.shadowColor}` }}
      >
        {item.icon}
      </div>
      <span className="text-[11px] sm:text-xs font-semibold text-gray-700 text-center leading-tight">
        {item.title}
      </span>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/* Page                                                                */
/* ------------------------------------------------------------------ */

export default function ProductionPage() {
  return <ProductionMenu />;
}
