'use client';

import { useState } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';

// 유연한 타입 정의 - 다양한 소스에서 사용 가능
interface OptionColumn {
  id: string;
  name: string;
  key: string;
  type: string;
  required: boolean;
}

interface AttributeSubTab {
  id: string;
  label: string;
  key: string;
  order: number;
  isDefault?: boolean;
}

interface OptionDialogProps {
  isOpen: boolean;
  setIsOpen: (open: boolean) => void;
  newOptionValue: string;
  setNewOptionValue: (value: string) => void;
  newOptionLabel: string;
  setNewOptionLabel: (label: string) => void;
  newOptionColumnValues: Record<string, string>;
  setNewOptionColumnValues: (values: Record<string, string>) => void;
  // string 타입으로 유연하게 처리 (textbox, number, dropdown, checkbox, date, textarea)
  newOptionInputType: string;
  setNewOptionInputType: (type: string) => void;
  newOptionRequired: boolean;
  setNewOptionRequired: (required: boolean) => void;
  // string[] 또는 string 모두 지원
  newOptionOptions: string | string[];
  setNewOptionOptions: (options: string | string[]) => void;
  newOptionPlaceholder: string;
  setNewOptionPlaceholder: (placeholder: string) => void;
  newOptionDefaultValue: string;
  setNewOptionDefaultValue: (defaultValue: string) => void;
  editingOptionType: string | null;
  attributeSubTabs: AttributeSubTab[];
  attributeColumns: Record<string, OptionColumn[]>;
  handleAddOption: () => void;
}

