'use client';

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Plus, Trash2, Settings, Package } from 'lucide-react';
import type { ItemMasterField } from '@/contexts/ItemMasterContext';
import type { MasterOption, OptionColumn } from '../types';
import type { AttributeSubTab } from '../hooks/useTabManagement';

// UnitOption은 MasterOption으로 대체
export type UnitOption = MasterOption;

// AttributeColumn은 OptionColumn으로 대체
export type AttributeColumn = OptionColumn;

// 입력 타입 라벨 변환 헬퍼 함수
const getInputTypeLabel = (inputType: string | undefined): string => {
  const labels: Record<string, string> = {
    textbox: '텍스트박스',
    number: '숫자',
    dropdown: '드롭다운',
    checkbox: '체크박스',
    date: '날짜',
    textarea: '텍스트영역',
  };
  return labels[inputType || ''] || '텍스트박스';
};

interface AttributeTabContentProps {
  activeAttributeTab: string;
  setActiveAttributeTab: (tab: string) => void;
  attributeSubTabs: AttributeSubTab[];
  unitOptions: UnitOption[];
  materialOptions: UnitOption[];
  surfaceTreatmentOptions: UnitOption[];
  customAttributeOptions: Record<string, UnitOption[]>;
  attributeColumns: Record<string, AttributeColumn[]>;
  itemMasterFields: ItemMasterField[];
  // 다이얼로그 핸들러
  setIsManageAttributeTabsDialogOpen: (open: boolean) => void;
  setIsOptionDialogOpen: (open: boolean) => void;
  setEditingOptionType: (type: string) => void;
  setNewOptionValue: (value: string) => void;
  setNewOptionLabel: (value: string) => void;
  setNewOptionColumnValues: (values: Record<string, string>) => void;
  setIsColumnManageDialogOpen: (open: boolean) => void;
  setManagingColumnType: (type: string) => void;
  setNewColumnName: (name: string) => void;
  setNewColumnKey: (key: string) => void;
  setNewColumnType: (type: 'text' | 'number') => void;
  setNewColumnRequired: (required: boolean) => void;
  handleDeleteOption: (type: string, id: string) => void;
}

