"use client";

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

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

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

interface RecentInboundItem {
  id: string;
  time: string;
  type: string;
  itemName: string;
  qty: string;
  supplier: string;
  statusColor: string;
  statusLabel: string;
}

/* ------------------------------------------------------------------ */
/* Static Data (UI만)                                                  */
/* ------------------------------------------------------------------ */

const EXTERNAL_ITEMS: InboundMenuItem[] = [
  {
    id: "purchase",
    title: "구매입고",
    gradient: "linear-gradient(135deg,#3b82f6,#1d4ed8)",
    shadowColor: "rgba(59,130,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="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
      </svg>
    ),
    href: "/pop/inbound/purchase",
  },
  {
    id: "outsourcing",
    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="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" />
      </svg>
    ),
    href: "/pop/inbound/subcontractor",
  },
  {
    id: "return",
    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 15L3 9m0 0l6-6M3 9h12a6 6 0 010 12h-3" />
      </svg>
    ),
    href: "/pop/inbound/return-external",
  },
  {
    id: "supplied-material",
    title: "사급자재",
    gradient: "linear-gradient(135deg,#06b6d4,#0e7490)",
    shadowColor: "rgba(6,182,212,.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 7.5l-9-5.25L3 7.5m18 0l-9 5.25m9-5.25v9l-9 5.25M3 7.5l9 5.25M3 7.5v9l9 5.25m0-9v9" />
      </svg>
    ),
    href: "/pop/inbound/supplied",
  },
  {
    id: "defect",
    title: "불량입고",
    gradient: "linear-gradient(135deg,#ef4444,#b91c1c)",
    shadowColor: "rgba(239,68,68,.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="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
      </svg>
    ),
    href: "/pop/inbound/error",
  },
  {
    id: "outsource-return",
    title: "외주자재회수",
    gradient: "linear-gradient(135deg,#ec4899,#be185d)",
    shadowColor: "rgba(236,72,153,.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="M19.5 12c0-1.232-.046-2.453-.138-3.662a4.006 4.006 0 00-3.7-3.7 48.678 48.678 0 00-7.324 0 4.006 4.006 0 00-3.7 3.7c-.017.22-.032.441-.046.662M19.5 12l3-3m-3 3l-3-3m-12 3c0 1.232.046 2.453.138 3.662a4.006 4.006 0 003.7 3.7 48.656 48.656 0 007.324 0 4.006 4.006 0 003.7-3.7c.017-.22.032-.441.046-.662M4.5 12l3 3m-3-3l-3 3" />
      </svg>
    ),
    href: "/pop/inbound/recovery",
  },
  {
    id: "exchange",
    title: "교환입고",
    gradient: "linear-gradient(135deg,#14b8a6,#0f766e)",
    shadowColor: "rgba(20,184,166,.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="M7.5 21L3 16.5m0 0L7.5 12M3 16.5h13.5m0-13.5L21 7.5m0 0L16.5 12M21 7.5H7.5" />
      </svg>
    ),
    href: "/pop/inbound/change",
  },
];

const INTERNAL_ITEMS: InboundMenuItem[] = [
  {
    id: "production",
    title: "생산입고",
    gradient: "linear-gradient(135deg,#22c55e,#15803d)",
    shadowColor: "rgba(34,197,94,.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/inbound/production",
  },
  {
    id: "return-internal",
    title: "반납입고",
    gradient: "linear-gradient(135deg,#f97316,#c2410c)",
    shadowColor: "rgba(249,115,22,.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="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182" />
      </svg>
    ),
    href: "/pop/inbound/return-internal",
  },
  {
    id: "transfer",
    title: "재고이동",
    gradient: "linear-gradient(135deg,#64748b,#334155)",
    shadowColor: "rgba(100,116,139,.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="M7.5 7.5h-.75A2.25 2.25 0 004.5 9.75v7.5a2.25 2.25 0 002.25 2.25h7.5a2.25 2.25 0 002.25-2.25v-7.5a2.25 2.25 0 00-2.25-2.25h-.75m0-3l-3-3m0 0l-3 3m3-3v11.25m6-2.25h.75a2.25 2.25 0 012.25 2.25v7.5a2.25 2.25 0 01-2.25 2.25h-7.5a2.25 2.25 0 01-2.25-2.25v-7.5a2.25 2.25 0 012.25-2.25H12m-3 0V5.25" />
      </svg>
    ),
    href: "#",
  },
  {
    id: "inbound-manage",
    title: "입고관리",
    gradient: "linear-gradient(135deg,#3b82f6,#1e40af)",
    shadowColor: "rgba(59,130,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="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m5.231 13.481L15 17.25m-4.5-15H5.625c-.621 0-1.125.504-1.125 1.125v16.5c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9zm3.75 11.625a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z" />
      </svg>
    ),
    href: "/pop/inbound/inbound-manage",
  },
];

