"use client";

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

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

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

interface RecentOutboundItem {
  id: string;
  time: string;
  type: string;
  itemName: string;
  qty: string;
  customer: string;
  statusColor: string;
  statusLabel: string;
}

interface KpiData {
  todayTotal: number;
  todayWaiting: number;
  todayCompleted: number;
  salesCount: number;
  returnCount: number;
  otherCount: number;
  todayQty: number;
  todayQtyUnit: string;
}

interface OutboundRow {
  id: number;
  outbound_number: string;
  outbound_type: string | null;
  outbound_date: string | null;
  outbound_status: string | null;
  outbound_qty: number | string | null;
  item_name: string | null;
  item_code: string | null;
  customer_name: string | null;
  unit: string | null;
  created_date: string | null;
  warehouse_name: string | null;
  reference_number: string | null;
}

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

const EXTERNAL_ITEMS: OutboundMenuItem[] = [
  {
    id: "sales",
    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="M8.25 18.75a1.5 1.5 0 01-3 0m3 0a1.5 1.5 0 00-3 0m3 0h6m-9 0H3.375a1.125 1.125 0 01-1.125-1.125V14.25m17.25 4.5a1.5 1.5 0 01-3 0m3 0a1.5 1.5 0 00-3 0m3 0H6.75m11.25 0h2.625c.621 0 1.125-.504 1.125-1.125v-4.875c0-.621-.504-1.125-1.125-1.125H17.25m-13.5-.375V6.375c0-.621.504-1.125 1.125-1.125h7.5c.621 0 1.125.504 1.125 1.125v7.125" />
      </svg>
    ),
    href: "/pop/outbound/sales",
  },
  {
    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: "#",
  },
  {
    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: "#",
  },
  {
    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: "#",
  },
  {
    id: "other",
    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="M6.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0zM12.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0zM18.75 12a.75.75 0 11-1.5 0 .75.75 0 011.5 0z" />
      </svg>
    ),
    href: "#",
  },
];

const INTERNAL_ITEMS: OutboundMenuItem[] = [
  {
    id: "production",
    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="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: "#",
  },
  {
    id: "transfer",
    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="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: "#",
  },
];

/* ------------------------------------------------------------------ */
/* Helpers                                                             */
/* ------------------------------------------------------------------ */

function getStatusStyle(status: string | null): { color: string; label: string } {
  switch (status) {
    case "완료":
    case "출고완료":
      return { color: "text-green-600 bg-green-50", label: "완료" };
    case "대기":
      return { color: "text-amber-600 bg-amber-50", label: "대기" };
    case "진행중":
    case "출고중":
      return { color: "text-blue-600 bg-blue-50", label: "진행중" };
    default:
      return { color: "text-gray-600 bg-gray-50", label: status || "대기" };
  }
}

function shortenType(type: string | null): string {
  if (!type) return "기타";
  if (type.includes("판매")) return "판매출고";
  if (type.includes("반품")) return "반품출고";
  if (type.includes("외주")) return "외주출고";
  if (type.includes("생산")) return "생산출고";
  if (type.includes("사급")) return "사급출고";
  return type;
}

function isCompleted(status: string | null): boolean {
  return status === "완료" || status === "출고완료";
}

function isSales(type: string | null): boolean {
  return !!type && type.includes("판매");
}

