'use client';

/**
 * 필드 불러오기 다이얼로그
 *
 * @description 2025-11-27: API 변경으로 "항목/독립필드" 탭 통합
 * - item_master_fields 테이블 삭제됨
 * - 모든 필드가 item_fields로 통합 (section_id=NULL이 독립 필드)
 * - 이전: itemMasterFields + independentFields 분리
 * - 현재: fields 단일 목록으로 통합
 */
import { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { FormInput, Search, Info, Loader2, Hash, Calendar, CheckSquare, ChevronDown, Type, AlignLeft, Database } from 'lucide-react';
import { ContentSkeleton } from '@/components/ui/skeleton';
import type { ItemField, ItemMasterField } from '@/contexts/ItemMasterContext';
import type { FieldUsageResponse } from '@/types/item-master-api';
import { isNextRedirectError } from '@/lib/utils/redirect-error';

interface ImportFieldDialogProps {
  isOpen: boolean;
  setIsOpen: (open: boolean) => void;
  /** 필드 목록 (item_fields WHERE section_id IS NULL) - ItemField 또는 ItemMasterField 모두 허용 */
  fields: (ItemField | ItemMasterField)[];
  /** @deprecated 2025-11-27: fields로 통합됨. 하위 호환성을 위해 유지 */
  independentFields?: ItemField[];
  /** @deprecated 2025-11-27: fields로 통합됨. 하위 호환성을 위해 유지 */
  itemMasterFields?: ItemMasterField[];
  selectedFieldId: number | null;
  setSelectedFieldId: (id: number | null) => void;
  onImport: () => void;
  onRefresh: () => Promise<void>;
  onGetUsage?: (fieldId: number) => Promise<FieldUsageResponse>;
  isLoading?: boolean;
  targetSectionTitle?: string;
}

// Field type icon mapping
const FIELD_TYPE_ICONS: Record<string, React.ReactNode> = {
  textbox: <Type className="w-4 h-4" />,
  number: <Hash className="w-4 h-4" />,
  dropdown: <ChevronDown className="w-4 h-4" />,
  checkbox: <CheckSquare className="w-4 h-4" />,
  date: <Calendar className="w-4 h-4" />,
  textarea: <AlignLeft className="w-4 h-4" />,
};

const FIELD_TYPE_LABELS: Record<string, string> = {
  textbox: '텍스트박스',
  number: '숫자',
  dropdown: '드롭다운',
  checkbox: '체크박스',
  date: '날짜',
  textarea: '텍스트영역',
};

export function ImportFieldDialog({
  isOpen,
  setIsOpen,
  fields = [],
  independentFields,
  itemMasterFields,
  selectedFieldId,
  setSelectedFieldId,
  onImport,
  onRefresh,
  onGetUsage,
  isLoading = false,
  targetSectionTitle,
}: ImportFieldDialogProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [usageInfo, setUsageInfo] = useState<FieldUsageResponse | null>(null);
  const [isLoadingUsage, setIsLoadingUsage] = useState(false);

  // 2025-11-27: 하위 호환성 - fields가 없으면 independentFields나 itemMasterFields 사용
  const allFields = fields.length > 0
    ? fields
    : (independentFields || itemMasterFields || []);

  // Filter fields by search query
  // Note: ItemField와 ItemMasterField 타입의 속성 차이를 처리하기 위해 타입 단언 사용
  const filteredFields = allFields.filter(field => {
    const f = field as ItemField & ItemMasterField; // 두 타입의 모든 속성 접근 허용
    return (
      f.field_name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      f.description?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      f.category?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      f.placeholder?.toLowerCase().includes(searchQuery.toLowerCase())
    );
  });

  // Load fields when dialog opens
  useEffect(() => {
    if (isOpen) {
      onRefresh();
      setSearchQuery('');
      setUsageInfo(null);
    }
  }, [isOpen]);

  // Load usage info when field is selected
  useEffect(() => {
    const loadUsage = async () => {
      if (selectedFieldId && onGetUsage) {
        setIsLoadingUsage(true);
        try {
          const usage = await onGetUsage(selectedFieldId);
          setUsageInfo(usage);
        } catch (error) {
          if (isNextRedirectError(error)) throw error;
          console.error('Failed to load usage info:', error);
          setUsageInfo(null);
        } finally {
          setIsLoadingUsage(false);
        }
      } else {
        setUsageInfo(null);
      }
    };
    loadUsage();
  }, [selectedFieldId, onGetUsage]);

  const handleClose = () => {
    setIsOpen(false);
    setSelectedFieldId(null);
    setSearchQuery('');
    setUsageInfo(null);
  };

  return (
    <Dialog open={isOpen} onOpenChange={(open) => {
      if (!open) handleClose();
      else setIsOpen(open);
    }}>
      <DialogContent className="max-w-[95vw] sm:max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>필드 불러오기</DialogTitle>
          <DialogDescription>
            필드를 선택하여 {targetSectionTitle ? `"${targetSectionTitle}" 섹션` : '현재 섹션'}에 연결합니다.
          </DialogDescription>
        </DialogHeader>

        {/* Search */}
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="필드 검색..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10"
          />
        </div>

        <div className="space-y-4">
          {isLoading ? (
            <ContentSkeleton type="list" rows={5} />
          ) : filteredFields.length === 0 ? (
            <div className="text-center py-8">
              <FormInput className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
              <p className="text-muted-foreground">
                {searchQuery ? '검색 결과가 없습니다' : '등록된 필드가 없습니다'}
              </p>
              <p className="text-sm text-muted-foreground mt-2">
                항목 탭에서 새 필드를 생성해주세요
              </p>
            </div>
          ) : (
            <div className="space-y-2 max-h-80 overflow-y-auto">
              {/* 통합 필드 목록 - ItemField와 ItemMasterField 타입 호환을 위해 intersection 타입 사용 */}
              {filteredFields.map((field) => {
                // 두 타입의 모든 속성에 안전하게 접근하기 위한 타입 단언
                const f = field as ItemField & ItemMasterField;
                return (
                  <div
                    key={f.id}
                    onClick={() => setSelectedFieldId(f.id)}
                    className={`p-4 border rounded-lg cursor-pointer transition-colors ${
                      selectedFieldId === f.id
                        ? 'border-blue-500 bg-blue-50 dark:bg-blue-950'
                        : 'hover:bg-gray-50 dark:hover:bg-gray-800'
                    }`}
                  >
                    <div className="flex items-start gap-3">
                      <div className="p-2 rounded-lg bg-blue-100 dark:bg-blue-900">
                        {FIELD_TYPE_ICONS[f.field_type] || <Database className="w-5 h-5 text-blue-600 dark:text-blue-400" />}
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-1 flex-wrap">
                          <h4 className="font-medium">{f.field_name}</h4>
                          <Badge variant="secondary">
                            {FIELD_TYPE_LABELS[f.field_type] || f.field_type}
                          </Badge>
                          {f.category && (
                            <Badge variant="outline" className="text-xs">{f.category}</Badge>
                          )}
                          {(f.is_required || f.properties?.required) && (
                            <Badge variant="destructive" className="text-xs">필수</Badge>
                          )}
                        </div>
                        {(f.description || f.placeholder) && (
                          <p className="text-sm text-muted-foreground mb-2 truncate">
                            {f.description || f.placeholder}
                          </p>
                        )}
                        <div className="flex items-center gap-4 text-xs text-muted-foreground">
                          {f.default_value && (
                            <span>기본값: {f.default_value}</span>
                          )}
                          {f.options && f.options.length > 0 && (
                            <span>{f.options.length}개 옵션</span>
                          )}
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}

          {/* Usage Info Panel */}
          {selectedFieldId && (
            <div className="mt-4 p-4 bg-gray-50 dark:bg-gray-900 rounded-lg border">
              <div className="flex items-center gap-2 mb-2">
                <Info className="h-4 w-4 text-blue-500" />
                <Label className="font-medium">사용처 정보</Label>
              </div>
              {isLoadingUsage ? (
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <Loader2 className="h-4 w-4 animate-spin" />
                  <span>사용처를 확인하는 중...</span>
                </div>
              ) : usageInfo ? (
                <div className="text-sm space-y-1">
                  <p>총 {usageInfo.total_usage_count}개 섹션에서 사용 중</p>
                  {usageInfo.linked_sections.length > 0 && (
                    <div className="flex flex-wrap gap-1 mt-2">
                      {usageInfo.linked_sections.slice(0, 5).map(section => (
                        <Badge key={section.id} variant="outline" className="text-xs">
                          {section.title}
                        </Badge>
                      ))}
                      {usageInfo.linked_sections.length > 5 && (
                        <Badge variant="outline" className="text-xs">
                          +{usageInfo.linked_sections.length - 5}개 더
                        </Badge>
                      )}
                    </div>
                  )}
                </div>
              ) : (
                <p className="text-sm text-muted-foreground">
                  이 필드를 선택하면 섹션에 연결됩니다.
                </p>
              )}
            </div>
          )}
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={handleClose}>취소</Button>
          <Button
            onClick={() => {
              onImport();
              handleClose();
            }}
            disabled={!selectedFieldId || isLoading}
          >
            불러오기
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}