"use client";

import React, { useState, useCallback, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import {
  Settings,
  GitBranch,
  ClipboardList,
  ChevronRight,
  Factory,
  Keyboard,
  Plus,
  Pencil,
  Trash2,
  List,
  Settings2,
} from "lucide-react";
import { ProcessMasterTab } from "./ProcessMasterTab";
import { ItemRoutingTab } from "./ItemRoutingTab";
import { ProcessWorkStandardTab } from "./ProcessWorkStandardTab";
import { useTableSettings } from "@/hooks/useTableSettings";
import { TableSettingsModal } from "@/components/common/TableSettingsModal";

const GRID_COLUMNS = [
  { key: "process_code", label: "공정코드" },
  { key: "process_name", label: "공정명" },
  { key: "process_type", label: "공정유형" },
  { key: "standard_time", label: "표준시간(분)" },
  { key: "worker_count", label: "작업인원" },
  { key: "use_yn", label: "사용여부" },
];

const TAB_META = [
  {
    value: "process",
    label: "공정 마스터",
    shortLabel: "공정",
    description: "공정코드/유형/표준시간/사용설비 관리",
    detailDesc: "공정코드, 공정유형, 표준시간을 등록하고 사용 설비를 매핑합니다.",
    icon: Settings,
    color: "text-blue-500",
    badgeColor: "bg-blue-50 text-blue-700 ring-blue-600/20",
    shortcut: "1",
    actions: ["공정 등록", "공정 수정", "공정 삭제", "설비 연결"],
  },
  {
    value: "routing",
    label: "품목별 라우팅",
    shortLabel: "라우팅",
    description: "품목 라우팅 버전 및 공정 순서 관리",
    detailDesc: "품목별 생산 라우팅 버전을 관리하고 공정 순서 및 소요시간을 설정합니다.",
    icon: GitBranch,
    color: "text-emerald-500",
    badgeColor: "bg-emerald-50 text-emerald-700 ring-emerald-600/20",
    shortcut: "2",
    actions: ["버전 생성", "공정 순서 설정", "품목 등록", "품목 해제"],
  },
  {
    value: "workstandard",
    label: "공정 작업기준",
    shortLabel: "작업기준",
    description: "공정별 작업기준서 및 작업 표준 관리",
    detailDesc: "공정별 작업기준서를 등록하고 작업 표준을 문서화하여 품질을 관리합니다.",
    icon: ClipboardList,
    color: "text-violet-500",
    badgeColor: "bg-violet-50 text-violet-700 ring-violet-600/20",
    shortcut: "3",
    actions: ["기준서 등록", "기준서 수정", "기준서 삭제", "작업 표준 관리"],
  },
] as const;

type TabValue = (typeof TAB_META)[number]["value"];

const ACTION_ICONS = [Plus, Pencil, Trash2, List] as const;

export default function ProcessInfoPage() {
  const ts = useTableSettings("c16-process-info", "process_mst", GRID_COLUMNS);
  const [activeTab, setActiveTab] = useState<TabValue>("process");
  const [showShortcutHint, setShowShortcutHint] = useState(false);

  const activeMeta = TAB_META.find((t) => t.value === activeTab)!;

  const handleTabChange = useCallback((value: string) => {
    setActiveTab(value as TabValue);
  }, []);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (!e.altKey) return;
      const tabByShortcut = TAB_META.find((t) => t.shortcut === e.key);
      if (tabByShortcut) {
        e.preventDefault();
        setActiveTab(tabByShortcut.value);
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, []);

  return (
    <div className="flex h-[calc(100vh-4rem)] flex-col bg-muted/30">
      {/* 페이지 헤더 */}
      <div className="shrink-0 border-b bg-background px-6 py-3">
        <nav
          className="mb-1 flex items-center gap-1 text-xs text-muted-foreground"
          aria-label="breadcrumb"
        >
          <Factory className="h-3 w-3" />
          <span>생산관리</span>
          <ChevronRight className="h-3 w-3 opacity-50" />
          <span className="font-medium text-foreground">공정정보관리</span>
        </nav>
        <div className="flex items-center justify-between">
          <div className="flex items-baseline gap-2">
            <h1 className="text-base font-semibold text-foreground">공정정보관리</h1>
            <span className="text-xs text-muted-foreground">{activeMeta.description}</span>
          </div>
          <div className="flex items-center gap-1">
            <Button variant="ghost" size="sm" onClick={() => ts.setOpen(true)} title="테이블 설정">
              <Settings2 className="h-3.5 w-3.5" />
            </Button>
            <button
              type="button"
              className="flex items-center gap-1 rounded px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
              onClick={() => setShowShortcutHint((v) => !v)}
              aria-label="키보드 단축키 보기"
            >
              <Keyboard className="h-3 w-3" />
              <span>단축키</span>
            </button>
          </div>
        </div>
        {showShortcutHint && (
          <div className="mt-2 flex items-center gap-3 rounded-md bg-muted px-3 py-2 text-xs text-muted-foreground">
            <span className="font-medium text-foreground">탭 전환:</span>
            {TAB_META.map((t) => (
              <span key={t.value} className="flex items-center gap-1">
                <kbd className="rounded border border-border bg-background px-1.5 py-0.5 font-mono text-[10px]">
                  Alt+{t.shortcut}
                </kbd>
                <span>{t.shortLabel}</span>
              </span>
            ))}
          </div>
        )}
      </div>

      <Tabs
        value={activeTab}
        onValueChange={handleTabChange}
        className="flex min-h-0 flex-1 flex-col"
      >
        {/* 탭 네비게이션 */}
        <div className="shrink-0 border-b bg-background px-4">
          <TabsList className="h-12 bg-transparent gap-1">
            {TAB_META.map(({ value, label, icon: Icon, shortcut }) => (
              <TabsTrigger
                key={value}
                value={value}
                className="data-[state=active]:border-b-2 data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none rounded-none px-4 gap-1.5"
                aria-label={`${label} (Alt+${shortcut})`}
              >
                <Icon className="h-4 w-4" />
                {label}
              </TabsTrigger>
            ))}
          </TabsList>
        </div>

        {/* 탭 설명 배너 */}
        <div className="shrink-0 border-b bg-background/60 px-6 py-2">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <span
                className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ring-1 ring-inset ${activeMeta.badgeColor}`}
              >
                {activeMeta.shortLabel}
              </span>
              <span className="text-xs text-muted-foreground">{activeMeta.detailDesc}</span>
            </div>
            <div className="hidden items-center gap-2 sm:flex">
              {activeMeta.actions.map((action, i) => {
                const ActionIcon = ACTION_ICONS[i % ACTION_ICONS.length];
                return (
                  <span
                    key={action}
                    className="flex items-center gap-1 text-xs text-muted-foreground/70"
                  >
                    <ActionIcon className="h-3 w-3" />
                    {action}
                  </span>
                );
              })}
            </div>
          </div>
        </div>

        {/* 탭 컨텐츠 */}
        <TabsContent value="process" className="min-h-0 flex-1 overflow-hidden mt-0">
          <ProcessMasterTab />
        </TabsContent>

        <TabsContent value="routing" className="min-h-0 flex-1 overflow-hidden mt-0">
          <ItemRoutingTab />
        </TabsContent>

        <TabsContent value="workstandard" className="min-h-0 flex-1 overflow-hidden mt-0">
          <ProcessWorkStandardTab />
        </TabsContent>
      </Tabs>

      <TableSettingsModal
        open={ts.open}
        onOpenChange={ts.setOpen}
        tableName={ts.tableName}
        settingsId={ts.settingsId}
        defaultVisibleKeys={ts.defaultVisibleKeys}
        onSave={ts.applySettings}
      />
    </div>
  );
}
