'use client';

/**
 * 항목 탭 컴포넌트
 *
 * @deprecated 2025-11-27: "마스터 항목" → "항목"으로 명칭 변경
 * - item_master_fields 테이블 삭제됨
 * - item_fields WHERE section_id IS NULL로 통합
 * - 향후 FieldTab으로 리네임 예정
 */
import { useState, useMemo } from 'react';
import type { ItemMasterField } from '@/contexts/ItemMasterContext';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { getPresetStyle } from '@/lib/utils/status-config';
import { Plus, Edit, Trash2, Search, X } from 'lucide-react';

// 입력방식 옵션 (ItemMasterDataManagement에서 사용하는 상수)
const INPUT_TYPE_OPTIONS = [
  { value: 'textbox', label: '텍스트' },
  { value: 'dropdown', label: '드롭다운' },
  { value: 'checkbox', label: '체크박스' },
  { value: 'number', label: '숫자' },
  { value: 'date', label: '날짜' },
  { value: 'textarea', label: '텍스트영역' }
];

// 변경 레코드 타입 (임시 - 나중에 공통 타입으로 분리)
interface ChangeRecord {
  masterFields: Array<{
    type: 'add' | 'update' | 'delete';
    id: string;
    data?: any;
  }>;
  [key: string]: any;
}

interface MasterFieldTabProps {
  itemMasterFields: ItemMasterField[];
  setIsMasterFieldDialogOpen: (open: boolean) => void;
  handleEditMasterField: (field: ItemMasterField) => void;
  handleDeleteMasterField: (id: number) => void;
  hasUnsavedChanges: boolean;
  pendingChanges: ChangeRecord;
}

export function MasterFieldTab({
  itemMasterFields,
  setIsMasterFieldDialogOpen,
  handleEditMasterField,
  handleDeleteMasterField,
  hasUnsavedChanges: _hasUnsavedChanges,
  pendingChanges: _pendingChanges
}: MasterFieldTabProps) {
  const [searchQuery, setSearchQuery] = useState('');

  const filteredFields = useMemo(() => {
    if (!searchQuery.trim()) return itemMasterFields;
    const query = searchQuery.trim().toLowerCase();
    return itemMasterFields.filter(field => {
      const fieldName = field.field_name?.toLowerCase() || '';
      const fieldType = INPUT_TYPE_OPTIONS.find(t => t.value === field.field_type)?.label?.toLowerCase() || '';
      const category = field.category?.toLowerCase() || '';
      const description = field.description?.toLowerCase() || '';
      const fieldId = String(field.id);
      return fieldName.includes(query) || fieldType.includes(query) || category.includes(query) || description.includes(query) || fieldId.includes(query);
    });
  }, [itemMasterFields, searchQuery]);

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div>
              <CardTitle>항목 관리</CardTitle>
              <CardDescription>재사용 가능한 항목을 관리합니다. 섹션에 연결하여 사용할 수 있습니다.</CardDescription>
            </div>
            {/* 변경사항 배지 - 나중에 사용 예정으로 임시 숨김 */}
            {/* {hasUnsavedChanges && pendingChanges.masterFields.length > 0 && (
              <Badge variant="destructive" className="animate-pulse">
                {pendingChanges.masterFields.length}개 변경
              </Badge>
            )} */}
          </div>
          <Button onClick={() => setIsMasterFieldDialogOpen(true)}>
            <Plus className="h-4 w-4 mr-2" />항목 추가
          </Button>
        </div>
        {itemMasterFields.length > 0 && (
          <div className="relative mt-3">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input
              placeholder="항목명, 입력타입, 카테고리, ID로 검색..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-9 pr-9"
            />
            {searchQuery && (
              <button
                onClick={() => setSearchQuery('')}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
              >
                <X className="h-4 w-4" />
              </button>
            )}
          </div>
        )}
      </CardHeader>
      <CardContent>
        {itemMasterFields.length === 0 ? (
          <div className="text-center py-8">
            <p className="text-muted-foreground mb-2">등록된 항목이 없습니다</p>
            <p className="text-sm text-muted-foreground">
              항목 추가 버튼을 눌러 재사용 가능한 항목을 등록하세요.
            </p>
          </div>
        ) : (
          <div className="space-y-2">
            {searchQuery && (
              <p className="text-sm text-muted-foreground mb-2">
                {filteredFields.length}건 검색됨 (전체 {itemMasterFields.length}건)
              </p>
            )}
            {filteredFields.length === 0 && searchQuery ? (
              <div className="text-center py-8">
                <p className="text-muted-foreground">"{searchQuery}"에 대한 검색 결과가 없습니다</p>
              </div>
            ) : null}
            {filteredFields.map((field, index) => (
              <div key={`masterfield-${field.id}-${index}`} className="flex items-center justify-between p-4 border rounded hover:bg-gray-50 transition-colors">
                <div className="flex-1">
                  <div className="flex items-center gap-2">
                    <span>{field.field_name}</span>
                    <Badge variant="outline" className="text-xs">
                      {INPUT_TYPE_OPTIONS.find(t => t.value === field.field_type)?.label}
                    </Badge>
                    {(field.is_required || field.properties?.required) && (
                      <Badge variant="destructive" className="text-xs">필수</Badge>
                    )}
                    {field.category && (
                      <Badge variant="secondary" className="text-xs">{field.category}</Badge>
                    )}
                    {field.properties?.attributeType && field.properties.attributeType !== 'custom' && (
                      <Badge variant="default" className={`text-xs ${getPresetStyle('info')}`}>
                        {field.properties.attributeType === 'unit' ? '단위 연동' :
                         field.properties.attributeType === 'material' ? '재질 연동' : '표면처리 연동'}
                      </Badge>
                    )}
                  </div>
                  <div className="text-sm text-muted-foreground mt-1">
                    ID: {field.id}
                    {field.description && (
                      <span className="ml-2">• {field.description}</span>
                    )}
                  </div>
                  {field.options && field.options.length > 0 && (
                    <div className="text-xs text-gray-500 mt-1">
                      옵션: {field.options.map(opt => opt.label).join(', ')}
                      {field.properties?.attributeType && field.properties.attributeType !== 'custom' && (
                        <span className="ml-2 text-blue-600">
                          (속성 탭 자동 동기화)
                        </span>
                      )}
                    </div>
                  )}
                </div>
                <div className="flex gap-2">
                  <Button
                    size="sm"
                    variant="ghost"
                    onClick={() => handleEditMasterField(field)}
                  >
                    <Edit className="h-4 w-4 text-blue-500" />
                  </Button>
                  <Button
                    size="sm"
                    variant="ghost"
                    onClick={() => handleDeleteMasterField(field.id)}
                  >
                    <Trash2 className="h-4 w-4 text-red-500" />
                  </Button>
                </div>
              </div>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  );
}
