'use client';

/**
 * 작업일지 모달 (독립형)
 *
 * workOrderId만 전달하면 WorkOrder를 로드하고 공정별 작업일지를 표시.
 * QMS 등 외부에서 재사용 가능.
 */

import { useState, useEffect } from 'react';
import { Loader2 } from 'lucide-react';
import { DocumentViewer } from '@/components/document-system';
import { getWorkOrderById } from '../actions';
import type { WorkOrder, ProcessType } from '../types';
import { ScreenWorkLogContent } from './ScreenWorkLogContent';
import { SlatWorkLogContent } from './SlatWorkLogContent';
import { BendingWorkLogContent } from './BendingWorkLogContent';

const PROCESS_LABELS: Record<string, string> = {
  screen: '스크린',
  slat: '슬랫',
  bending: '절곡',
};

interface WorkLogModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  workOrderId: string | null;
  processType?: ProcessType;
}

export function WorkLogModal({
  open,
  onOpenChange,
  workOrderId,
  processType = 'screen',
}: WorkLogModalProps) {
  const [order, setOrder] = useState<WorkOrder | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (open && workOrderId) {
      setIsLoading(true);
      setError(null);
      getWorkOrderById(workOrderId)
        .then((result) => {
          if (result.success && result.data) {
            setOrder(result.data);
          } else {
            setError(result.error || '데이터를 불러올 수 없습니다.');
          }
        })
        .catch(() => setError('서버 오류가 발생했습니다.'))
        .finally(() => setIsLoading(false));
    } else if (!open) {
      setOrder(null);
      setError(null);
    }
  }, [open, workOrderId]);

  if (!workOrderId) return null;

  const processLabel = PROCESS_LABELS[processType] || '스크린';

  const renderContent = () => {
    if (!order) return null;
    switch (processType) {
      case 'slat':
        return <SlatWorkLogContent data={order} />;
      case 'bending':
        return <BendingWorkLogContent data={order} />;
      default:
        return <ScreenWorkLogContent data={order} />;
    }
  };

  return (
    <DocumentViewer
      title="작업일지"
      subtitle={`${processLabel} 생산부서`}
      preset="inspection"
      open={open}
      onOpenChange={onOpenChange}
    >
      {isLoading ? (
        <div className="flex items-center justify-center h-64 bg-white">
          <Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
        </div>
      ) : error || !order ? (
        <div className="flex flex-col items-center justify-center h-64 gap-4 bg-white">
          <p className="text-muted-foreground">{error || '데이터를 불러올 수 없습니다.'}</p>
        </div>
      ) : (
        renderContent()
      )}
    </DocumentViewer>
  );
}