export function OptionDialog({
  isOpen,
  setIsOpen,
  newOptionValue,
  setNewOptionValue,
  newOptionLabel,
  setNewOptionLabel,
  newOptionColumnValues,
  setNewOptionColumnValues,
  newOptionInputType,
  setNewOptionInputType,
  newOptionRequired,
  setNewOptionRequired,
  newOptionOptions,
  setNewOptionOptions,
  newOptionPlaceholder,
  setNewOptionPlaceholder,
  newOptionDefaultValue,
  setNewOptionDefaultValue,
  editingOptionType,
  attributeSubTabs,
  attributeColumns,
  handleAddOption,
}: OptionDialogProps) {
  const [isSubmitted, setIsSubmitted] = useState(false);

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

  // 유효성 검사
  const isValueEmpty = !newOptionValue.trim();
  const isLabelEmpty = !newOptionLabel.trim();
  const isDropdownOptionsEmpty = newOptionInputType === 'dropdown' && !optionsString.trim();

  const handleClose = () => {
    setIsOpen(false);
    setNewOptionValue('');
    setNewOptionLabel('');
    setNewOptionColumnValues({});
    setNewOptionInputType('textbox');
    setNewOptionRequired(false);
    setNewOptionOptions('');
    setNewOptionPlaceholder('');
    setNewOptionDefaultValue('');
    setIsSubmitted(false);
  };

  const handleSubmit = () => {
    setIsSubmitted(true);
    if (!isValueEmpty && !isLabelEmpty && !isDropdownOptionsEmpty) {
      handleAddOption();
      setIsSubmitted(false);
    }
  };

  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>
            {editingOptionType === 'unit' && '단위'}
            {editingOptionType === 'material' && '재질'}
            {editingOptionType === 'surface' && '표면처리'}
            {editingOptionType && !['unit', 'material', 'surface'].includes(editingOptionType) &&
              (attributeSubTabs.find(t => t.key === editingOptionType)?.label || '속성')}
            {' '}속성의 항목을 추가합니다. 입력방식과 속성을 설정하세요.
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4">
          {/* 기본 정보 */}
          <div className="border rounded-lg p-4 space-y-3 bg-blue-50">
            <h4 className="font-medium text-sm">기본 정보</h4>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label>값 (Value) *</Label>
                <Input
                  value={newOptionValue}
                  onChange={(e) => setNewOptionValue(e.target.value)}
                  placeholder="예: kg, stainless"
                  className={isSubmitted && isValueEmpty ? 'border-red-500 focus-visible:ring-red-500' : ''}
                />
                {isSubmitted && isValueEmpty && (
                  <p className="text-xs text-red-500 mt-1">값을 입력해주세요</p>
                )}
              </div>
              <div>
                <Label>라벨 (표시명) *</Label>
                <Input
                  value={newOptionLabel}
                  onChange={(e) => setNewOptionLabel(e.target.value)}
                  placeholder="예: 킬로그램, 스테인리스"
                  className={isSubmitted && isLabelEmpty ? 'border-red-500 focus-visible:ring-red-500' : ''}
                />
                {isSubmitted && isLabelEmpty && (
                  <p className="text-xs text-red-500 mt-1">라벨을 입력해주세요</p>
                )}
              </div>
            </div>
          </div>

          {/* 입력 방식 설정 */}
          <div className="border rounded-lg p-4 space-y-3">
            <h4 className="font-medium text-sm">입력 방식 설정</h4>
            <div>
              <Label>입력 방식 *</Label>
              <Select value={newOptionInputType} onValueChange={(v: any) => setNewOptionInputType(v)}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="textbox">텍스트박스</SelectItem>
                  <SelectItem value="number">숫자</SelectItem>
                  <SelectItem value="dropdown">드롭다운</SelectItem>
                  <SelectItem value="checkbox">체크박스</SelectItem>
                  <SelectItem value="date">날짜</SelectItem>
                  <SelectItem value="textarea">텍스트영역</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {newOptionInputType === 'dropdown' && (
              <div>
                <Label className="flex items-center gap-1">
                  드롭다운 옵션 <span className="text-red-500">*</span>
                </Label>
                <Input
                  value={optionsString}
                  onChange={(e) => setNewOptionOptions(e.target.value)}
                  placeholder="옵션1, 옵션2, 옵션3 (쉼표로 구분)"
                  className={isSubmitted && isDropdownOptionsEmpty ? 'border-red-500 focus-visible:ring-red-500' : ''}
                />
                {isSubmitted && isDropdownOptionsEmpty ? (
                  <p className="text-xs text-red-500 mt-1">드롭다운 옵션을 입력해주세요</p>
                ) : (
                  <p className="text-xs text-muted-foreground mt-1">
                    쉼표로 구분하여 여러 옵션을 입력하세요
                  </p>
                )}
              </div>
            )}

            <div>
              <Label>플레이스홀더 (선택)</Label>
              <Input
                value={newOptionPlaceholder}
                onChange={(e) => setNewOptionPlaceholder(e.target.value)}
                placeholder="예: 값을 입력하세요"
              />
            </div>

            <div>
              <Label>기본값 (선택)</Label>
              <Input
                value={newOptionDefaultValue}
                onChange={(e) => setNewOptionDefaultValue(e.target.value)}
                placeholder={
                  newOptionInputType === 'checkbox' ? 'true 또는 false' :
                  newOptionInputType === 'number' ? '숫자' :
                  '기본값'
                }
              />
            </div>

            <div className="flex items-center gap-2">
              <Switch checked={newOptionRequired} onCheckedChange={setNewOptionRequired} />
              <Label>필수 입력</Label>
            </div>
          </div>

          {/* 추가 칼럼 (기존 칼럼 시스템과 호환) */}
          {editingOptionType && attributeColumns[editingOptionType]?.length > 0 && (
            <div className="border rounded-lg p-4 space-y-3">
              <h4 className="font-medium text-sm">추가 칼럼</h4>
              <div className="grid grid-cols-2 gap-4">
                {attributeColumns[editingOptionType].map((column) => (
                  <div key={column.id}>
                    <Label className="flex items-center gap-1">
                      {column.name}
                      {column.required && <span className="text-red-500">*</span>}
                    </Label>
                    <Input
                      type={column.type === 'number' ? 'number' : 'text'}
                      value={newOptionColumnValues[column.key] || ''}
                      onChange={(e) => setNewOptionColumnValues({
                        ...newOptionColumnValues,
                        [column.key]: e.target.value
                      })}
                      placeholder={`${column.name} 입력`}
                    />
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={handleClose}>취소</Button>
          <Button onClick={handleSubmit}>추가</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
