"use client";

/**
 * 수주 문서 모달 컴포넌트
 * - 계약서, 거래명세서, 발주서를 모달 형태로 표시
 * - DocumentViewer 시스템 사용
 */

import { useState, useEffect } from "react";
import { DocumentViewer } from "@/components/document-system";
import { ContractDocument } from "./ContractDocument";
import { TransactionDocument } from "./TransactionDocument";
import { PurchaseOrderDocument } from "./PurchaseOrderDocument";
import { SalesOrderDocument } from "./SalesOrderDocument";
import { OrderItem, getOrderDocumentDetail } from "../actions";
import { getCompanyInfo } from "@/components/settings/CompanyInfoManagement/actions";

// 문서 타입
export type OrderDocumentType = "contract" | "transaction" | "purchaseOrder" | "salesOrder";

// 제품 정보 타입 (견적의 calculation_inputs에서 추출)
export interface ProductInfo {
  productName: string;
  productCategory?: string;
  openWidth?: string;
  openHeight?: string;
  quantity: number;
  floor?: string;
  code?: string;
}

// 문서 데이터 인터페이스
export interface OrderDocumentData {
  lotNumber: string;
  orderDate: string;
  client: string;
  siteName?: string;
  manager?: string;
  managerContact?: string;
  deliveryRequestDate?: string;
  expectedShipDate?: string;
  deliveryMethod?: string;
  address?: string;
  items?: OrderItem[];
  products?: ProductInfo[];
  subtotal?: number;
  discountRate?: number;
  totalAmount?: number;
  remarks?: string;
  // 수주서 전용 필드
  documentNumber?: string;
  certificationNumber?: string;
  recipientName?: string;
  recipientContact?: string;
  shutterCount?: number;
  fee?: number;
  orderId?: number;
}

interface OrderDocumentModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  documentType: OrderDocumentType;
  data: OrderDocumentData;
}

// 회사 정보 타입
interface CompanyInfo {
  companyName: string;
  representativeName: string;
  businessNumber: string;
  managerPhone: string;
  address: string;
}

export function OrderDocumentModal({
  open,
  onOpenChange,
  documentType,
  data,
}: OrderDocumentModalProps) {
  const [companyInfo, setCompanyInfo] = useState<CompanyInfo | null>(null);
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const [orderDetail, setOrderDetail] = useState<Record<string, any> | null>(null);

  // 모달이 열릴 때 회사 정보 조회
  useEffect(() => {
    if (open && !companyInfo) {
      getCompanyInfo().then((result) => {
        if (result.success && result.data) {
          setCompanyInfo({
            companyName: result.data.companyName,
            representativeName: result.data.representativeName,
            businessNumber: result.data.businessNumber,
            managerPhone: result.data.managerPhone,
            address: result.data.address,
          });
        }
      });
    }
  }, [open, companyInfo]);

  // 수주서일 때 BOM 상세 데이터 로드
  useEffect(() => {
    if (!open || documentType !== 'salesOrder' || !data.orderId) {
      setOrderDetail(null);
      return;
    }
    getOrderDocumentDetail(String(data.orderId)).then((result) => {
      if (result.success && result.data) {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const raw = result.data as Record<string, any>;
        setOrderDetail(raw?.data ?? raw);
      }
    });
  }, [open, documentType, data.orderId]);

  const getDocumentTitle = () => {
    switch (documentType) {
      case "contract":
        return "계약서";
      case "transaction":
        return "거래명세서";
      case "purchaseOrder":
        return "발주서";
      case "salesOrder":
        return "수주서";
      default:
        return "문서";
    }
  };

  const renderDocument = () => {
    switch (documentType) {
      case "contract":
        return (
          <ContractDocument
            orderNumber={data.lotNumber}
            orderDate={data.orderDate}
            client={data.client}
            siteName={data.siteName}
            clientManager={data.manager}
            clientContact={data.managerContact}
            companyName={companyInfo?.companyName}
            companyCeo={companyInfo?.representativeName}
            companyBusinessNumber={companyInfo?.businessNumber}
            companyContact={companyInfo?.managerPhone}
            companyAddress={companyInfo?.address}
            items={data.items || []}
            products={data.products}
            subtotal={data.subtotal || 0}
            discountRate={data.discountRate || 0}
            totalAmount={data.totalAmount || 0}
            remarks={data.remarks}
          />
        );
      case "transaction":
        return (
          <TransactionDocument
            orderNumber={data.lotNumber}
            orderDate={data.orderDate}
            client={data.client}
            items={data.items || []}
            subtotal={data.subtotal || 0}
            discountRate={data.discountRate || 0}
            totalAmount={data.totalAmount || 0}
          />
        );
      case "purchaseOrder":
        return (
          <PurchaseOrderDocument
            orderNumber={data.lotNumber}
            client={data.client}
            siteName={data.siteName || "-"}
            manager={data.manager}
            managerContact={data.managerContact}
            deliveryRequestDate={data.deliveryRequestDate || "-"}
            expectedShipDate={data.expectedShipDate}
            deliveryMethod={data.deliveryMethod}
            address={data.address || "-"}
            items={data.items || []}
            remarks={data.remarks}
          />
        );
      case "salesOrder":
        return (
          <SalesOrderDocument
            documentNumber={data.documentNumber}
            orderNumber={data.lotNumber}
            certificationNumber={data.certificationNumber}
            orderDate={data.orderDate}
            client={data.client}
            siteName={data.siteName}
            manager={data.manager}
            managerContact={data.managerContact}
            deliveryRequestDate={data.deliveryRequestDate}
            expectedShipDate={data.expectedShipDate}
            deliveryMethod={data.deliveryMethod}
            address={data.address}
            recipientName={data.recipientName}
            recipientContact={data.recipientContact}
            shutterCount={data.shutterCount}
            fee={data.fee}
            items={data.items || []}
            products={data.products}
            remarks={data.remarks}
            productRows={orderDetail?.products || []}
            motorsLeft={orderDetail?.motors?.left || []}
            motorsRight={orderDetail?.motors?.right || []}
            bendingParts={orderDetail?.bending_parts || []}
            bendingImages={orderDetail?.bending_images}
            subsidiaryParts={orderDetail?.subsidiary_parts || []}
            categoryCode={orderDetail?.category_code}
          />
        );
      default:
        return null;
    }
  };

  return (
    <DocumentViewer
      title={getDocumentTitle()}
      subtitle={`${getDocumentTitle()} 상세`}
      preset="readonly"
      open={open}
      onOpenChange={onOpenChange}
    >
      {renderDocument()}
    </DocumentViewer>
  );
}