'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 { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';

const ITEM_TYPE_OPTIONS = [
  { value: 'product', label: '제품' },
  { value: 'part', label: '부품' },
  { value: 'material', label: '자재' },
  { value: 'assembly', label: '조립품' },
];

interface SectionTemplateDialogProps {
  isSectionTemplateDialogOpen: boolean;
  setIsSectionTemplateDialogOpen: (open: boolean) => void;
  editingSectionTemplateId: number | null;
  setEditingSectionTemplateId: (id: number | null) => void;
  newSectionTemplateTitle: string;
  setNewSectionTemplateTitle: (title: string) => void;
  newSectionTemplateDescription: string;
  setNewSectionTemplateDescription: (description: string) => void;
  // string 또는 string[] 모두 지원
  newSectionTemplateCategory: string | string[];
  setNewSectionTemplateCategory: (category: string | string[]) => void;
  newSectionTemplateType: 'fields' | 'bom';
  setNewSectionTemplateType: (type: 'fields' | 'bom') => void;
  handleUpdateSectionTemplate: () => void;
  handleAddSectionTemplate: () => void;
}

export function SectionTemplateDialog({
  isSectionTemplateDialogOpen,
  setIsSectionTemplateDialogOpen,
  editingSectionTemplateId,
  setEditingSectionTemplateId,
  newSectionTemplateTitle,
  setNewSectionTemplateTitle,
  newSectionTemplateDescription,
  setNewSectionTemplateDescription,
  newSectionTemplateCategory,
  setNewSectionTemplateCategory,
  newSectionTemplateType,
  setNewSectionTemplateType,
  handleUpdateSectionTemplate,
  handleAddSectionTemplate,
}: SectionTemplateDialogProps) {
  const [isSubmitted, setIsSubmitted] = useState(false);

  // 카테고리 정규화: string → string[] 변환
  const categoryArray = Array.isArray(newSectionTemplateCategory)
    ? newSectionTemplateCategory
    : newSectionTemplateCategory ? [newSectionTemplateCategory] : [];

  // 유효성 검사
  const isTitleEmpty = !newSectionTemplateTitle.trim();

  const handleClose = () => {
    setIsSectionTemplateDialogOpen(false);
    setEditingSectionTemplateId(null);
    setNewSectionTemplateTitle('');
    setNewSectionTemplateDescription('');
    setNewSectionTemplateCategory([]);
    setNewSectionTemplateType('fields');
    setIsSubmitted(false);
  };

  const handleSubmit = () => {
    setIsSubmitted(true);
    if (!isTitleEmpty) {
      if (editingSectionTemplateId) {
        handleUpdateSectionTemplate();
      } else {
        handleAddSectionTemplate();
      }
      setIsSubmitted(false);
    }
  };

  return (
    <Dialog open={isSectionTemplateDialogOpen} onOpenChange={(open) => {
      if (!open) handleClose();
      else setIsSectionTemplateDialogOpen(open);
    }}>
      <DialogContent className="max-w-[95vw] sm:max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{editingSectionTemplateId ? '섹션 수정' : '섹션 추가'}</DialogTitle>
          <DialogDescription>
            여러 페이지에서 재사용할 수 있는 섹션을 생성합니다
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4">
          <div>
            <Label>섹션 제목 *</Label>
            <Input
              value={newSectionTemplateTitle}
              onChange={(e) => setNewSectionTemplateTitle(e.target.value)}
              placeholder="예: 기본 정보"
              className={isSubmitted && isTitleEmpty ? 'border-red-500 focus-visible:ring-red-500' : ''}
            />
            {isSubmitted && isTitleEmpty && (
              <p className="text-xs text-red-500 mt-1">섹션 제목을 입력해주세요</p>
            )}
          </div>

          <div>
            <Label>설명 (선택)</Label>
            <Textarea
              value={newSectionTemplateDescription}
              onChange={(e) => setNewSectionTemplateDescription(e.target.value)}
              placeholder="섹션에 대한 설명"
            />
          </div>

          <div>
            <Label>섹션 타입 *</Label>
            <Select
              value={newSectionTemplateType}
              onValueChange={(val) => setNewSectionTemplateType(val as 'fields' | 'bom')}
              disabled={!!editingSectionTemplateId}
            >
              <SelectTrigger>
                <SelectValue placeholder="섹션 타입을 선택하세요" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="fields">일반 필드</SelectItem>
                <SelectItem value="bom">BOM (부품 구성)</SelectItem>
              </SelectContent>
            </Select>
            <p className="text-xs text-gray-500 mt-1">
              {editingSectionTemplateId
                ? '※ 템플릿 타입은 수정할 수 없습니다.'
                : '일반 필드: 텍스트, 드롭다운 등의 항목 관리 | BOM: 하위 품목 구성 관리'}
            </p>
          </div>

          <div>
            <Label>적용 카테고리 (선택)</Label>
            <div className="grid grid-cols-3 gap-2 mt-2">
              {ITEM_TYPE_OPTIONS.map((type) => (
                <div key={type.value} className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    id={`cat-${type.value}`}
                    checked={categoryArray.includes(type.value)}
                    onChange={(e) => {
                      if (e.target.checked) {
                        setNewSectionTemplateCategory([...categoryArray, type.value]);
                      } else {
                        setNewSectionTemplateCategory(categoryArray.filter(c => c !== type.value));
                      }
                    }}
                    className="rounded"
                  />
                  <label htmlFor={`cat-${type.value}`} className="text-sm cursor-pointer">
                    {type.label}
                  </label>
                </div>
              ))}
            </div>
            <p className="text-xs text-muted-foreground mt-2">
              선택하지 않으면 모든 카테고리에서 사용 가능합니다
            </p>
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={handleClose}>취소</Button>
          <Button onClick={handleSubmit}>
            {editingSectionTemplateId ? '수정' : '추가'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
