/**
 * 검사기준 상세보기
 * 문서 미리보기 및 출력 기능 포함
 */

import { useState } from "react";
import { Button } from "./ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Badge } from "./ui/badge";
import { ArrowLeft, Edit, FileText, Printer } from "lucide-react";
import type { InspectionStandard } from "./contexts/DataContext";
import { InspectionStandardDocument } from "./InspectionStandardDocument";

interface InspectionStandardViewProps {
  standard: InspectionStandard;
  onBack: () => void;
  onEdit: () => void;
}

export function InspectionStandardView({ standard, onBack, onEdit }: InspectionStandardViewProps) {
  const [showDocument, setShowDocument] = useState(false);

  const inspectionTypeLabel = 
    standard.inspectionType === 'incoming' ? '수입검사' :
    standard.inspectionType === 'process' ? '중간검사' : '제품검사';

  const handlePrint = () => {
    window.print();
  };

  if (showDocument) {
    return (
      <div className="space-y-4">
        <div className="flex items-center justify-between print:hidden">
          <Button variant="outline" onClick={() => setShowDocument(false)}>
            <ArrowLeft className="h-4 w-4 mr-2" />
            상세정보로 돌아가기
          </Button>
          <Button onClick={handlePrint}>
            <Printer className="h-4 w-4 mr-2" />
            인쇄
          </Button>
        </div>
        <InspectionStandardDocument standard={standard} />
      </div>
    );
  }

  return (
    <div className="space-y-6 p-6">
      {/* 헤더 */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold">{standard.inspectionName}</h2>
          <p className="text-muted-foreground">검사기준 상세 정보</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={onBack}>
            <ArrowLeft className="h-4 w-4 mr-2" />
            목록으로
          </Button>
          <Button variant="outline" onClick={() => setShowDocument(true)}>
            <FileText className="h-4 w-4 mr-2" />
            문서 미리보기
          </Button>
          {!standard.isFinal && (
            <Button onClick={onEdit}>
              <Edit className="h-4 w-4 mr-2" />
              수정
            </Button>
          )}
        </div>
      </div>

      {/* 기본 정보 */}
      <Card>
        <CardHeader>
          <CardTitle>기본 정보</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <div className="text-sm text-muted-foreground">기준번호</div>
            <div className="font-mono">{standard.standardNumber}</div>
          </div>
          <div>
            <div className="text-sm text-muted-foreground">검사유형</div>
            <Badge className={
              standard.inspectionType === 'incoming' ? 'bg-blue-500' :
              standard.inspectionType === 'process' ? 'bg-orange-500' : 'bg-green-500'
            }>
              {inspectionTypeLabel}
            </Badge>
          </div>
          <div>
            <div className="text-sm text-muted-foreground">검사명칭</div>
            <div>{standard.inspectionName}</div>
          </div>
          <div>
            <div className="text-sm text-muted-foreground">상태</div>
            <Badge variant={standard.status === 'active' ? 'default' : 'secondary'}>
              {standard.status === 'active' ? '사용중' : '미사용'}
            </Badge>
          </div>
          {standard.itemCode && (
            <div>
              <div className="text-sm text-muted-foreground">품목코드</div>
              <div className="font-mono">{standard.itemCode}</div>
            </div>
          )}
          {standard.itemName && (
            <div>
              <div className="text-sm text-muted-foreground">품목명</div>
              <div>{standard.itemName}</div>
            </div>
          )}
          <div>
            <div className="text-sm text-muted-foreground">등록일</div>
            <div>{new Date(standard.createdAt).toLocaleString()}</div>
          </div>
          <div>
            <div className="text-sm text-muted-foreground">등록자</div>
            <div>{standard.createdBy}</div>
          </div>
          {standard.description && (
            <div className="col-span-2">
              <div className="text-sm text-muted-foreground">설명</div>
              <div className="mt-1">{standard.description}</div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 버전 정보 */}
      <Card>
        <CardHeader>
          <CardTitle>버전 정보</CardTitle>
        </CardHeader>
        <CardContent className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <div className="text-sm text-muted-foreground">현재 차수</div>
            <div>{standard.currentRevision}차</div>
          </div>
          <div>
            <div className="text-sm text-muted-foreground">확정 여부</div>
            <Badge variant={standard.isFinal ? 'default' : 'outline'}>
              {standard.isFinal ? '확정' : '미확정'}
            </Badge>
          </div>
          {standard.isFinal && standard.finalizedDate && (
            <div>
              <div className="text-sm text-muted-foreground">확정일</div>
              <div>{new Date(standard.finalizedDate).toLocaleString()}</div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 문서 템플릿 정보 */}
      <Card>
        <CardHeader>
          <CardTitle>문서 템플릿 구성</CardTitle>
        </CardHeader>
        <CardContent className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <div className="text-sm text-muted-foreground mb-2">문서 제목</div>
              <div>{standard.documentTemplate.title}</div>
            </div>
            <div>
              <div className="text-sm text-muted-foreground mb-2">회사명</div>
              <div>{standard.documentTemplate.companyName}</div>
            </div>
          </div>

          <div>
            <div className="text-sm text-muted-foreground mb-2">결재라인</div>
            <div className="flex gap-4">
              {standard.documentTemplate.approvalLines.map((line) => (
                <div key={line.id} className="flex items-center gap-2">
                  <Badge variant="outline">{line.position}</Badge>
                  <span>{line.name || '미지정'}</span>
                  {line.department && (
                    <span className="text-sm text-muted-foreground">({line.department})</span>
                  )}
                </div>
              ))}
            </div>
          </div>

          <div>
            <div className="text-sm text-muted-foreground mb-2">
              기본정보 필드 ({standard.documentTemplate.basicInfoFields.length}개)
            </div>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-2">
              {standard.documentTemplate.basicInfoFields.map((field) => (
                <div key={field.id} className="text-sm">
                  • {field.label}
                  {field.required && <span className="text-red-500">*</span>}
                </div>
              ))}
            </div>
          </div>

          <div>
            <div className="text-sm text-muted-foreground mb-2">
              검사항목 칼럼 ({standard.documentTemplate.inspectionColumns.length}개)
            </div>
            <div className="overflow-x-auto">
              <table className="w-full border">
                <thead>
                  <tr className="bg-muted">
                    {standard.documentTemplate.inspectionColumns.map(col => (
                      <th key={col.id} className="border p-2 text-sm">
                        {col.name}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {standard.documentTemplate.inspectionItems.slice(0, 3).map(item => (
                    <tr key={item.id}>
                      {standard.documentTemplate.inspectionColumns.map(col => (
                        <td key={col.id} className="border p-2 text-sm">
                          {item.values[col.id] || '-'}
                        </td>
                      ))}
                    </tr>
                  ))}
                </tbody>
              </table>
              {standard.documentTemplate.inspectionItems.length > 3 && (
                <p className="text-sm text-muted-foreground mt-2">
                  외 {standard.documentTemplate.inspectionItems.length - 3}개 항목
                </p>
              )}
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 수정 이력 */}
      {standard.revisions && standard.revisions.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>수정 이력</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {standard.revisions.map((revision) => (
                <div key={revision.revisionNumber} className="border-l-2 border-primary pl-4">
                  <div className="flex items-center gap-2">
                    <Badge>{revision.revisionNumber}차 수정</Badge>
                    <span className="text-sm text-muted-foreground">
                      {new Date(revision.revisionDate).toLocaleString()}
                    </span>
                    <span className="text-sm">by {revision.revisionBy}</span>
                  </div>
                  {revision.revisionReason && (
                    <p className="text-sm text-muted-foreground mt-1">
                      사유: {revision.revisionReason}
                    </p>
                  )}
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