/* 최근 입고 정적 목업 데이터 */
const RECENT_ITEMS: RecentInboundItem[] = [
  {
    id: "1",
    time: "10:14",
    type: "구매입고",
    itemName: "데모제일 20L (3공정 시연용)",
    qty: "20 EA",
    supplier: "거래처테스트(발주처)",
    statusColor: "text-green-600 bg-green-50",
    statusLabel: "완료",
  },
  {
    id: "2",
    time: "09:52",
    type: "구매입고",
    itemName: "용주N_CTG28_반투명",
    qty: "10 EA",
    supplier: "거래처테스트(발주처)",
    statusColor: "text-gray-600 bg-gray-50",
    statusLabel: "대기",
  },
];

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

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

  /* KPI carousel */
  const [kpiIdx, setKpiIdx] = useState(1);
  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: InboundMenuItem) => {
    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-blue-600" />
                <KpiCell value="0" label="검수 대기" color="text-amber-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-blue-600" />
                <KpiCell value="0" label="구매입고" color="text-purple-600" />
                <KpiCell value="0" label="외주입고" color="text-gray-600" />
              </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-blue-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 ? "#3b82f6" : "#D1D5DB",
              }}
              aria-label={`KPI 슬라이드 ${idx + 1}`}
            />
          ))}
        </div>
      </div>

      {/* ===== External Inbound ===== */}
      <section>
        <div className="flex items-center gap-2 mb-3">
          <div className="w-1 h-5 rounded-full bg-blue-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">
          {EXTERNAL_ITEMS.map((item) => (
            <MenuIcon key={item.id} item={item} onClick={handleMenuClick} />
          ))}
        </div>
      </section>

      {/* ===== Internal Inbound ===== */}
      <section>
        <div className="flex items-center gap-2 mb-3">
          <div className="w-1 h-5 rounded-full bg-green-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">
          {INTERNAL_ITEMS.map((item) => (
            <MenuIcon key={item.id} item={item} onClick={handleMenuClick} />
          ))}
        </div>
      </section>

      {/* ===== Recent Inbound ===== */}
      <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 flex-col gap-2">
            {RECENT_ITEMS.map((item) => (
              <div
                key={item.id}
                className="flex items-center gap-3 p-3 rounded-xl hover:bg-gray-50 transition-colors"
              >
                <span
                  className="text-xs font-semibold text-gray-400 min-w-[44px] text-right"
                  style={{ fontVariantNumeric: "tabular-nums" }}
                >
                  {item.time}
                </span>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <span className="text-sm font-semibold text-gray-900 truncate">{item.itemName}</span>
                    <span
                      className={`text-[10px] font-semibold px-1.5 py-0.5 rounded-full shrink-0 ${item.statusColor}`}
                    >
                      {item.statusLabel}
                    </span>
                  </div>
                  <div className="text-xs text-gray-400 mt-0.5 truncate">
                    {item.type} | {item.supplier} | {item.qty}
                  </div>
                </div>
              </div>
            ))}
          </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: InboundMenuItem;
  onClick: (item: InboundMenuItem) => 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 InboundPage() {
  return <InboundTypeSelect />;
}
