'use client';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Plus, X, Edit, Trash2, Check } from 'lucide-react';
import { toast } from 'sonner';
import type { ItemPage, ItemSection, ItemMasterField } from '@/contexts/ItemMasterContext';
import { ConditionalDisplayUI, type ConditionalFieldConfig } from '../components/ConditionalDisplayUI';
import { fieldService } from '../services';

// 입력 타입 정의
export type InputType = 'textbox' | 'dropdown' | 'checkbox' | 'number' | 'date' | 'textarea';

// 입력 모드 타입: 'new'/'existing' 또는 'custom'/'master' 모두 지원
type FieldInputModeType = 'new' | 'existing' | 'custom' | 'master';

// 텍스트박스 칼럼 타입 (단순 구조)
interface OptionColumn {
  id: string;
  name: string;
  key: string;
}

// 유연한 조건부 필드 설정 타입
interface FlexibleConditionField {
  fieldId?: string;
  fieldKey?: string;
  fieldName?: string;
  operator?: string;
  value?: string;
  expectedValue?: string;
  logicOperator?: 'AND' | 'OR';
}

const INPUT_TYPE_OPTIONS: Array<{ value: InputType; label: string }> = [
  { value: 'textbox', label: '텍스트박스' },
  { value: 'dropdown', label: '드롭다운' },
  { value: 'checkbox', label: '체크박스' },
  { value: 'number', label: '숫자' },
  { value: 'date', label: '날짜' },
  { value: 'textarea', label: '텍스트영역' }
];

interface FieldDialogProps {
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  editingFieldId: number | null;
  setEditingFieldId: (id: number | null) => void;
  // 'new'/'existing' 또는 'custom'/'master' 모두 지원
  fieldInputMode: FieldInputModeType;
  setFieldInputMode: (mode: FieldInputModeType) => void;
  showMasterFieldList: boolean;
  setShowMasterFieldList: (show: boolean) => void;
  // string 또는 number | null 모두 지원
  selectedMasterFieldId: string | number | null;
  setSelectedMasterFieldId: (id: string | number | null) => void;
  textboxColumns: OptionColumn[];
  setTextboxColumns: React.Dispatch<React.SetStateAction<OptionColumn[]>>;
  newFieldConditionEnabled: boolean;
  setNewFieldConditionEnabled: (enabled: boolean) => void;
  newFieldConditionTargetType: 'field' | 'section';
  setNewFieldConditionTargetType: (type: 'field' | 'section') => void;
  // 유연한 조건부 필드 설정 - ConditionalFieldConfig 또는 ConditionField 모두 지원
  newFieldConditionFields: FlexibleConditionField[] | ConditionalFieldConfig[];
  setNewFieldConditionFields: React.Dispatch<React.SetStateAction<FlexibleConditionField[]>> | React.Dispatch<React.SetStateAction<ConditionalFieldConfig[]>>;
  // 유연한 섹션 조건 - string[] 또는 ConditionSection[] 모두 지원
  newFieldConditionSections: string[] | Array<{ sectionId?: string; sectionTitle?: string; operator?: string; value?: string; logicOperator?: 'AND' | 'OR' }>;
  setNewFieldConditionSections: React.Dispatch<React.SetStateAction<string[]>> | React.Dispatch<React.SetStateAction<Array<{ sectionId?: string; sectionTitle?: string; operator?: string; value?: string; logicOperator?: 'AND' | 'OR' }>>>;
  tempConditionValue: string;
  setTempConditionValue: (value: string) => void;
  newFieldName: string;
  setNewFieldName: (name: string) => void;
  newFieldKey: string;
  setNewFieldKey: (key: string) => void;
  // string 타입으로 유연하게 처리
  newFieldInputType: string;
  setNewFieldInputType: (type: string) => void;
  newFieldRequired: boolean;
  setNewFieldRequired: (required: boolean) => void;
  newFieldDescription: string;
  setNewFieldDescription: (description: string) => void;
  // string 또는 string[] 모두 지원
  newFieldOptions: string | string[];
  setNewFieldOptions: ((options: string | string[]) => void) | React.Dispatch<React.SetStateAction<string[]>> | React.Dispatch<React.SetStateAction<string>>;
  selectedSectionForField: ItemSection | null;
  selectedPage: ItemPage | null;
  itemMasterFields: ItemMasterField[];
  handleAddField: () => void;
  setIsColumnDialogOpen: (open: boolean) => void;
  setEditingColumnId: (id: string | null) => void;
  setColumnName: (name: string) => void;
  setColumnKey: (key: string) => void;
}

