/**
 * 검사 문서 템플릿 편집기
 * ResponsiveFormTemplate 기반으로 페이지 형태 구현
 * 발주서 톤앤매너와 결제라인 구성 기준
 */

import { useState } from "react";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Plus, Trash2, FileText, FileCheck, Settings, User, ListChecks, FileSpreadsheet, Info, Eye, Download, Mail, FileOutput, MessageCircle, Printer, X } from "lucide-react";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "./ui/dialog";
import type { InspectionStandard } from "./contexts/DataContext";
import {
  ResponsiveFormTemplate,
  FormSection,
  FormFieldGrid,
  FormField
} from "./templates/ResponsiveFormTemplate";
import { InspectionDocumentPreview } from "./InspectionDocumentPreview";

interface InspectionDocumentEditorProps {
  template: InspectionStandard['documentTemplate'];
  onSave: (template: InspectionStandard['documentTemplate']) => void;
  onBack: () => void;
  inspectionType: string;
}

export function InspectionDocumentEditor({ template, onSave, onBack, inspectionType }: InspectionDocumentEditorProps) {
  const [editedTemplate, setEditedTemplate] = useState(template);
  const [showPreview, setShowPreview] = useState(false);

  // 결재라인 추가
  const handleAddApprovalLine = () => {
    const newLine = {
      id: Date.now().toString(),
      position: '',
      name: '',
      department: ''
    };
    setEditedTemplate(prev => {
      const updated = {
        ...prev,
        approvalLines: [...prev.approvalLines, newLine]
      };
      console.log('✅ 결재라인 추가됨:', updated.approvalLines);
      return updated;
    });
  };

  // 결재라인 삭제
  const handleRemoveApprovalLine = (id: string) => {
    setEditedTemplate(prev => {
      const updated = {
        ...prev,
        approvalLines: prev.approvalLines.filter(line => line.id !== id)
      };
      console.log('🗑️ 결재라인 삭제됨:', updated.approvalLines);
      return updated;
    });
  };

  // 결재라인 수정
  const handleUpdateApprovalLine = (id: string, field: string, value: string) => {
    setEditedTemplate(prev => {
      const updated = {
        ...prev,
        approvalLines: prev.approvalLines.map(line =>
          line.id === id ? { ...line, [field]: value } : line
        )
      };
      console.log('✏️ 결재라인 수정됨:', updated.approvalLines);
      return updated;
    });
  };

  // 기본정보 필드 추가
  const handleAddBasicField = () => {
    const newField = {
      id: Date.now().toString(),
      label: '',
      value: '',
      type: 'text' as const,
      required: false
    };
    setEditedTemplate(prev => ({
      ...prev,
      basicInfoFields: [...prev.basicInfoFields, newField]
    }));
  };

  // 기본정보 필드 삭제
  const handleRemoveBasicField = (id: string) => {
    setEditedTemplate(prev => ({
      ...prev,
      basicInfoFields: prev.basicInfoFields.filter(field => field.id !== id)
    }));
  };

  // 기본정보 필드 수정
  const handleUpdateBasicField = (id: string, field: string, value: any) => {
    setEditedTemplate(prev => ({
      ...prev,
      basicInfoFields: prev.basicInfoFields.map(f =>
        f.id === id ? { ...f, [field]: value } : f
      )
    }));
  };

  // 검사항목 칼럼 추가
  const handleAddColumn = () => {
    const newColumn = {
      id: Date.now().toString(),
      name: '',
      type: 'text' as const,
      width: '100px'
    };
    setEditedTemplate(prev => ({
      ...prev,
      inspectionColumns: [...prev.inspectionColumns, newColumn]
    }));
  };

  // 검사항목 칼럼 삭제
  const handleRemoveColumn = (id: string) => {
    setEditedTemplate(prev => ({
      ...prev,
      inspectionColumns: prev.inspectionColumns.filter(col => col.id !== id)
    }));
  };

  // 검사항목 칼럼 수정
  const handleUpdateColumn = (id: string, field: string, value: any) => {
    setEditedTemplate(prev => ({
      ...prev,
      inspectionColumns: prev.inspectionColumns.map(col =>
        col.id === id ? { ...col, [field]: value } : col
      )
    }));
  };

  // 검사항목 추가
  const handleAddInspectionItem = () => {
    const newNo = editedTemplate.inspectionItems.length + 1;
    const values: Record<string, any> = {};
    editedTemplate.inspectionColumns.forEach(col => {
      values[col.id] = col.id === editedTemplate.inspectionColumns[0].id ? newNo.toString() : '';
    });

    const newItem = {
      id: Date.now().toString(),
      no: newNo,
      values
    };
    setEditedTemplate(prev => ({
      ...prev,
      inspectionItems: [...prev.inspectionItems, newItem]
    }));
  };

  // 검사항목 삭제
  const handleRemoveInspectionItem = (id: string) => {
    setEditedTemplate(prev => ({
      ...prev,
      inspectionItems: prev.inspectionItems.filter(item => item.id !== id)
        .map((item, idx) => ({
          ...item,
          no: idx + 1,
          values: {
            ...item.values,
            [prev.inspectionColumns[0].id]: (idx + 1).toString()
          }
        }))
    }));
  };

  // 검사항목 값 수정
  const handleUpdateInspectionItem = (id: string, columnId: string, value: string) => {
    setEditedTemplate(prev => ({
      ...prev,
      inspectionItems: prev.inspectionItems.map(item =>
        item.id === id
          ? { ...item, values: { ...item.values, [columnId]: value } }
          : item
      )
    }));
  };

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

  return (
    <>
      <ResponsiveFormTemplate
        title={`${inspectionTypeName} 문서 템플릿 편집`}
        description="검사 성적서 양식을 커스터마이징합니다"
        icon={FileCheck}
        onSave={() => {
          console.log('💾 템플릿 저장 버튼 클릭');
          console.log('💾 저장될 결재라인:', editedTemplate.approvalLines);
          console.log('💾 전체 템플릿:', editedTemplate);
          onSave(editedTemplate);
        }}
        onCancel={onBack}
        saveText="템플릿 저장"
        maxWidth="2xl"
        headerActions={
          <Button
            variant="outline"
            onClick={() => setShowPreview(true)}
            type="button"
          >
            <Eye className="h-4 w-4 mr-2" />
            미리보기
          </Button>
        }
      >
        {/* 문서 기본 정보 */}
        <FormSection 
          title="문서 기본 정보" 
          icon={FileText}
          description="검사 성적서의 기본 정보를 설정합니다"
        >
          <FormFieldGrid columns={2}>
            <FormField label="문서 제목" required>
              <Input
                value={editedTemplate.title}
                onChange={(e) => setEditedTemplate(prev => ({ ...prev, title: e.target.value }))}
                placeholder="예: 수입검사 성적서"
              />
            </FormField>

            <FormField label="회사명" required>
              <Input
                value={editedTemplate.companyName}
                onChange={(e) => setEditedTemplate(prev => ({ ...prev, companyName: e.target.value }))}
                placeholder="경동기업"
              />
            </FormField>

            <FormField label="회사 주소">
              <Input
                value={editedTemplate.companyAddress || ''}
                onChange={(e) => setEditedTemplate(prev => ({ ...prev, companyAddress: e.target.value }))}
                placeholder="회사 주소 입력"
              />
            </FormField>

            <FormField label="회사 연락처">
              <Input
                value={editedTemplate.companyPhone || ''}
                onChange={(e) => setEditedTemplate(prev => ({ ...prev, companyPhone: e.target.value }))}
                placeholder="연락처 입력"
              />
            </FormField>
          </FormFieldGrid>
        </FormSection>

        {/* 결재라인 */}
        <FormSection 
          title="결재라인 설정" 
          icon={User}
          description="문서 승인을 위한 결재라인을 구성합니다 (발주서 톤앤매너 기준)"
        >
          <div className="space-y-3">
            <div className="flex items-center justify-between mb-3">
              <p className="text-sm text-muted-foreground">
                작성/검토/승인 순서로 구성하세요
              </p>
              <Button size="sm" onClick={handleAddApprovalLine} type="button">
                <Plus className="h-4 w-4 mr-2" />
                결재자 추가
              </Button>
            </div>
            
            {editedTemplate.approvalLines.length === 0 ? (
              <div className="text-center py-8 border-2 border-dashed rounded-lg text-muted-foreground">
                결재자를 추가해주세요
              </div>
            ) : (
              <div className="space-y-2">
                {editedTemplate.approvalLines.map((line, index) => (
                  <div key={line.id} className="flex gap-2 items-center p-3 bg-muted/30 rounded-lg">
                    <div className="flex items-center justify-center w-8 h-8 bg-primary/10 text-primary rounded-full text-sm font-medium">
                      {index + 1}
                    </div>
                    <Input
                      placeholder="직책 (작성, 검토, 승인)"
                      value={line.position}
                      onChange={(e) => handleUpdateApprovalLine(line.id, 'position', e.target.value)}
                      className="w-36"
                    />
                    <Input
                      placeholder="이름"
                      value={line.name}
                      onChange={(e) => handleUpdateApprovalLine(line.id, 'name', e.target.value)}
                      className="flex-1"
                    />
                    <Input
                      placeholder="부서"
                      value={line.department || ''}
                      onChange={(e) => handleUpdateApprovalLine(line.id, 'department', e.target.value)}
                      className="flex-1"
                    />
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleRemoveApprovalLine(line.id)}
                      type="button"
                      className="text-red-600 hover:text-red-700 hover:bg-red-50"
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                ))}
              </div>
            )}
          </div>
        </FormSection>

        {/* 기본정보 필드 */}
        <FormSection 
          title="기본정보 필드 구성" 
          icon={ListChecks}
          description="검사 대상의 기본 정보를 입력받을 필드를 설정합니다"
        >
          <div className="space-y-3">
            <div className="flex items-center justify-between mb-3">
              <p className="text-sm text-muted-foreground">
                품명, 규격, 검사일자 등의 필드를 구성하세요
              </p>
              <Button size="sm" onClick={handleAddBasicField} type="button">
                <Plus className="h-4 w-4 mr-2" />
                필드 추가
              </Button>
            </div>
            
            {editedTemplate.basicInfoFields.length === 0 ? (
              <div className="text-center py-8 border-2 border-dashed rounded-lg text-muted-foreground">
                기본정보 필드를 추가해주세요
              </div>
            ) : (
              <div className="space-y-2">
                {editedTemplate.basicInfoFields.map((field, index) => (
                  <div key={field.id} className="flex gap-2 items-center p-2 bg-muted/30 rounded-lg">
                    <div className="flex items-center justify-center w-8 h-8 bg-blue-100 text-blue-700 rounded text-sm font-medium">
                      {index + 1}
                    </div>
                    <Input
                      placeholder="필드명"
                      value={field.label}
                      onChange={(e) => handleUpdateBasicField(field.id, 'label', e.target.value)}
                      className="flex-1"
                    />
                    <Input
                      placeholder="기본값 (선택)"
                      value={field.value || ''}
                      onChange={(e) => handleUpdateBasicField(field.id, 'value', e.target.value)}
                      className="flex-1"
                    />
                    <Select
                      value={field.type}
                      onValueChange={(value) => handleUpdateBasicField(field.id, 'type', value)}
                    >
                      <SelectTrigger className="w-32">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="text">텍스트</SelectItem>
                        <SelectItem value="date">날짜</SelectItem>
                        <SelectItem value="number">숫자</SelectItem>
                      </SelectContent>
                    </Select>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleRemoveBasicField(field.id)}
                      type="button"
                      className="text-red-600 hover:text-red-700 hover:bg-red-50"
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                ))}
              </div>
            )}
          </div>
        </FormSection>

        {/* 검사항목 칼럼 */}
        <FormSection 
          title="검사항목 칼럼 구성" 
          icon={FileSpreadsheet}
          description="검사 결과를 기록할 테이블의 칼럼을 설정합니다"
        >
          <div className="space-y-3">
            <div className="flex items-center justify-between mb-3">
              <p className="text-sm text-muted-foreground">
                NO, 검사항목, 검사기준, 측정값, 판정 등의 칼럼을 구성하세요
              </p>
              <Button size="sm" onClick={handleAddColumn} type="button">
                <Plus className="h-4 w-4 mr-2" />
                칼럼 추가
              </Button>
            </div>
            
            {editedTemplate.inspectionColumns.length === 0 ? (
              <div className="text-center py-8 border-2 border-dashed rounded-lg text-muted-foreground">
                칼럼을 추가해주세요
              </div>
            ) : (
              <div className="space-y-2">
                {editedTemplate.inspectionColumns.map((col, index) => (
                  <div key={col.id} className="flex gap-2 items-center p-2 bg-muted/30 rounded-lg">
                    <div className="flex items-center justify-center w-8 h-8 bg-green-100 text-green-700 rounded text-sm font-medium">
                      {index + 1}
                    </div>
                    <Input
                      placeholder="칼럼명"
                      value={col.name}
                      onChange={(e) => handleUpdateColumn(col.id, 'name', e.target.value)}
                      className="flex-1"
                    />
                    <Select
                      value={col.type}
                      onValueChange={(value) => handleUpdateColumn(col.id, 'type', value)}
                    >
                      <SelectTrigger className="w-32">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="text">텍스트</SelectItem>
                        <SelectItem value="number">숫자</SelectItem>
                        <SelectItem value="select">선택</SelectItem>
                      </SelectContent>
                    </Select>
                    <Input
                      placeholder="너비"
                      value={col.width || ''}
                      onChange={(e) => handleUpdateColumn(col.id, 'width', e.target.value)}
                      className="w-24"
                    />
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleRemoveColumn(col.id)}
                      type="button"
                      className="text-red-600 hover:text-red-700 hover:bg-red-50"
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                ))}
              </div>
            )}
          </div>
        </FormSection>

        {/* 검사항목 데이터 */}
        <FormSection 
          title="검사항목 데이터 (기본 템플릿)" 
          icon={Settings}
          description="검사 성적서에 기본으로 포함될 검사항목을 설정합니다"
        >
          <div className="space-y-3">
            <div className="flex items-center justify-between mb-3">
              <p className="text-sm text-muted-foreground">
                실제 검사 시 이 템플릿을 기반으로 항목이 생성됩니다
              </p>
              <Button size="sm" onClick={handleAddInspectionItem} type="button">
                <Plus className="h-4 w-4 mr-2" />
                항목 추가
              </Button>
            </div>
            
            {editedTemplate.inspectionColumns.length === 0 ? (
              <div className="text-center py-8 border-2 border-dashed rounded-lg text-muted-foreground">
                먼저 칼럼을 구성해주세요
              </div>
            ) : editedTemplate.inspectionItems.length === 0 ? (
              <div className="text-center py-8 border-2 border-dashed rounded-lg text-muted-foreground">
                검사항목을 추가해주세요
              </div>
            ) : (
              <div className="overflow-x-auto border rounded-lg">
                <table className="w-full">
                  <thead>
                    <tr className="bg-muted">
                      {editedTemplate.inspectionColumns.map(col => (
                        <th key={col.id} className="border p-2 text-sm font-medium" style={{ width: col.width }}>
                          {col.name}
                        </th>
                      ))}
                      <th className="border p-2 w-20 text-sm font-medium">작업</th>
                    </tr>
                  </thead>
                  <tbody>
                    {editedTemplate.inspectionItems.map(item => (
                      <tr key={item.id} className="hover:bg-muted/50">
                        {editedTemplate.inspectionColumns.map(col => (
                          <td key={col.id} className="border p-1">
                            <Input
                              value={item.values[col.id] || ''}
                              onChange={(e) => handleUpdateInspectionItem(item.id, col.id, e.target.value)}
                              className="h-8 text-sm"
                            />
                          </td>
                        ))}
                        <td className="border p-1 text-center">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleRemoveInspectionItem(item.id)}
                            type="button"
                            className="text-red-600 hover:text-red-700 hover:bg-red-50"
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </FormSection>

        {/* 하단 정보 */}
        <FormSection 
          title="하단 정보" 
          icon={Info}
          description="비고 및 종합판정 영역을 설정합니다"
        >
          <FormFieldGrid columns={2}>
            <FormField label="비고 라벨">
              <Input
                value={editedTemplate.notesLabel || '비고'}
                onChange={(e) => setEditedTemplate(prev => ({ ...prev, notesLabel: e.target.value }))}
                placeholder="비고"
              />
            </FormField>

            <FormField label="판정 라벨">
              <Input
                value={editedTemplate.judgmentLabel || '종합판정'}
                onChange={(e) => setEditedTemplate(prev => ({ ...prev, judgmentLabel: e.target.value }))}
                placeholder="종합판정"
              />
            </FormField>
          </FormFieldGrid>

          <FormField 
            label="판정 옵션" 
            helpText="쉼표로 구분하여 입력하세요"
          >
            <Input
              value={editedTemplate.judgmentOptions?.join(', ') || ''}
              onChange={(e) => setEditedTemplate(prev => ({ 
                ...prev, 
                judgmentOptions: e.target.value.split(',').map(s => s.trim()).filter(Boolean)
              }))}
              placeholder="합격, 불합격, 조건부합격"
            />
          </FormField>
        </FormSection>
      </ResponsiveFormTemplate>

      {/* 미리보기 다이얼로그 */}
      <Dialog open={showPreview} onOpenChange={setShowPreview}>
        <DialogContent className="max-w-[95vw] md:max-w-[800px] lg:max-w-[900px] h-[95vh] flex flex-col p-0 overflow-hidden">
          <DialogHeader className="flex-shrink-0 px-6 py-4 border-b">
            <DialogTitle>문서 미리보기</DialogTitle>
          </DialogHeader>
          
          {/* 버튼 영역 - 고정 */}
          <div className="flex-shrink-0 px-6 py-3 border-b bg-muted/30 flex flex-wrap gap-2 justify-between items-center">
            <div className="flex gap-2 flex-wrap">
              <Button size="sm" variant="default" className="bg-red-600 hover:bg-red-700" onClick={() => {
                alert('인쇄 대화상자에서 "PDF로 저장" 옵션을 선택하여 PDF를 생성할 수 있습니다.');
                window.print();
              }}>
                <Download className="w-4 h-4 mr-2" />
                PDF
              </Button>
              <Button size="sm" variant="default" className="bg-blue-600 hover:bg-blue-700" onClick={() => {
                alert('이메일 전송 기능은 백엔드 연동이 필요합니다.');
              }}>
                <Mail className="w-4 h-4 mr-2" />
                이메일
              </Button>
              <Button size="sm" variant="default" className="bg-purple-600 hover:bg-purple-700" onClick={() => {
                alert('팩스 전송 기능은 백엔드 연동이 필요합니다.');
              }}>
                <FileOutput className="w-4 h-4 mr-2" />
                팩스
              </Button>
              <Button size="sm" variant="default" className="bg-yellow-500 hover:bg-yellow-600" onClick={() => {
                alert('카카오톡 전송 기능은 백엔드 연동이 필요합니다.');
              }}>
                <MessageCircle className="w-4 h-4 mr-2" />
                카카오톡
              </Button>
              <Button size="sm" variant="outline" onClick={() => window.print()}>
                <Printer className="w-4 h-4 mr-2" />
                인쇄
              </Button>
            </div>
            <Button size="sm" variant="outline" onClick={() => setShowPreview(false)}>
              <X className="w-4 h-4 mr-2" />
              닫기
            </Button>
          </div>
          
          {/* 스크롤 가능한 문서 영역 */}
          <div className="flex-1 overflow-hidden bg-gray-100">
            {/* A4 문서 영역 */}
            <div 
              className="h-full overflow-y-auto p-4"
              style={{
                scrollbarWidth: 'thin',
                scrollbarColor: 'rgb(203 213 225) transparent'
              }}
            >
              <style dangerouslySetInnerHTML={{__html: `
                .h-full.overflow-y-auto::-webkit-scrollbar {
                  width: 8px;
                }
                .h-full.overflow-y-auto::-webkit-scrollbar-track {
                  background: transparent;
                }
                .h-full.overflow-y-auto::-webkit-scrollbar-thumb {
                  background-color: rgb(203 213 225);
                  border-radius: 4px;
                  transition: background-color 0.2s;
                }
                .h-full.overflow-y-auto::-webkit-scrollbar-thumb:hover {
                  background-color: rgb(148 163 184);
                }
                .h-full.overflow-y-auto::-webkit-scrollbar-thumb:active {
                  background-color: rgb(100 116 139);
                }
              `}} />
              <div className="max-w-[210mm] mx-auto bg-white shadow-lg rounded-lg p-8">
                <InspectionDocumentPreview template={editedTemplate} inspectionType={inspectionType} />
              </div>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}