"use client";

import React, { useState } from "react";
import { Plus, Pencil, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import { WorkItem, WorkItemDetail, DetailTypeDefinition } from "../types";
import { DetailFormModal } from "./DetailFormModal";

interface WorkItemDetailListProps {
  workItem: WorkItem | null;
  details: WorkItemDetail[];
  detailTypes: DetailTypeDefinition[];
  readonly?: boolean;
  selectedItemCode?: string;
  onCreateDetail: (data: Partial<WorkItemDetail>) => void;
  onUpdateDetail: (id: string, data: Partial<WorkItemDetail>) => void;
  onDeleteDetail: (id: string) => void;
}

export function WorkItemDetailList({
  workItem,
  details,
  detailTypes,
  readonly,
  selectedItemCode,
  onCreateDetail,
  onUpdateDetail,
  onDeleteDetail,
}: WorkItemDetailListProps) {
  const [modalOpen, setModalOpen] = useState(false);
  const [modalMode, setModalMode] = useState<"add" | "edit">("add");
  const [editTarget, setEditTarget] = useState<WorkItemDetail | null>(null);

  if (!workItem) {
    return (
      <div className="flex h-full flex-col items-center justify-center text-center">
        <p className="text-sm text-muted-foreground">
          왼쪽에서 항목을 선택하세요
        </p>
      </div>
    );
  }

  const getTypeLabel = (value?: string) =>
    detailTypes.find((t) => t.value === value)?.label || value || "-";

  const handleOpenAdd = () => {
    setModalMode("add");
    setEditTarget(null);
    setModalOpen(true);
  };

  const handleOpenEdit = (detail: WorkItemDetail) => {
    setModalMode("edit");
    setEditTarget(detail);
    setModalOpen(true);
  };

  const handleSubmit = (data: Partial<WorkItemDetail>) => {
    if (modalMode === "add") {
      onCreateDetail({ ...data, sort_order: details.length + 1 });
    } else if (editTarget) {
      onUpdateDetail(editTarget.id, data);
    }
  };

  const getContentSummary = (detail: WorkItemDetail): string => {
    const type = detail.detail_type;
    if (type === "inspection") {
      if (detail.process_inspection_apply === "apply") return "품목별 검사정보 (자동 연동)";
      const parts = [detail.content];
      if (detail.inspection_method) parts.push(`[${detail.inspection_method}]`);
      if (detail.base_value) {
        parts.push(`(기준: ${detail.base_value}${detail.tolerance ? ` ±${detail.tolerance}` : ""} ${detail.unit || ""})`);
      }
      return parts.join(" ");
    }
    if (type === "procedure" && detail.duration_minutes) {
      return `${detail.content} (${detail.duration_minutes}분)`;
    }
    if (type === "input" && detail.input_type) {
      const typeMap: Record<string, string> = {
        text: "텍스트",
        number: "숫자",
        date: "날짜",
        textarea: "장문",
      };
      return `${detail.content} [${typeMap[detail.input_type] || detail.input_type}]`;
    }
    if (type === "lookup") return "품목 등록 문서 (자동 연동)";
    if (type === "equip_inspection") {
      return detail.equip_inspection_apply === "apply"
        ? "설비 점검항목 (설비정보 연동)"
        : detail.content || "설비점검";
    }
    if (type === "equip_condition") {
      const parts = [detail.content];
      if (detail.condition_base_value) {
        parts.push(`(기준: ${detail.condition_base_value}${detail.condition_tolerance ? ` ±${detail.condition_tolerance}` : ""} ${detail.condition_unit || ""})`);
      }
      return parts.join(" ");
    }
    if (type === "production_result") return "작업수량 / 불량수량 / 양품수량";
    if (type === "material_input") return "BOM 구성 자재 (자동 연동)";
    return detail.content || "-";
  };

  return (
    <div className="flex h-full flex-col">
      {/* 헤더 */}
      <div className="flex items-center justify-between border-b px-4 py-2">
        <div className="flex items-center gap-2">
          <span className="text-sm font-semibold">{workItem.title}</span>
          <Badge variant="secondary" className="text-[10px]">
            {details.length}개
          </Badge>
        </div>
        {!readonly && (
          <Button
            variant="outline"
            size="sm"
            className="h-7 gap-1 text-xs"
            onClick={handleOpenAdd}
          >
            <Plus className="h-3 w-3" />
            상세 추가
          </Button>
        )}
      </div>

      {/* 테이블 */}
      <div className="flex-1 overflow-y-auto">
        <table className="w-full text-xs">
          <thead className="sticky top-0 bg-muted/50">
            <tr className="border-b">
              <th className="w-12 px-2 py-2 text-center font-medium text-muted-foreground">
                순서
              </th>
              <th className="w-20 px-2 py-2 text-left font-medium text-muted-foreground">
                유형
              </th>
              <th className="px-2 py-2 text-left font-medium text-muted-foreground">
                내용
              </th>
              <th className="w-14 px-2 py-2 text-center font-medium text-muted-foreground">
                필수
              </th>
              {!readonly && (
                <th className="w-16 px-2 py-2 text-center font-medium text-muted-foreground">
                  관리
                </th>
              )}
            </tr>
          </thead>
          <tbody>
            {details.map((detail, idx) => (
              <tr
                key={detail.id}
                className="border-b transition-colors hover:bg-muted/30"
              >
                <td className="px-2 py-1.5 text-center text-muted-foreground">
                  {idx + 1}
                </td>
                <td className="px-2 py-1.5">
                  <Badge variant="outline" className="text-[10px] font-normal">
                    {getTypeLabel(detail.detail_type)}
                  </Badge>
                </td>
                <td className="px-2 py-1.5">{getContentSummary(detail)}</td>
                <td className="px-2 py-1.5 text-center">
                  <Badge
                    variant={detail.is_required === "Y" ? "default" : "secondary"}
                    className="text-[10px] font-normal"
                  >
                    {detail.is_required === "Y" ? "필수" : "선택"}
                  </Badge>
                </td>
                {!readonly && (
                  <td className="px-2 py-1.5 text-center">
                    <div className="flex justify-center gap-0.5">
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-6 w-6"
                        onClick={() => handleOpenEdit(detail)}
                      >
                        <Pencil className="h-3 w-3" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-6 w-6 text-destructive hover:text-destructive"
                        onClick={() => onDeleteDetail(detail.id)}
                      >
                        <Trash2 className="h-3 w-3" />
                      </Button>
                    </div>
                  </td>
                )}
              </tr>
            ))}
          </tbody>
        </table>

        {details.length === 0 && (
          <div className="flex flex-col items-center justify-center py-8 text-center">
            <p className="text-xs text-muted-foreground">
              상세 항목이 없습니다. &quot;상세 추가&quot; 버튼을 클릭하여 추가하세요.
            </p>
          </div>
        )}
      </div>

      {/* 추가/수정 모달 */}
      <DetailFormModal
        open={modalOpen}
        onClose={() => setModalOpen(false)}
        onSubmit={handleSubmit}
        detailTypes={detailTypes}
        editData={editTarget}
        mode={modalMode}
        selectedItemCode={selectedItemCode}
      />
    </div>
  );
}
