'use client';

/**
 * 작업지시 등록 페이지
 * API 연동 완료 (2025-12-26)
 * IntegratedDetailTemplate 마이그레이션 (2025-01-20)
 */

import { useState, useEffect, useCallback } from 'react';
import { invalidateDashboard } from '@/lib/dashboard-invalidation';
import { useRouter } from 'next/navigation';
import { FileText, X, Edit, Loader2, Plus, Search, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { DatePicker } from '@/components/ui/date-picker';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { SalesOrderSelectModal } from './SalesOrderSelectModal';
import { AssigneeSelectModal } from './AssigneeSelectModal';
import { toast } from 'sonner';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { createWorkOrder, getProcessOptions, searchItemsForWorkOrder, type ProcessOption, type ManualItemOption } from './actions';
import { type SalesOrder } from './types';
import { workOrderCreateConfig } from './workOrderConfig';

import { useDevFill } from '@/components/dev';
import { generateWorkOrderData } from '@/components/dev/generators/workOrderData';

// 수동 등록 품목
interface ManualItem {
  item_id?: number;
  item_name: string;
  specification: string;
  quantity: number;
  unit: string;
}

type RegistrationMode = 'linked' | 'manual';

interface FormData {
  // 수주 정보
  selectedOrder: SalesOrder | null;
  splitOption: 'all' | 'partial';

  // 기본 정보
  client: string;
  projectName: string;
  orderNo: string;
  itemCount: number;

  // 작업지시 정보
  processId: number | null;  // 공정 ID (FK → processes.id)
  shipmentDate: string;
  priority: number;
  assignees: string[];

  // 비고
  note: string;
}

const initialFormData: FormData = {
  selectedOrder: null,
  splitOption: 'all',
  client: '',
  projectName: '',
  orderNo: '',
  itemCount: 0,
  processId: null,
  shipmentDate: '',
  priority: 5,
  assignees: [],
  note: '',
};

export function WorkOrderCreate() {
  const router = useRouter();
  const [mode, setMode] = useState<RegistrationMode>('linked');
  const [formData, setFormData] = useState<FormData>(initialFormData);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isAssigneeModalOpen, setIsAssigneeModalOpen] = useState(false);
  const [assigneeNames, setAssigneeNames] = useState<string[]>([]);
  const [validationErrors, setValidationErrors] = useState<Record<string, string>>({});
  const [, setIsSubmitting] = useState(false);
  const [processOptions, setProcessOptions] = useState<ProcessOption[]>([]);
  const [isLoadingProcesses, setIsLoadingProcesses] = useState(true);

  // 수동 등록 품목 관리
  const [manualItems, setManualItems] = useState<ManualItem[]>([]);
  const [itemSearchQuery, setItemSearchQuery] = useState('');
  const [itemSearchResults, setItemSearchResults] = useState<ManualItemOption[]>([]);
  const [isSearchingItems, setIsSearchingItems] = useState(false);
  const [showItemSearch, setShowItemSearch] = useState(false);

  // 필드 에러 클리어 헬퍼
  const clearFieldError = useCallback((field: string) => {
    if (validationErrors[field]) {
      setValidationErrors(prev => {
        const next = { ...prev };
        delete next[field];
        return next;
      });
    }
  }, [validationErrors]);

  // 공정 옵션 로드
  useEffect(() => {
    async function loadProcessOptions() {
      setIsLoadingProcesses(true);
      const result = await getProcessOptions();
      if (result.success) {
        setProcessOptions(result.data);
        // 첫 번째 공정을 기본값으로 설정
        if (result.data.length > 0 && !formData.processId) {
          setFormData(prev => ({ ...prev, processId: result.data[0].id }));
        }
      } else {
        toast.error(result.error || '공정 목록을 불러오는데 실패했습니다.');
      }
      setIsLoadingProcesses(false);
    }
    loadProcessOptions();
  }, []);

  // DevToolbar 자동 채우기
  useDevFill(
    'workOrder',
    useCallback(async () => {
      // 공정 옵션 직접 가져오기 (state가 아직 로딩 전일 수 있음)
      const processResult = await getProcessOptions();
      const processes = processResult.success ? processResult.data : [];

      const sampleData = generateWorkOrderData({ processOptions: processes });

      // 수동 등록 모드로 변경
      setMode('manual');

      // 폼 데이터 채우기
      setFormData(prev => ({
        ...prev,
        client: '테스트 거래처',
        projectName: '테스트 현장',
        orderNo: '',
        itemCount: 0,
        processId: sampleData.processId,
        shipmentDate: sampleData.shipmentDate,
        priority: sampleData.priority,
        note: sampleData.note,
      }));

      toast.success('[Dev] 작업지시 폼이 자동으로 채워졌습니다.');
    }, [])
  );

  // 수주 선택 핸들러
  const handleSelectOrder = (order: SalesOrder) => {
    setFormData({
      ...formData,
      selectedOrder: order,
      client: order.client,
      projectName: order.projectName,
      orderNo: order.orderNo,
      itemCount: order.itemCount,
    });
    clearFieldError('selectedOrder');
  };

  // 수주 해제
  const handleClearOrder = () => {
    setFormData({
      ...initialFormData,
      processId: formData.processId,
      shipmentDate: formData.shipmentDate,
      priority: formData.priority,
    });
  };

  // 품목 검색 (수동 등록용)
  const handleItemSearch = async (query: string) => {
    setItemSearchQuery(query);
    if (query.length < 1) {
      setItemSearchResults([]);
      return;
    }
    setIsSearchingItems(true);
    const result = await searchItemsForWorkOrder(query, 'BENDING');
    if (result.success) {
      setItemSearchResults(result.data);
    }
    setIsSearchingItems(false);
  };

  // 검색 결과에서 품목 추가
  const handleAddItem = (item: ManualItemOption) => {
    // 이미 추가된 품목인지 확인
    if (manualItems.some(mi => mi.item_id === item.id)) {
      toast.error('이미 추가된 품목입니다.');
      return;
    }
    setManualItems(prev => [...prev, {
      item_id: item.id,
      item_name: item.name,
      specification: item.specification,
      quantity: 1,
      unit: item.unit,
    }]);
    setShowItemSearch(false);
    setItemSearchQuery('');
    setItemSearchResults([]);
    clearFieldError('items');
  };

  // 품목 수량 변경
  const handleItemQtyChange = (index: number, qty: number) => {
    setManualItems(prev => prev.map((item, i) => i === index ? { ...item, quantity: qty } : item));
  };

  // 품목 삭제
  const handleRemoveItem = (index: number) => {
    setManualItems(prev => prev.filter((_, i) => i !== index));
  };

  // 폼 제출
  const handleSubmit = async (): Promise<{ success: boolean; error?: string }> => {
    // Validation 체크
    const errors: Record<string, string> = {};

    if (mode === 'linked') {
      if (!formData.selectedOrder) {
        errors.selectedOrder = '수주를 선택해주세요';
      }
    } else {
      if (!formData.client) {
        errors.client = '발주처를 입력해주세요';
      }
      if (!formData.projectName) {
        errors.projectName = '현장명을 입력해주세요';
      }
      if (manualItems.length === 0) {
        errors.items = '품목을 1개 이상 추가해주세요';
      }
    }

    if (!formData.processId) {
      errors.processId = '공정을 선택해주세요';
    }

    if (!formData.shipmentDate) {
      errors.shipmentDate = '출고예정일을 선택해주세요';
    }

    // 에러가 있으면 상태 업데이트 후 리턴
    if (Object.keys(errors).length > 0) {
      setValidationErrors(errors);
      const firstError = Object.values(errors)[0];
      toast.error(firstError);
      return { success: false, error: '' };
    }

    // 에러 초기화
    setValidationErrors({});
    setIsSubmitting(true);

    try {
      // API 호출
      const result = await createWorkOrder({
        salesOrderId: formData.selectedOrder?.id ? parseInt(formData.selectedOrder.id) : undefined,
        projectName: formData.projectName,
        processId: formData.processId!,  // 공정 ID (FK → processes.id)
        scheduledDate: formData.shipmentDate,
        assigneeIds: formData.assignees.map(id => parseInt(id)),
        note: formData.note || undefined,
        ...(mode === 'manual' && manualItems.length > 0 ? {
          items: manualItems.map(item => ({
            item_id: item.item_id,
            item_name: item.item_name,
            specification: item.specification,
            quantity: item.quantity,
            unit: item.unit,
          })),
        } : {}),
      });

      if (!result.success) {
        return { success: false, error: result.error || '작업지시 등록에 실패했습니다.' };
      }
      invalidateDashboard('production');
      return { success: true };
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('[WorkOrderCreate] handleSubmit error:', error);
      const errorMessage = error instanceof Error ? error.message : '작업지시 등록 중 오류가 발생했습니다.';
      return { success: false, error: errorMessage };
    } finally {
      setIsSubmitting(false);
    }
  };

  // 취소
  const handleCancel = () => {
    router.back();
  };

  // 선택된 공정의 코드 가져오기
  const getSelectedProcessCode = (): string => {
    const selectedProcess = processOptions.find(p => p.id === formData.processId);
    return selectedProcess?.processCode || '-';
  };

  // 폼 컨텐츠 렌더링
  const renderFormContent = useCallback(() => (
    <div className="space-y-6">
        {/* 등록 방식 */}
        <section className="bg-white border rounded-lg p-6">
          <h3 className="font-semibold mb-4">등록 방식</h3>
          <RadioGroup
            value={mode}
            onValueChange={(value) => setMode(value as RegistrationMode)}
            className="flex gap-6"
          >
            <div className="flex items-center space-x-2">
              <RadioGroupItem value="linked" id="linked" />
              <Label htmlFor="linked" className="cursor-pointer">
                수주 연동 등록{' '}
                <span className="text-muted-foreground text-sm">
                  (회계확인 완료된 수주에서 불러오기)
                </span>
              </Label>
            </div>
            <div className="flex items-center space-x-2">
              <RadioGroupItem value="manual" id="manual" />
              <Label htmlFor="manual" className="cursor-pointer">
                수동 등록{' '}
                <span className="text-muted-foreground text-sm">
                  (재고생산)
                </span>
              </Label>
            </div>
          </RadioGroup>
        </section>

        {/* 수주 정보 (연동 모드) */}
        {mode === 'linked' && (
          <section className="bg-muted/30 border rounded-lg p-6">
            <h3 className="font-semibold mb-4">수주 정보</h3>
            {!formData.selectedOrder ? (
              <div className={`flex items-center justify-between p-4 bg-white border rounded-lg ${validationErrors.selectedOrder ? 'border-red-500' : ''}`}>
                <div className="flex items-center gap-3">
                  <FileText className="w-5 h-5 text-muted-foreground" />
                  <div>
                    <p className="font-medium">수주에서 불러오기</p>
                    <p className="text-sm text-muted-foreground">
                      회계확인 완료된 수주를 선택하면 정보가 자동으로 채워집니다
                    </p>
                  </div>
                </div>
                <Button variant="outline" onClick={() => setIsModalOpen(true)}>
                  <FileText className="w-4 h-4 mr-1.5" />
                  수주 선택
                </Button>
              </div>
            ) : (
              <div className="p-4 bg-white border rounded-lg">
                <div className="flex items-start justify-between mb-4">
                  <div>
                    <div className="flex items-center gap-2 mb-1">
                      <span className="font-semibold">{formData.selectedOrder.orderNo}</span>
                      <span className="text-sm text-muted-foreground">
                        {formData.selectedOrder.status}에서 불러옴
                      </span>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      {formData.selectedOrder.client} / {formData.selectedOrder.projectName} / {formData.selectedOrder.itemCount}개 품목
                    </p>
                  </div>
                  <div className="flex items-center gap-2">
                    <Button variant="ghost" size="sm" onClick={handleClearOrder}>
                      <X className="w-4 h-4 mr-1" />
                      해제
                    </Button>
                    <Button variant="outline" size="sm" onClick={() => setIsModalOpen(true)}>
                      <Edit className="w-4 h-4 mr-1" />
                      변경
                    </Button>
                  </div>
                </div>

                {/* 분할 선택 */}
                <div className="pt-4 border-t">
                  <h4 className="text-sm font-medium mb-2">분할 선택</h4>
                  <RadioGroup
                    value={formData.splitOption}
                    onValueChange={(value) =>
                      setFormData({ ...formData, splitOption: value as 'all' | 'partial' })
                    }
                    className="flex gap-4"
                  >
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="all" id="split-all" />
                      <Label htmlFor="split-all" className="cursor-pointer">
                        전체 품목
                      </Label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="partial" id="split-partial" />
                      <Label htmlFor="split-partial" className="cursor-pointer">
                        {formData.selectedOrder.orderNo}-01
                      </Label>
                    </div>
                  </RadioGroup>
                </div>
              </div>
            )}
            {validationErrors.selectedOrder && <p className="text-sm text-red-500 mt-1">{validationErrors.selectedOrder}</p>}
          </section>
        )}

        {/* 기본 정보 */}
        <section className="bg-muted/30 border rounded-lg p-6">
          <h3 className="font-semibold mb-4">기본 정보</h3>
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>발주처 *</Label>
              <Input
                value={formData.client}
                onChange={(e) => {
                  setFormData({ ...formData, client: e.target.value });
                  clearFieldError('client');
                }}
                placeholder={mode === 'linked' ? '수주를 선택하면 자동 입력됩니다' : '발주처 입력'}
                disabled={mode === 'linked'}
                className={`bg-white ${validationErrors.client ? 'border-red-500' : ''}`}
              />
              {validationErrors.client && <p className="text-sm text-red-500">{validationErrors.client}</p>}
            </div>
            <div className="space-y-2">
              <Label>현장명 *</Label>
              <Input
                value={formData.projectName}
                onChange={(e) => {
                  setFormData({ ...formData, projectName: e.target.value });
                  clearFieldError('projectName');
                }}
                placeholder={mode === 'linked' ? '수주를 선택하면 자동 입력됩니다' : '현장명 입력'}
                disabled={mode === 'linked'}
                className={`bg-white ${validationErrors.projectName ? 'border-red-500' : ''}`}
              />
              {validationErrors.projectName && <p className="text-sm text-red-500">{validationErrors.projectName}</p>}
            </div>
            <div className="space-y-2">
              <Label>수주번호</Label>
              <Input
                value={formData.orderNo}
                onChange={(e) => setFormData({ ...formData, orderNo: e.target.value })}
                placeholder={mode === 'linked' ? '수주를 선택하면 자동 입력됩니다' : '수주번호 입력'}
                disabled={mode === 'linked'}
                className="bg-white"
              />
            </div>
            <div className="space-y-2">
              <Label>품목수</Label>
              <Input
                value={formData.itemCount || ''}
                onChange={(e) => setFormData({ ...formData, itemCount: parseInt(e.target.value) || 0 })}
                placeholder={mode === 'linked' ? '수주를 선택하면 자동 입력됩니다' : '품목수 입력'}
                disabled={mode === 'linked'}
                className="bg-white"
              />
            </div>
          </div>
        </section>

        {/* 작업지시 정보 */}
        <section className="bg-muted/30 border rounded-lg p-6">
          <h3 className="font-semibold mb-4">작업지시 정보</h3>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>공정구분 *</Label>
              <Select
                value={formData.processId?.toString() || ''}
                onValueChange={(value) => {
                  setFormData({ ...formData, processId: parseInt(value) });
                  clearFieldError('processId');
                }}
                disabled={isLoadingProcesses}
              >
                <SelectTrigger className={`bg-white ${validationErrors.processId ? 'border-red-500' : ''}`}>
                  <SelectValue placeholder={isLoadingProcesses ? '로딩 중...' : '공정을 선택하세요'} />
                </SelectTrigger>
                <SelectContent>
                  {processOptions.map((process) => (
                    <SelectItem key={process.id} value={process.id.toString()}>
                      {process.processName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {validationErrors.processId && <p className="text-sm text-red-500">{validationErrors.processId}</p>}
              <p className="text-xs text-muted-foreground">
                공정코드: {getSelectedProcessCode()}
              </p>
            </div>

            <div className="space-y-2">
              <Label>출고예정일 *</Label>
              <DatePicker
                value={formData.shipmentDate}
                onChange={(date) => {
                  setFormData({ ...formData, shipmentDate: date });
                  clearFieldError('shipmentDate');
                }}
                className={validationErrors.shipmentDate ? 'border-red-500' : ''}
              />
              {validationErrors.shipmentDate && <p className="text-sm text-red-500">{validationErrors.shipmentDate}</p>}
            </div>

            <div className="space-y-2">
              <Label>우선순위 (1=긴급, 9=낮음)</Label>
              <Select
                value={formData.priority.toString()}
                onValueChange={(value) => setFormData({ ...formData, priority: parseInt(value) })}
              >
                <SelectTrigger className="bg-white">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {[1, 2, 3, 4, 5, 6, 7, 8, 9].map((n) => (
                    <SelectItem key={n} value={n.toString()}>
                      {n} {n === 5 ? '(일반)' : n === 1 ? '(긴급)' : ''}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label>담당자 (다중선택 가능)</Label>
              <div
                onClick={() => setIsAssigneeModalOpen(true)}
                className="flex min-h-10 w-full cursor-pointer items-center rounded-md border border-input bg-white px-3 py-2 text-sm ring-offset-background hover:bg-accent/50"
              >
                {assigneeNames.length > 0 ? (
                  <span>{assigneeNames.join(', ')}</span>
                ) : (
                  <span className="text-muted-foreground">담당자를 선택하세요 (팀/개인)</span>
                )}
              </div>
            </div>
          </div>
        </section>

        {/* 품목 (수동 등록 모드) */}
        {mode === 'manual' && (
          <section className="bg-muted/30 border rounded-lg p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-semibold">
                품목 목록
                {manualItems.length > 0 && (
                  <span className="text-sm font-normal text-muted-foreground ml-2">
                    ({manualItems.length}개)
                  </span>
                )}
              </h3>
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() => setShowItemSearch(!showItemSearch)}
              >
                <Plus className="w-4 h-4 mr-1" />
                품목 추가
              </Button>
            </div>

            {/* 품목 검색 */}
            {showItemSearch && (
              <div className="mb-4 p-4 bg-white border rounded-lg space-y-3">
                <div className="flex gap-2">
                  <div className="relative flex-1">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                    <Input
                      value={itemSearchQuery}
                      onChange={(e) => handleItemSearch(e.target.value)}
                      placeholder="절곡품 코드 또는 품목명으로 검색"
                      className="pl-9"
                    />
                  </div>
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => { setShowItemSearch(false); setItemSearchResults([]); setItemSearchQuery(''); }}
                  >
                    <X className="w-4 h-4" />
                  </Button>
                </div>
                {isSearchingItems && (
                  <div className="flex items-center gap-2 text-sm text-muted-foreground py-2">
                    <Loader2 className="w-4 h-4 animate-spin" />
                    검색 중...
                  </div>
                )}
                {itemSearchResults.length > 0 && (
                  <div className="max-h-48 overflow-y-auto border rounded">
                    {itemSearchResults.map((item) => (
                      <button
                        key={item.id}
                        type="button"
                        onClick={() => handleAddItem(item)}
                        className="w-full text-left px-3 py-2 hover:bg-accent text-sm border-b last:border-b-0 flex justify-between items-center"
                      >
                        <div>
                          <span className="font-medium">{item.code}</span>
                          <span className="text-muted-foreground ml-2">{item.name}</span>
                          {item.specification && (
                            <span className="text-muted-foreground ml-1">({item.specification})</span>
                          )}
                        </div>
                        <span className="text-xs text-muted-foreground">{item.unit}</span>
                      </button>
                    ))}
                  </div>
                )}
                {itemSearchQuery.length > 0 && !isSearchingItems && itemSearchResults.length === 0 && (
                  <p className="text-sm text-muted-foreground py-2">검색 결과가 없습니다.</p>
                )}
              </div>
            )}

            {/* 품목 목록 테이블 */}
            {manualItems.length > 0 ? (
              <div className="bg-white border rounded-lg overflow-hidden">
                <table className="w-full text-sm">
                  <thead className="bg-muted/50">
                    <tr>
                      <th className="text-left px-4 py-2 font-medium">No</th>
                      <th className="text-left px-4 py-2 font-medium">품목명</th>
                      <th className="text-left px-4 py-2 font-medium">규격</th>
                      <th className="text-center px-4 py-2 font-medium w-28">수량</th>
                      <th className="text-center px-4 py-2 font-medium w-16">단위</th>
                      <th className="text-center px-4 py-2 font-medium w-16"></th>
                    </tr>
                  </thead>
                  <tbody>
                    {manualItems.map((item, index) => (
                      <tr key={index} className="border-t">
                        <td className="px-4 py-2 text-muted-foreground">{index + 1}</td>
                        <td className="px-4 py-2">{item.item_name}</td>
                        <td className="px-4 py-2 text-muted-foreground">{item.specification || '-'}</td>
                        <td className="px-4 py-2 text-center">
                          <Input
                            type="number"
                            min={1}
                            value={item.quantity}
                            onChange={(e) => handleItemQtyChange(index, parseInt(e.target.value) || 1)}
                            className="w-24 text-center mx-auto h-8"
                          />
                        </td>
                        <td className="px-4 py-2 text-center text-muted-foreground">{item.unit}</td>
                        <td className="px-4 py-2 text-center">
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            onClick={() => handleRemoveItem(index)}
                            className="h-7 w-7 p-0 text-destructive hover:text-destructive"
                          >
                            <Trash2 className="w-4 h-4" />
                          </Button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <div className="text-center py-8 text-muted-foreground bg-white border rounded-lg">
                <p>추가된 품목이 없습니다.</p>
                <p className="text-sm mt-1">위의 &apos;품목 추가&apos; 버튼으로 절곡품을 검색하여 추가하세요.</p>
              </div>
            )}

            {validationErrors.items && (
              <p className="text-sm text-destructive mt-2">{validationErrors.items}</p>
            )}
          </section>
        )}

        {/* 비고 */}
        <section className="bg-muted/30 border rounded-lg p-6">
          <h3 className="font-semibold mb-4">비고</h3>
          <Textarea
            value={formData.note}
            onChange={(e) => setFormData({ ...formData, note: e.target.value })}
            placeholder="특이사항이나 메모를 입력하세요"
            rows={4}
            className="bg-white"
          />
        </section>
      </div>
  ), [mode, formData, validationErrors, processOptions, isLoadingProcesses, assigneeNames, getSelectedProcessCode, manualItems, showItemSearch, itemSearchQuery, itemSearchResults, isSearchingItems, clearFieldError]);

  return (
    <>
      <IntegratedDetailTemplate
        config={workOrderCreateConfig}
        mode="create"
        isLoading={isLoadingProcesses}
        onCancel={handleCancel}
        onSubmit={async () => {
          return await handleSubmit();
        }}
        renderForm={renderFormContent}
      />

      {/* 수주 선택 모달 */}
      <SalesOrderSelectModal
        open={isModalOpen}
        onOpenChange={setIsModalOpen}
        onSelect={handleSelectOrder}
      />

      {/* 담당자 선택 모달 */}
      <AssigneeSelectModal
        open={isAssigneeModalOpen}
        onOpenChange={setIsAssigneeModalOpen}
        selectedIds={formData.assignees}
        onSelect={(ids, names) => {
          setFormData({ ...formData, assignees: ids });
          setAssigneeNames(names);
        }}
      />
    </>
  );
}