function isReturn(type: string | null): boolean {
  return !!type && type.includes("반품");
}

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

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

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

  /* Data state */
  const [kpi, setKpi] = useState<KpiData>({
    todayTotal: 0, todayWaiting: 0, todayCompleted: 0,
    salesCount: 0, returnCount: 0, otherCount: 0,
    todayQty: 0, todayQtyUnit: "EA",
  });
  const [recentItems, setRecentItems] = useState<RecentOutboundItem[]>([]);
  const [loading, setLoading] = useState(true);

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

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

  /* Fetch real data from API */
  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        const today = new Date().toISOString().slice(0, 10);

        const [todayRes, allRes] = await Promise.all([
          apiClient.get("/outbound/list", {
            params: { date_from: today, date_to: today },
          }),
          apiClient.get("/outbound/list"),
        ]);

        const todayRows: OutboundRow[] = todayRes.data?.data ?? [];
        const allRows: OutboundRow[] = allRes.data?.data ?? [];

        // --- KPI ---
        const todayTotal = todayRows.length;
        const todayCompleted = todayRows.filter((r) => isCompleted(r.outbound_status)).length;
        const todayWaiting = todayTotal - todayCompleted;
        const salesCount = todayRows.filter((r) => isSales(r.outbound_type)).length;
        const returnCount = todayRows.filter((r) => isReturn(r.outbound_type)).length;
        const otherCount = todayTotal - salesCount - returnCount;
        const todayQty = todayRows.reduce((sum, r) => {
          const q = typeof r.outbound_qty === "number" ? r.outbound_qty : Number(r.outbound_qty) || 0;
          return sum + q;
        }, 0);

        setKpi({
          todayTotal, todayWaiting, todayCompleted,
          salesCount, returnCount, otherCount,
          todayQty, todayQtyUnit: "EA",
        });

        // --- Recent 5 ---
        const sorted = [...allRows].sort((a, b) => {
          const da = new Date(a.created_date || "").getTime() || 0;
          const db = new Date(b.created_date || "").getTime() || 0;
          return db - da;
        });

        const unique = sorted.slice(0, 5);

        const mapped: RecentOutboundItem[] = unique.map((row, idx) => {
          const dateObj = row.created_date ? new Date(row.created_date) : null;
          const time = dateObj
            ? `${String(dateObj.getHours()).padStart(2, "0")}:${String(dateObj.getMinutes()).padStart(2, "0")}`
            : "--:--";
          const qtyNum = typeof row.outbound_qty === "number" ? row.outbound_qty : Number(row.outbound_qty) || 0;
          const statusInfo = getStatusStyle(row.outbound_status);

          return {
            id: String(row.id || idx),
            time,
            type: shortenType(row.outbound_type),
            itemName: row.item_name || row.item_code || row.outbound_number || "-",
            qty: `${qtyNum.toLocaleString()} ${row.unit || "EA"}`,
            customer: row.customer_name || "-",
            statusColor: statusInfo.color,
            statusLabel: statusInfo.label,
          };
        });

        setRecentItems(mapped);
      } catch {
        // keep empty
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

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

  return (
    <div className="flex flex-col gap-5">
      {/* ===== Back + Title ===== */}
      <div className="flex items-center gap-3">
        <button
          onClick={() => router.push("/pop/home")}
          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 transition-transform duration-400"
          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={loading ? "-" : kpi.todayTotal.toLocaleString()} label="금일 출고" color="text-green-600" />
                <KpiCell value={loading ? "-" : kpi.todayWaiting.toLocaleString()} label="대기" color="text-amber-600" />
                <KpiCell value={loading ? "-" : kpi.todayCompleted.toLocaleString()} label="완료" color="text-blue-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={loading ? "-" : kpi.salesCount.toLocaleString()} label="판매출고" color="text-green-600" />
                <KpiCell value={loading ? "-" : kpi.returnCount.toLocaleString()} label="반품출고" color="text-amber-600" />
                <KpiCell value={loading ? "-" : kpi.otherCount.toLocaleString()} label="기타출고" color="text-gray-600" />
              </div>
            </div>
          </div>
        </div>
        {/* Dots */}
        <div className="flex justify-center gap-2 mt-3">
          {[0, 1].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 ? "#22c55e" : "#D1D5DB",
              }}
              aria-label={`KPI slide ${idx + 1}`}
            />
          ))}
        </div>
      </div>

      {/* ===== External Outbound ===== */}
      <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">
          {EXTERNAL_ITEMS.map((item) => (
            <MenuIcon key={item.id} item={item} onClick={handleMenuClick} />
          ))}
        </div>
      </section>

      {/* ===== Internal Outbound ===== */}
      <section>
        <div className="flex items-center gap-2 mb-3">
          <div className="w-1 h-5 rounded-full bg-emerald-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 Outbound ===== */}
      <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">
            {loading ? (
              <div className="flex flex-col gap-3 py-2">
                {[1, 2, 3].map((i) => (
                  <div key={i} className="flex items-center gap-3 p-3">
                    <div className="w-[44px] h-4 bg-gray-100 rounded animate-pulse" />
                    <div className="flex-1 flex flex-col gap-1.5">
                      <div className="h-4 bg-gray-100 rounded w-3/4 animate-pulse" />
                      <div className="h-3 bg-gray-50 rounded w-1/2 animate-pulse" />
                    </div>
                  </div>
                ))}
              </div>
            ) : recentItems.length === 0 ? (
              <div className="text-center py-8 text-sm text-gray-400">
                최근 출고 내역이 없습니다
              </div>
            ) : (
              recentItems.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.customer} | {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: OutboundMenuItem; onClick: (item: OutboundMenuItem) => 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>
  );
}
