'use client';

import { useState, useEffect, useCallback } from 'react';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { getApprovalFormsByCategory } from './form-actions';
import type { ApprovalFormCategory, ApprovalFormItem } from './form-actions';

interface FormSelectorProps {
  selectedFormId?: number;
  selectedFormCode?: string;
  onFormSelect: (form: { id: number; code: string; name: string; category: string } | null) => void;
  disabled?: boolean;
}

/**
 * 2단계 양식 선택 컴포넌트
 * 1단계: 카테고리 선택 (재무, 인사, 총무 등)
 * 2단계: 양식 선택 (카테고리 내 양식 목록)
 */
export function FormSelector({ selectedFormId, selectedFormCode, onFormSelect, disabled }: FormSelectorProps) {
  const [categories, setCategories] = useState<ApprovalFormCategory[]>([]);
  const [selectedCategory, setSelectedCategory] = useState<string>('');
  const [isLoading, setIsLoading] = useState(true);

  // 양식 목록 로드
  useEffect(() => {
    const load = async () => {
      setIsLoading(true);
      const result = await getApprovalFormsByCategory();
      if (result.success) {
        setCategories(result.data);

        // 기존 선택값 복원
        if (selectedFormCode || selectedFormId) {
          for (const cat of result.data) {
            const found = cat.forms.find(
              f => f.id === selectedFormId || f.code === selectedFormCode
            );
            if (found) {
              setSelectedCategory(cat.category);
              break;
            }
          }
        }
      }
      setIsLoading(false);
    };
    load();
  }, [selectedFormId, selectedFormCode]);

  // 현재 카테고리의 양식 목록
  const currentForms = categories.find(c => c.category === selectedCategory)?.forms || [];

  // 카테고리 변경
  const handleCategoryChange = useCallback((category: string) => {
    setSelectedCategory(category);
    onFormSelect(null); // 카테고리 변경 시 양식 선택 초기화
  }, [onFormSelect]);

  // 양식 선택
  const handleFormSelect = useCallback((formId: string) => {
    const form = currentForms.find(f => String(f.id) === formId);
    if (form) {
      onFormSelect({
        id: form.id,
        code: form.code,
        name: form.name,
        category: form.category,
      });
    }
  }, [currentForms, onFormSelect]);

  if (isLoading) {
    return (
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div className="space-y-2">
          <Label>문서 분류</Label>
          <Select disabled><SelectTrigger><SelectValue placeholder="로딩 중..." /></SelectTrigger></Select>
        </div>
        <div className="space-y-2">
          <Label>양식 선택</Label>
          <Select disabled><SelectTrigger><SelectValue placeholder="로딩 중..." /></SelectTrigger></Select>
        </div>
      </div>
    );
  }

  return (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
      {/* 1단계: 카테고리 선택 */}
      <div className="space-y-2">
        <Label>문서 분류</Label>
        <Select
          value={selectedCategory}
          onValueChange={handleCategoryChange}
          disabled={disabled}
        >
          <SelectTrigger>
            <SelectValue placeholder="분류 선택" />
          </SelectTrigger>
          <SelectContent>
            {categories.map((cat) => (
              <SelectItem key={cat.category} value={cat.category}>
                {cat.categoryLabel} ({cat.forms.length})
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* 2단계: 양식 선택 */}
      <div className="space-y-2">
        <Label>양식 선택</Label>
        <Select
          key={`form-${selectedCategory}-${selectedFormId}`}
          value={selectedFormId ? String(selectedFormId) : ''}
          onValueChange={handleFormSelect}
          disabled={disabled || !selectedCategory}
        >
          <SelectTrigger>
            <SelectValue placeholder={selectedCategory ? '양식 선택' : '분류를 먼저 선택하세요'} />
          </SelectTrigger>
          <SelectContent>
            {currentForms.map((form) => (
              <SelectItem key={form.id} value={String(form.id)}>
                {form.name}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
    </div>
  );
}
