'use client';

import { useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Plus, Edit, Trash2, Folder, Package, FileText, GripVertical, Copy, Download, Unlink } from 'lucide-react';
import type { SectionTemplate, BOMItem, TemplateField } from '@/contexts/ItemMasterContext';
import { BOMManagementSection } from '../../BOMManagementSection';

interface SectionsTabProps {
  // 섹션 템플릿 데이터
  sectionTemplates: SectionTemplate[];

  // 다이얼로그 상태
  setIsSectionTemplateDialogOpen: (open: boolean) => void;
  setCurrentTemplateId: (id: number | null) => void;
  setIsTemplateFieldDialogOpen: (open: boolean) => void;

  // 템플릿 핸들러
  handleEditSectionTemplate: (template: SectionTemplate) => void;
  handleDeleteSectionTemplate: (id: number) => void;

  // 템플릿 필드 핸들러
  handleEditTemplateField: (templateId: number, field: TemplateField) => void;
  handleDeleteTemplateField: (templateId: number, fieldId: string) => void;

  // BOM 핸들러
  handleAddBOMItemToTemplate: (templateId: number, item: Omit<BOMItem, 'id' | 'created_at' | 'updated_at' | 'tenant_id' | 'section_id'>) => void;
  handleUpdateBOMItemInTemplate: (templateId: number, itemId: number, item: Partial<BOMItem>) => void;
  handleDeleteBOMItemFromTemplate: (templateId: number, itemId: number) => void;

  // 옵션
  ITEM_TYPE_OPTIONS: Array<{ value: string; label: string }>;
  INPUT_TYPE_OPTIONS: Array<{ value: string; label: string }>;
  unitOptions?: Array<{ value: string; label: string }>;

  // 변경사항 추적 (나중에 사용 예정)
  hasUnsavedChanges?: boolean;
  pendingChanges?: {
    sectionTemplates: any[];
  };

  // 2025-11-26 추가: 복제 및 필드 불러오기
  onCloneSection?: (sectionId: number) => Promise<void>;
  setIsImportFieldDialogOpen?: (open: boolean) => void;
  setImportFieldTargetSectionId?: (id: number | null) => void;
}