export function FieldDialog({
  isOpen,
  onOpenChange,
  editingFieldId,
  setEditingFieldId,
  fieldInputMode,
  setFieldInputMode,
  showMasterFieldList,
  setShowMasterFieldList,
  selectedMasterFieldId,
  setSelectedMasterFieldId,
  textboxColumns,
  setTextboxColumns,
  newFieldConditionEnabled,
  setNewFieldConditionEnabled,
  newFieldConditionTargetType,
  setNewFieldConditionTargetType,
  newFieldConditionFields,
  setNewFieldConditionFields,
  newFieldConditionSections: _newFieldConditionSections,
  setNewFieldConditionSections,
  tempConditionValue,
  setTempConditionValue,
  newFieldName,
  setNewFieldName,
  newFieldKey,
  setNewFieldKey,
  newFieldInputType,
  setNewFieldInputType,
  newFieldRequired,
  setNewFieldRequired,
  newFieldDescription,
  setNewFieldDescription,
  newFieldOptions,
  setNewFieldOptions,
  selectedSectionForField,
  selectedPage,
  itemMasterFields,
  handleAddField,
  setIsColumnDialogOpen,
  setEditingColumnId,
  setColumnName,
  setColumnKey,
}: FieldDialogProps) {
  const [isSubmitted, setIsSubmitted] = useState(false);

  // 입력 모드 정규화: 'new' → 'custom', 'existing' → 'master'
  const normalizedInputMode =
    fieldInputMode === 'new' ? 'custom' :
    fieldInputMode === 'existing' ? 'master' :
    fieldInputMode;

  const isCustomMode = normalizedInputMode === 'custom';
  const isMasterMode = normalizedInputMode === 'master';

  // 옵션을 문자열로 변환하여 처리
  const optionsString = Array.isArray(newFieldOptions) ? newFieldOptions.join(', ') : newFieldOptions;

  // setNewFieldOptions 래퍼 - union type 호환성 해결
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const handleSetNewFieldOptions = (options: string | string[]) => (setNewFieldOptions as any)(options);

  // fieldService를 사용한 유효성 검사
  const nameValidation = fieldService.validateFieldName(newFieldName);
  const keyValidation = fieldService.validateFieldKey(newFieldKey);
  const isNameEmpty = !nameValidation.valid;
  const isKeyEmpty = !newFieldKey.trim();
  const isKeyInvalid = newFieldKey.trim() !== '' && !keyValidation.valid;

  const handleClose = () => {
    setIsSubmitted(false);
    onOpenChange(false);
    setEditingFieldId(null);
    setFieldInputMode('custom');
    setShowMasterFieldList(false);
    setSelectedMasterFieldId('');
    setTextboxColumns([]);
    setNewFieldConditionEnabled(false);
    setNewFieldConditionTargetType('field');
    setNewFieldConditionFields([]);
    setNewFieldConditionSections([]);
    setTempConditionValue('');

    // 핵심 입력 필드 초기화 (취소 시에도 이전 데이터 남지 않도록)
    setNewFieldName('');
    setNewFieldKey('');
    setNewFieldInputType('textbox');
    setNewFieldRequired(false);
    handleSetNewFieldOptions('');
    setNewFieldDescription('');
  };

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent className="max-w-2xl max-h-[90vh] flex flex-col p-0">
        <DialogHeader className="sticky top-0 bg-white z-10 px-6 py-4 border-b">
          <DialogTitle>{editingFieldId ? '항목 수정' : '항목 추가'}</DialogTitle>
          <DialogDescription>
            재사용 가능한 항목을 선택하거나 직접 입력하세요
          </DialogDescription>
        </DialogHeader>
        <div className="flex-1 overflow-y-auto px-6 py-4 space-y-4">
        {/* 입력 모드 선택 (편집 시에는 표시 안 함) */}
        {!editingFieldId && (
          <div className="flex gap-2 p-1 bg-gray-100 rounded">
            <Button
              variant={isCustomMode ? 'default' : 'ghost'}
              size="sm"
              onClick={() => setFieldInputMode('custom')}
              className="flex-1"
            >
              직접 입력
            </Button>
            <Button
              variant={isMasterMode ? 'default' : 'ghost'}
              size="sm"
              onClick={() => {
                setFieldInputMode('master');
                setShowMasterFieldList(true);
              }}
              className="flex-1"
            >
              항목 선택
            </Button>
          </div>
        )}

        {/* 항목 목록 */}
        {isMasterMode && !editingFieldId && showMasterFieldList && (
          <div className="border rounded p-3 space-y-2 max-h-[400px] overflow-y-auto">
            <div className="flex items-center justify-between mb-2">
              <Label>항목 목록</Label>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setShowMasterFieldList(false)}
              >
                <X className="h-4 w-4" />
              </Button>
            </div>
            {itemMasterFields.length === 0 ? (
              <p className="text-sm text-muted-foreground text-center py-4">
                등록된 항목이 없습니다
              </p>
            ) : (
              <div className="space-y-2">
                {itemMasterFields.map((field, index) => (
                  <div
                    key={`dialog-${field.id}-${index}`}
                    className={`p-3 border rounded cursor-pointer transition-colors ${
                      selectedMasterFieldId === String(field.id)
                        ? 'bg-blue-50 border-blue-300'
                        : 'hover:bg-gray-50'
                    }`}
                    onClick={() => {
                      setSelectedMasterFieldId(String(field.id));
                      setNewFieldName(field.field_name);
                      setNewFieldKey(field.id.toString());
                      setNewFieldInputType(field.field_type);
                      setNewFieldRequired(field.properties?.required || false);
                      setNewFieldDescription(field.description || '');
                      // options는 {label, value}[] 배열이므로 label만 추출
                      handleSetNewFieldOptions(field.options?.map(opt => opt.label).join(', ') || '');
                      if (field.properties?.multiColumn && field.properties?.columnNames) {
                        setTextboxColumns(
                          field.properties.columnNames.map((name: string, idx: number) => ({
                            id: `col-${idx}`,
                            name,
                            key: `column${idx + 1}`
                          }))
                        );
                      }
                    }}
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <span className="font-medium">{field.field_name}</span>
                          <Badge variant="outline" className="text-xs">
                            {INPUT_TYPE_OPTIONS.find(o => o.value === field.field_type)?.label || field.field_type}
                          </Badge>
                          {field.properties?.required && (
                            <Badge variant="destructive" className="text-xs">필수</Badge>
                          )}
                        </div>
                        {field.description && (
                          <p className="text-xs text-muted-foreground mt-1">{field.description}</p>
                        )}
                        {field.category && (
                          <div className="flex gap-1 mt-1">
                            <Badge variant="secondary" className="text-xs">
                              {field.category}
                            </Badge>
                          </div>
                        )}
                      </div>
                      {selectedMasterFieldId === String(field.id) && (
                        <Check className="h-5 w-5 text-blue-600" />
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {/* 직접 입력 폼 */}
        {(isCustomMode || editingFieldId) && (
          <>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <Label>항목명 *</Label>
                <Input
                  value={newFieldName}
                  onChange={(e) => setNewFieldName(e.target.value)}
                  placeholder="예: 품목명"
                  className={isSubmitted && isNameEmpty ? 'border-red-500 focus-visible:ring-red-500' : ''}
                />
                {isSubmitted && isNameEmpty && (
                  <p className="text-xs text-red-500 mt-1">항목명을 입력해주세요</p>
                )}
              </div>
              <div>
                <Label>필드 키 *</Label>
                <Input
                  value={newFieldKey}
                  onChange={(e) => setNewFieldKey(e.target.value)}
                  placeholder="예: itemName"
                  className={(isSubmitted && isKeyEmpty) || isKeyInvalid ? 'border-red-500 focus-visible:ring-red-500' : ''}
                />
                {isSubmitted && isKeyEmpty && (
                  <p className="text-xs text-red-500 mt-1">필드 키를 입력해주세요</p>
                )}
                {isKeyInvalid && (
                  <p className="text-xs text-red-500 mt-1">영문으로 시작하고, 영문/숫자/언더스코어(_)만 사용 가능합니다</p>
                )}
              </div>
            </div>

            <div>
              <Label>입력방식 *</Label>
              <Select value={newFieldInputType} onValueChange={(v) => setNewFieldInputType(v as InputType)}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {INPUT_TYPE_OPTIONS.map(opt => (
                    <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {newFieldInputType === 'dropdown' && (
              <div>
                <Label>드롭다운 옵션</Label>
                <Input
                  value={optionsString}
                  onChange={(e) => handleSetNewFieldOptions(e.target.value)}
                  placeholder="옵션1, 옵션2, 옵션3 (쉼표로 구분)"
                />
              </div>
            )}

            {/* 텍스트박스 컬럼 관리 */}
            {newFieldInputType === 'textbox' && (
              <div className="border rounded p-3 space-y-3">
                <div className="flex items-center justify-between">
                  <Label>텍스트박스 컬럼 관리</Label>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => {
                      setIsColumnDialogOpen(true);
                      setEditingColumnId(null);
                      setColumnName('');
                      setColumnKey('');
                    }}
                  >
                    <Plus className="h-4 w-4 mr-1" />
                    컬럼 추가
                  </Button>
                </div>
                {textboxColumns.length > 0 ? (
                  <div className="space-y-2">
                    {textboxColumns.map((col, index) => (
                      <div key={col.id} className="flex items-center gap-2 p-2 bg-gray-50 rounded">
                        <span className="text-sm flex-1">
                          {index + 1}. {col.name} ({col.key})
                        </span>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            setEditingColumnId(col.id);
                            setColumnName(col.name);
                            setColumnKey(col.key);
                            setIsColumnDialogOpen(true);
                          }}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => {
                            setTextboxColumns(prev => prev.filter(c => c.id !== col.id));
                            toast.success('컬럼이 삭제되었습니다');
                          }}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    ))}
                  </div>
                ) : (
                  <p className="text-sm text-muted-foreground text-center py-2">
                    추가된 컬럼이 없습니다
                  </p>
                )}
              </div>
            )}

            <div>
              <Label>설명 (선택)</Label>
              <Textarea
                value={newFieldDescription}
                onChange={(e) => setNewFieldDescription(e.target.value)}
                placeholder="항목에 대한 설명"
              />
            </div>

            <div className="flex items-center gap-2">
              <Switch checked={newFieldRequired} onCheckedChange={setNewFieldRequired} />
              <Label>필수 항목</Label>
            </div>
          </>
        )}

        {/* 조건부 표시 설정 - 모든 입력방식에서 사용 가능 */}
        {(isCustomMode || editingFieldId) && (
          <ConditionalDisplayUI
            newFieldConditionEnabled={newFieldConditionEnabled}
            setNewFieldConditionEnabled={setNewFieldConditionEnabled}
            newFieldConditionTargetType={newFieldConditionTargetType}
            setNewFieldConditionTargetType={setNewFieldConditionTargetType}
            newFieldConditionFields={newFieldConditionFields as ConditionalFieldConfig[]}
            setNewFieldConditionFields={setNewFieldConditionFields as (value: ConditionalFieldConfig[] | ((prev: ConditionalFieldConfig[]) => ConditionalFieldConfig[])) => void}
            tempConditionValue={tempConditionValue}
            setTempConditionValue={setTempConditionValue}
            newFieldKey={newFieldKey}
            newFieldInputType={newFieldInputType as InputType}
            selectedPage={selectedPage}
            selectedSectionForField={selectedSectionForField}
            editingFieldId={editingFieldId}
            INPUT_TYPE_OPTIONS={INPUT_TYPE_OPTIONS}
          />
        )}
        </div>
        <DialogFooter className="shrink-0 bg-white z-10 px-6 py-4 border-t">
          <Button variant="outline" onClick={handleClose}>취소</Button>
          <Button onClick={async () => {
            setIsSubmitted(true);
            // 2025-11-28: field_key validation 추가
            const shouldValidate = isCustomMode || editingFieldId;
            if (shouldValidate && (isNameEmpty || isKeyEmpty || isKeyInvalid)) {
              return;
            }
            await handleAddField();
            setIsSubmitted(false);
          }}>저장</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}