export function AttributeTabContent({
  activeAttributeTab,
  setActiveAttributeTab,
  attributeSubTabs,
  unitOptions,
  materialOptions,
  surfaceTreatmentOptions,
  customAttributeOptions,
  attributeColumns,
  itemMasterFields,
  setIsManageAttributeTabsDialogOpen,
  setIsOptionDialogOpen,
  setEditingOptionType,
  setNewOptionValue,
  setNewOptionLabel,
  setNewOptionColumnValues,
  setIsColumnManageDialogOpen,
  setManagingColumnType,
  setNewColumnName,
  setNewColumnKey,
  setNewColumnType,
  setNewColumnRequired,
  handleDeleteOption,
}: AttributeTabContentProps) {
  // 옵션 목록 렌더링 헬퍼
  const renderOptionList = (
    options: UnitOption[],
    optionType: string,
    title: string
  ) => {
    const columns = attributeColumns[optionType] || [];

    return (
      <div className="space-y-4">
        <div className="flex items-center justify-between mb-4">
          <h3 className="font-medium">{title}</h3>
          <div className="flex gap-2">
            <Button variant="outline" size="sm" onClick={() => {
              setManagingColumnType(optionType);
              setNewColumnName('');
              setNewColumnKey('');
              setNewColumnType('text');
              setNewColumnRequired(false);
              setIsColumnManageDialogOpen(true);
            }}>
              <Settings className="w-4 h-4 mr-2" />칼럼 관리
            </Button>
            <Button size="sm" onClick={() => {
              setEditingOptionType(optionType === 'units' ? 'unit' : optionType === 'materials' ? 'material' : optionType === 'surface' ? 'surface' : optionType);
              setIsOptionDialogOpen(true);
            }}>
              <Plus className="w-4 h-4 mr-2" />추가
            </Button>
          </div>
        </div>
        <div className="space-y-3">
          {options.map((option) => {
            const hasColumns = columns.length > 0 && option.columnValues;

            return (
              <div key={option.id} className="p-4 border rounded hover:bg-gray-50 transition-colors">
                <div className="flex items-start justify-between gap-3">
                  <div className="flex-1 space-y-2">
                    <div className="flex items-center gap-2">
                      <span className="font-medium text-base">{option.label}</span>
                      {option.inputType && (
                        <Badge variant="outline" className="text-xs">{getInputTypeLabel(option.inputType)}</Badge>
                      )}
                      {option.required && (
                        <Badge variant="destructive" className="text-xs">필수</Badge>
                      )}
                    </div>

                    <div className="text-sm text-muted-foreground space-y-1">
                      <div className="flex gap-2">
                        <span className="font-medium min-w-16">값(Value):</span>
                        <span>{option.value}</span>
                      </div>
                      {option.placeholder && (
                        <div className="flex gap-2">
                          <span className="font-medium min-w-16">플레이스홀더:</span>
                          <span>{option.placeholder}</span>
                        </div>
                      )}
                      {option.defaultValue && (
                        <div className="flex gap-2">
                          <span className="font-medium min-w-16">기본값:</span>
                          <span>{option.defaultValue}</span>
                        </div>
                      )}
                      {option.inputType === 'dropdown' && option.options && (
                        <div className="flex gap-2">
                          <span className="font-medium min-w-16">옵션:</span>
                          <div className="flex flex-wrap gap-1">
                            {option.options.map((opt, idx) => (
                              <Badge key={idx} variant="secondary" className="text-xs">{opt}</Badge>
                            ))}
                          </div>
                        </div>
                      )}
                    </div>

                    {hasColumns && (
                      <div className="mt-3 pt-3 border-t">
                        <p className="text-xs font-medium text-muted-foreground mb-2">추가 칼럼</p>
                        <div className="grid grid-cols-2 gap-2 text-sm">
                          {columns.map((column) => (
                            <div key={column.id} className="flex gap-2">
                              <span className="text-muted-foreground">{column.name}:</span>
                              <span>{option.columnValues?.[column.key] || '-'}</span>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                  <Button variant="ghost" size="sm" onClick={() => handleDeleteOption(optionType === 'units' ? 'unit' : optionType === 'materials' ? 'material' : optionType === 'surface' ? 'surface' : optionType, option.id)}>
                    <Trash2 className="w-4 h-4 text-red-500" />
                  </Button>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  };

  // 마스터 필드 속성 렌더링
  const renderMasterFieldProperties = (masterField: ItemMasterField) => {
    const propertiesArray = masterField?.properties
      ? Object.entries(masterField.properties).map(([key, value]) => ({ key, ...value as object }))
      : [];

    if (propertiesArray.length === 0) return null;

    return (
      <div className="space-y-4">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h3 className="font-medium">{masterField.field_name} 속성 목록</h3>
            <p className="text-sm text-muted-foreground mt-1">
              항목 탭에서 추가한 &quot;{masterField.field_name}&quot; 항목의 속성값들입니다
            </p>
          </div>
        </div>

        <div className="space-y-3">
          {/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
          {propertiesArray.map((property: any) => {
            const inputTypeLabel = getInputTypeLabel(property.type);

            return (
              <div key={property.key} className="p-4 border rounded hover:bg-gray-50 transition-colors">
                <div className="flex items-start justify-between gap-3">
                  <div className="flex-1 space-y-2">
                    <div className="flex items-center gap-2">
                      <span className="font-medium text-base">{property.label}</span>
                      <Badge variant="outline" className="text-xs">{inputTypeLabel}</Badge>
                      {property.required && (
                        <Badge variant="destructive" className="text-xs">필수</Badge>
                      )}
                    </div>

                    <div className="text-sm text-muted-foreground space-y-1">
                      <div className="flex gap-2">
                        <span className="font-medium min-w-24">키(Key):</span>
                        <code className="bg-gray-100 px-2 py-0.5 rounded text-xs">{property.key}</code>
                      </div>
                      {property.placeholder && (
                        <div className="flex gap-2">
                          <span className="font-medium min-w-24">플레이스홀더:</span>
                          <span>{property.placeholder}</span>
                        </div>
                      )}
                      {property.defaultValue && (
                        <div className="flex gap-2">
                          <span className="font-medium min-w-24">기본값:</span>
                          <span>{property.defaultValue}</span>
                        </div>
                      )}
                      {property.type === 'dropdown' && property.options && (
                        <div className="flex gap-2">
                          <span className="font-medium min-w-24">옵션:</span>
                          <div className="flex flex-wrap gap-1">
                            {property.options.map((opt: string, idx: number) => (
                              <Badge key={idx} variant="secondary" className="text-xs">{opt}</Badge>
                            ))}
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        <div className="mt-4 p-4 bg-blue-50 border border-blue-200 rounded-lg">
          <div className="flex items-start gap-2">
            <Package className="w-5 h-5 text-blue-600 mt-0.5" />
            <div className="flex-1">
              <p className="text-sm font-medium text-blue-900">
                마스터 항목 속성 관리
              </p>
              <p className="text-xs text-blue-700 mt-1">
                이 속성들은 <strong>항목 탭</strong>에서 &quot;{masterField.field_name}&quot; 항목을 편집하여 추가/수정/삭제할 수 있습니다.
              </p>
            </div>
          </div>
        </div>
      </div>
    );
  };

  // 사용자 정의 속성 렌더링
  const renderCustomAttributeTab = () => {
    const currentTabKey = activeAttributeTab;
    const currentOptions = customAttributeOptions[currentTabKey] || [];
    const columns = attributeColumns[currentTabKey] || [];

    return (
      <div className="space-y-4">
        <div className="flex items-center justify-between mb-4">
          <h3 className="font-medium">
            {attributeSubTabs.find(t => t.key === activeAttributeTab)?.label || '사용자 정의'} 목록
          </h3>
          <div className="flex gap-2">
            <Button variant="outline" size="sm" onClick={() => {
              setManagingColumnType(currentTabKey);
              setNewColumnName('');
              setNewColumnKey('');
              setNewColumnType('text');
              setNewColumnRequired(false);
              setIsColumnManageDialogOpen(true);
            }}>
              <Settings className="w-4 h-4 mr-2" />칼럼 관리
            </Button>
            <Button size="sm" onClick={() => {
              setEditingOptionType(activeAttributeTab);
              setNewOptionValue('');
              setNewOptionLabel('');
              setNewOptionColumnValues({});
              setIsOptionDialogOpen(true);
            }}>
              <Plus className="w-4 h-4 mr-2" />추가
            </Button>
          </div>
        </div>

        {currentOptions.length > 0 ? (
          <div className="space-y-3">
            {currentOptions.map((option) => {
              const hasColumns = columns.length > 0 && option.columnValues;
              const inputTypeLabel = getInputTypeLabel(option.inputType);

              return (
                <div key={option.id} className="p-4 border rounded hover:bg-gray-50 transition-colors">
                  <div className="flex items-start justify-between gap-3">
                    <div className="flex-1 space-y-2">
                      <div className="flex items-center gap-2">
                        <span className="font-medium text-base">{option.label}</span>
                        <Badge variant="outline" className="text-xs">{inputTypeLabel}</Badge>
                        {option.required && (
                          <Badge variant="destructive" className="text-xs">필수</Badge>
                        )}
                      </div>

                      <div className="text-sm text-muted-foreground space-y-1">
                        <div className="flex gap-2">
                          <span className="font-medium min-w-16">값(Value):</span>
                          <span>{option.value}</span>
                        </div>
                        {option.placeholder && (
                          <div className="flex gap-2">
                            <span className="font-medium min-w-16">플레이스홀더:</span>
                            <span>{option.placeholder}</span>
                          </div>
                        )}
                        {option.defaultValue && (
                          <div className="flex gap-2">
                            <span className="font-medium min-w-16">기본값:</span>
                            <span>{option.defaultValue}</span>
                          </div>
                        )}
                        {option.inputType === 'dropdown' && option.options && (
                          <div className="flex gap-2">
                            <span className="font-medium min-w-16">옵션:</span>
                            <div className="flex flex-wrap gap-1">
                              {option.options.map((opt, idx) => (
                                <Badge key={idx} variant="secondary" className="text-xs">{opt}</Badge>
                              ))}
                            </div>
                          </div>
                        )}
                      </div>

                      {hasColumns && (
                        <div className="mt-3 pt-3 border-t">
                          <p className="text-xs font-medium text-muted-foreground mb-2">추가 칼럼</p>
                          <div className="grid grid-cols-2 gap-2 text-sm">
                            {columns.map((column) => (
                              <div key={column.id} className="flex gap-2">
                                <span className="text-muted-foreground">{column.name}:</span>
                                <span>{option.columnValues?.[column.key] || '-'}</span>
                              </div>
                            ))}
                          </div>
                        </div>
                      )}
                    </div>
                    <Button variant="ghost" size="sm" onClick={() => handleDeleteOption(currentTabKey, option.id)}>
                      <Trash2 className="w-4 h-4 text-red-500" />
                    </Button>
                  </div>
                </div>
              );
            })}
          </div>
        ) : (
          <div className="border-2 border-dashed rounded-lg p-8 text-center text-gray-500">
            <Settings className="w-12 h-12 mx-auto mb-4 text-gray-400" />
            <p className="mb-2">아직 추가된 항목이 없습니다</p>
            <p className="text-sm">위 &quot;추가&quot; 버튼을 클릭하여 새로운 속성을 추가할 수 있습니다</p>
          </div>
        )}
      </div>
    );
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>속성 관리</CardTitle>
        <CardDescription>단위, 재질, 표면처리 등의 속성을 관리합니다</CardDescription>
      </CardHeader>
      <CardContent>
        {/* 속성 하위 탭 (칩 형태) */}
        <div className="flex items-center gap-2 mb-6 border-b pb-2">
          <div className="flex gap-2 flex-1 flex-wrap">
            {attributeSubTabs.sort((a, b) => a.order - b.order).map(tab => (
              <Button
                key={tab.id}
                variant={activeAttributeTab === tab.key ? 'default' : 'outline'}
                size="sm"
                onClick={() => setActiveAttributeTab(tab.key)}
                className="rounded-full"
              >
                {tab.label}
              </Button>
            ))}
          </div>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => setIsManageAttributeTabsDialogOpen(true)}
            className="shrink-0"
          >
            <Settings className="w-4 h-4 mr-1" />
            항목 관리
          </Button>
        </div>

        {/* 단위 관리 */}
        {activeAttributeTab === 'units' && renderOptionList(unitOptions, 'units', '단위 목록')}

        {/* 재질 관리 */}
        {activeAttributeTab === 'materials' && renderOptionList(materialOptions, 'materials', '재질 목록')}

        {/* 표면처리 관리 */}
        {activeAttributeTab === 'surface' && renderOptionList(surfaceTreatmentOptions, 'surface', '표면처리 목록')}

        {/* 사용자 정의 속성 탭 및 마스터 항목 탭 */}
        {!['units', 'materials', 'surface'].includes(activeAttributeTab) && (() => {
          const currentTabKey = activeAttributeTab;

          // 마스터 항목인지 확인
          const masterField = itemMasterFields.find(f => f.id.toString() === currentTabKey);

          if (masterField) {
            const propertiesArray = masterField?.properties
              ? Object.entries(masterField.properties).map(([key, value]) => ({ key, ...value as object }))
              : [];

            if (propertiesArray.length > 0) {
              return renderMasterFieldProperties(masterField);
            }
          }

          // 사용자 정의 속성 탭
          return renderCustomAttributeTab();
        })()}
      </CardContent>
    </Card>
  );
}