export function SectionsTab({
  sectionTemplates,
  setIsSectionTemplateDialogOpen,
  setCurrentTemplateId,
  setIsTemplateFieldDialogOpen,
  handleEditSectionTemplate,
  handleDeleteSectionTemplate,
  handleEditTemplateField,
  handleDeleteTemplateField,
  handleAddBOMItemToTemplate,
  handleUpdateBOMItemInTemplate,
  handleDeleteBOMItemFromTemplate,
  ITEM_TYPE_OPTIONS,
  INPUT_TYPE_OPTIONS,
  unitOptions = [],
  hasUnsavedChanges: _hasUnsavedChanges = false,
  pendingChanges: _pendingChanges = { sectionTemplates: [] },
  onCloneSection,
  setIsImportFieldDialogOpen,
  setImportFieldTargetSectionId,
}: SectionsTabProps) {
  // 2025-11-27: prop 변경 추적 (디버깅용)
  useEffect(() => {
  }, [sectionTemplates]);

  return (
    <Card>
      <CardHeader>
        <div className="flex items-start justify-between gap-2">
          <div className="flex items-center gap-3 min-w-0">
            <div className="min-w-0">
              <CardTitle>섹션 템플릿 관리</CardTitle>
              <CardDescription className="truncate">재사용 가능한 섹션 템플릿을 관리합니다</CardDescription>
            </div>
            {/* 변경사항 배지 - 나중에 사용 예정으로 임시 숨김 */}
            {/* {hasUnsavedChanges && pendingChanges.sectionTemplates.length > 0 && (
              <Badge variant="destructive" className="animate-pulse">
                {pendingChanges.sectionTemplates.length}개 변경
              </Badge>
            )} */}
          </div>
          <Button size="sm" className="shrink-0" onClick={() => setIsSectionTemplateDialogOpen(true)}>
            <Plus className="h-4 w-4 md:mr-2" /><span className="hidden md:inline">섹션추가</span>
          </Button>
        </div>
      </CardHeader>
      <CardContent>
        <Tabs defaultValue="general" className="w-full">
          <TabsList className="grid w-full grid-cols-2 mb-6">
            <TabsTrigger value="general" className="flex items-center gap-2">
              <Folder className="h-4 w-4" />
              일반 섹션
            </TabsTrigger>
            <TabsTrigger value="module" className="flex items-center gap-2">
              <Package className="h-4 w-4" />
              모듈 섹션
            </TabsTrigger>
          </TabsList>

          {/* 일반 섹션 탭 */}
          <TabsContent value="general">
            {(() => {
              return null;
            })()}
            {sectionTemplates.filter(t => t.section_type !== 'BOM').length === 0 ? (
              <div className="text-center py-12">
                <Folder className="w-16 h-16 mx-auto text-gray-300 mb-4" />
                <p className="text-muted-foreground mb-2">등록된 일반 섹션이 없습니다</p>
                <p className="text-sm text-muted-foreground">
                  섹션추가 버튼을 눌러 재사용 가능한 섹션을 등록하세요.
                </p>
              </div>
            ) : (
              <div className="space-y-4">
                {sectionTemplates.filter(t => t.section_type !== 'BOM').map((template) => (
                  <Card key={template.id}>
                    <CardHeader className="pb-3">
                      <div className="flex items-start justify-between gap-2">
                        <div className="flex items-center gap-3 min-w-0 flex-1">
                          <Folder className="h-5 w-5 text-blue-500 shrink-0" />
                          <div className="min-w-0 flex-1">
                            <CardTitle className="text-base truncate">{template.template_name}</CardTitle>
                            {template.description && (
                              <CardDescription className="text-sm mt-0.5 truncate">{template.description}</CardDescription>
                            )}
                          </div>
                        </div>
                        <div className="flex items-center gap-1 shrink-0">
                          {template.category && template.category.length > 0 && (
                            <div className="hidden md:flex flex-wrap gap-1 mr-2">
                              {template.category.map((cat, idx) => (
                                <Badge key={idx} variant="secondary" className="text-xs">
                                  {ITEM_TYPE_OPTIONS.find(t => t.value === cat)?.label || cat}
                                </Badge>
                              ))}
                            </div>
                          )}
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => handleEditSectionTemplate(template)}
                            title="수정"
                          >
                            <Edit className="h-4 w-4" />
                          </Button>
                          {onCloneSection && (
                            <Button
                              size="sm"
                              variant="ghost"
                              onClick={() => onCloneSection(template.id)}
                              title="복제"
                            >
                              <Copy className="h-4 w-4 text-green-500" />
                            </Button>
                          )}
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => handleDeleteSectionTemplate(template.id)}
                            title="삭제"
                          >
                            <Trash2 className="h-4 w-4 text-red-500" />
                          </Button>
                        </div>
                      </div>
                    </CardHeader>
                    <CardContent>
                      <div className="mb-4 flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
                        <p className="text-sm text-muted-foreground">
                          이 템플릿과 관련되는 항목 목록을 조회합니다
                        </p>
                        <div className="flex gap-2 shrink-0">
                          {setIsImportFieldDialogOpen && setImportFieldTargetSectionId && (
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => {
                                setImportFieldTargetSectionId(template.id);
                                setIsImportFieldDialogOpen(true);
                              }}
                            >
                              <Download className="h-4 w-4 mr-2" />
                              불러오기
                            </Button>
                          )}
                          <Button
                            size="sm"
                            onClick={() => {
                              setCurrentTemplateId(template.id);
                              setIsTemplateFieldDialogOpen(true);
                            }}
                          >
                            <Plus className="h-4 w-4 mr-2" />
                            항목 추가
                          </Button>
                        </div>
                      </div>

                      {(!template.fields || template.fields.length === 0) ? (
                        <div className="bg-gray-50 border-2 border-dashed border-gray-200 rounded-lg py-16">
                          <div className="text-center">
                            <div className="w-16 h-16 mx-auto mb-4 bg-gray-100 rounded-lg flex items-center justify-center">
                              <FileText className="w-8 h-8 text-gray-400" />
                            </div>
                            <p className="text-gray-600 mb-1">
                              항목을 활용한 구간입니다 추가 버튼을 클릭해보세요
                            </p>
                            <p className="text-sm text-gray-500">
                              품목의 목록명, 수량, 입력방법 고객화된 표시할 수 있습니다
                            </p>
                          </div>
                        </div>
                      ) : (
                        <div className="space-y-2">
                          {template.fields.map((field, index) => (
                            <div
                              key={`${template.id}-${field.id}-${index}`}
                              className="flex items-center justify-between gap-2 p-3 border rounded hover:bg-gray-50 transition-colors"
                            >
                              <div className="flex-1 min-w-0">
                                <div className="flex items-center gap-1.5 flex-wrap">
                                  <GripVertical className="h-4 w-4 text-gray-400 shrink-0" />
                                  <span className="text-sm font-medium">{field.name}</span>
                                  <Badge variant="outline" className="text-xs shrink-0">
                                    {INPUT_TYPE_OPTIONS.find(t => t.value === field.property.inputType)?.label}
                                  </Badge>
                                  {field.property.required && (
                                    <Badge variant="destructive" className="text-xs shrink-0">필수</Badge>
                                  )}
                                </div>
                                <div className="ml-6 text-xs text-gray-500 mt-1 truncate">
                                  필드키: {field.fieldKey}
                                  {field.description && (
                                    <span className="ml-2">• {field.description}</span>
                                  )}
                                </div>
                              </div>
                              <div className="flex gap-1 shrink-0">
                                <Button
                                  size="sm"
                                  variant="ghost"
                                  onClick={() => handleEditTemplateField(template.id, field)}
                                  title="수정"
                                >
                                  <Edit className="h-4 w-4 text-blue-500" />
                                </Button>
                                <Button
                                  size="sm"
                                  variant="ghost"
                                  onClick={() => handleDeleteTemplateField(template.id, field.id)}
                                  title="연결 해제"
                                >
                                  <Unlink className="h-4 w-4 text-orange-500" />
                                </Button>
                              </div>
                            </div>
                          ))}
                        </div>
                      )}
                    </CardContent>
                  </Card>
                ))}
              </div>
            )}
          </TabsContent>

          {/* 모듈 섹션 (BOM) 탭 */}
          <TabsContent value="module">
            {sectionTemplates.filter(t => t.section_type === 'BOM').length === 0 ? (
              <div className="text-center py-12">
                <Package className="w-16 h-16 mx-auto text-gray-300 mb-4" />
                <p className="text-muted-foreground mb-2">등록된 모듈 섹션이 없습니다</p>
                <p className="text-sm text-muted-foreground">
                  섹션추가 버튼을 눌러 BOM 모듈 섹션을 등록하세요.
                </p>
              </div>
            ) : (
              <div className="space-y-4">
                {sectionTemplates.filter(t => t.section_type === 'BOM').map((template) => (
                  <Card key={template.id}>
                    <CardHeader className="pb-3">
                      <div className="flex items-start justify-between gap-2">
                        <div className="flex items-center gap-3 min-w-0 flex-1">
                          <Package className="h-5 w-5 text-green-500 shrink-0" />
                          <div className="min-w-0 flex-1">
                            <CardTitle className="text-base truncate">{template.template_name}</CardTitle>
                            {template.description && (
                              <CardDescription className="text-sm mt-0.5 truncate">{template.description}</CardDescription>
                            )}
                          </div>
                        </div>
                        <div className="flex items-center gap-1 shrink-0">
                          {template.category && template.category.length > 0 && (
                            <div className="hidden md:flex flex-wrap gap-1 mr-2">
                              {template.category.map((cat, idx) => (
                                <Badge key={idx} variant="secondary" className="text-xs">
                                  {ITEM_TYPE_OPTIONS.find(t => t.value === cat)?.label || cat}
                                </Badge>
                              ))}
                            </div>
                          )}
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => handleEditSectionTemplate(template)}
                            title="수정"
                          >
                            <Edit className="h-4 w-4" />
                          </Button>
                          {onCloneSection && (
                            <Button
                              size="sm"
                              variant="ghost"
                              onClick={() => onCloneSection(template.id)}
                              title="복제"
                            >
                              <Copy className="h-4 w-4 text-green-500" />
                            </Button>
                          )}
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => handleDeleteSectionTemplate(template.id)}
                            title="삭제"
                          >
                            <Trash2 className="h-4 w-4 text-red-500" />
                          </Button>
                        </div>
                      </div>
                    </CardHeader>
                    <CardContent>
                      <BOMManagementSection
                        title=""
                        description=""
                        bomItems={template.bomItems || []}
                        onAddItem={(item) => handleAddBOMItemToTemplate(template.id, item)}
                        onUpdateItem={(itemId, item) => handleUpdateBOMItemInTemplate(template.id, itemId, item)}
                        onDeleteItem={(itemId) => handleDeleteBOMItemFromTemplate(template.id, itemId)}
                        unitOptions={unitOptions}
                        itemTypeOptions={ITEM_TYPE_OPTIONS}
                      />
                    </CardContent>
                  </Card>
                ))}
              </div>
            )}
          </TabsContent>
        </Tabs>
      </CardContent>
    </Card>
  );
}
