'use client';

import { useState, useCallback, useMemo, useRef, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Plus, X, Trash2, Loader2, Mic, Check, ChevronsUpDown } from 'lucide-react';
import { FileDropzone } from '@/components/ui/file-dropzone';
import { FileList, type NewFile, type ExistingFile } from '@/components/ui/file-list';
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 { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import { siteBriefingConfig } from './siteBriefingConfig';
import { TimePicker } from '@/components/ui/time-picker';
import { toast } from 'sonner';
import type { SiteBriefing, SiteBriefingFormData, ParticipatingCompany, BriefingDocument, AttendeeItem } from './types';
import {
  BRIEFING_TYPE_OPTIONS,
  ATTENDANCE_STATUS_OPTIONS,
  VAT_TYPE_OPTIONS,
  getEmptySiteBriefingFormData,
  siteBriefingToFormData,
} from './types';
import { Badge } from '@/components/ui/badge';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from '@/components/ui/command';
import { cn } from '@/lib/utils';
import { createSiteBriefing, updateSiteBriefing, deleteSiteBriefing } from './actions';
import { getPartnerList } from '../partners/actions';
import { getSiteList, createSite } from '../site-management/actions';
import { getEmployees } from '@/components/hr/EmployeeManagement/actions';
import type { Partner } from '../partners/types';
import type { Site } from '../site-management/types';
import type { Employee } from '@/components/hr/EmployeeManagement/types';

// 목업 문서 목록 (상세 모드에서 다운로드 버튼 테스트용)
const MOCK_DOCUMENTS: BriefingDocument[] = [
  {
    id: '1',
    fileName: '현장설명회_안내문.pdf',
    fileUrl: '#',
    fileSize: 1536000, // 1.5MB
    uploadedAt: '2024-12-20T09:00:00',
  },
  {
    id: '2',
    fileName: '입찰참가신청서.docx',
    fileUrl: '#',
    fileSize: 512000, // 500KB
    uploadedAt: '2024-12-20T09:30:00',
  },
  {
    id: '3',
    fileName: '현장배치도.pdf',
    fileUrl: '#',
    fileSize: 3145728, // 3MB
    uploadedAt: '2024-12-21T14:00:00',
  },
];

interface SiteBriefingFormProps {
  mode: 'view' | 'edit' | 'new';
  briefingId?: string;
  initialData?: SiteBriefing;
}

export default function SiteBriefingForm({ mode, briefingId, initialData }: SiteBriefingFormProps) {
  const router = useRouter();
  const isViewMode = mode === 'view';
  const isNewMode = mode === 'new';
  const isEditMode = mode === 'edit';

  // DEBUG: 초기 데이터 확인

  // 폼 데이터
  const [formData, setFormData] = useState<SiteBriefingFormData>(() => {
    const data = initialData ? siteBriefingToFormData(initialData) : getEmptySiteBriefingFormData();
    return data;
  });

  // 로딩 상태
  const [, _setIsLoading] = useState(false);

  // 다이얼로그 상태 (현장 신규 등록은 별도로 관리)

  // 새 파일 상태
  const [newDocumentFiles, setNewDocumentFiles] = useState<File[]>([]);

  // 거래처 목록
  const [partners, setPartners] = useState<Partner[]>([]);
  const [isLoadingPartners, setIsLoadingPartners] = useState(false);

  // 현장 목록 (선택된 거래처 기준)
  const [sites, setSites] = useState<Site[]>([]);
  const [isLoadingSites, setIsLoadingSites] = useState(false);

  // 현장 입력 및 선택
  const [siteInputValue, setSiteInputValue] = useState(formData.projectName);
  const [showSiteDropdown, setShowSiteDropdown] = useState(false);
  const siteInputRef = useRef<HTMLInputElement>(null);

  // 현장 신규 등록 다이얼로그
  const [showNewSiteDialog, setShowNewSiteDialog] = useState(false);
  const [newSiteName, setNewSiteName] = useState('');
  const [isCreatingSite, setIsCreatingSite] = useState(false);

  // 직원 목록 (참석자용)
  const [employees, setEmployees] = useState<Employee[]>([]);

  // 참석자 Multi-Select Combobox 상태
  const [attendeePopoverOpen, setAttendeePopoverOpen] = useState(false);
  const [attendeeSearchValue, setAttendeeSearchValue] = useState('');

  // 필드 변경 핸들러 (참석자 핸들러에서 사용하므로 먼저 선언)
  const handleChange = useCallback((field: keyof SiteBriefingFormData, value: unknown) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  }, []);

  // 참석자 선택 핸들러
  const handleAttendeeSelect = useCallback((employee: Employee) => {
    const newItem: AttendeeItem = { id: employee.id, name: employee.name };
    const exists = formData.attendeeItems.some((item) => item.id === employee.id);
    if (!exists) {
      handleChange('attendeeItems', [...formData.attendeeItems, newItem]);
    }
    setAttendeeSearchValue('');
  }, [formData.attendeeItems, handleChange]);

  // 참석자 제거 핸들러
  const handleAttendeeRemove = useCallback((attendeeId: string) => {
    handleChange('attendeeItems', formData.attendeeItems.filter((item) => item.id !== attendeeId && item.name !== attendeeId));
  }, [formData.attendeeItems, handleChange]);

  // 참석자 직접 입력 추가 핸들러
  const handleAttendeeAdd = useCallback(() => {
    const trimmed = attendeeSearchValue.trim();
    if (!trimmed) return;
    const exists = formData.attendeeItems.some((item) => item.name === trimmed);
    if (!exists) {
      const newItem: AttendeeItem = { id: '', name: trimmed };
      handleChange('attendeeItems', [...formData.attendeeItems, newItem]);
    }
    setAttendeeSearchValue('');
  }, [attendeeSearchValue, formData.attendeeItems, handleChange]);

  // 상세/수정 모드에서 목데이터 초기화
  useEffect(() => {
    if (initialData && formData.documents.length === 0) {
      setFormData((prev) => ({
        ...prev,
        documents: MOCK_DOCUMENTS,
      }));
    }
  }, [initialData]);

  // 거래처 목록 로드
  useEffect(() => {
    const loadPartners = async () => {
      setIsLoadingPartners(true);
      try {
        const result = await getPartnerList({ size: 100 });
        if (result.success && result.data) {
          setPartners(result.data.items);
        }
      } catch (error) {
        console.error('거래처 목록 로드 실패:', error);
      } finally {
        setIsLoadingPartners(false);
      }
    };
    loadPartners();
  }, []);

  // 거래처 선택 시 현장 목록 로드
  useEffect(() => {
    const loadSites = async () => {
      if (!formData.partnerId) {
        setSites([]);
        return;
      }
      setIsLoadingSites(true);
      try {
        const result = await getSiteList({ clientId: formData.partnerId, size: 100 });
        if (result.success && result.data) {
          setSites(result.data.items);
        }
      } catch (error) {
        console.error('현장 목록 로드 실패:', error);
      } finally {
        setIsLoadingSites(false);
      }
    };
    loadSites();
  }, [formData.partnerId]);

  // 초기 데이터가 있을 때 siteInputValue 동기화
  useEffect(() => {
    if (initialData?.title) {
      setSiteInputValue(initialData.title);
    }
  }, [initialData]);

  // 직원 목록 로드 (참석자용)
  useEffect(() => {
    const loadEmployees = async () => {
      try {
        const result = await getEmployees({ status: 'active', per_page: 100 });
        if (result.data && result.data.length > 0) {
          setEmployees(result.data);
        }
      } catch (error) {
        console.error('직원 목록 로드 실패:', error);
      }
    };
    loadEmployees();
  }, []);

  // 저장 핸들러 (IntegratedDetailTemplate용)
  const handleSubmit = useCallback(async (): Promise<{ success: boolean; error?: string }> => {
    if (!formData.projectName.trim()) {
      return { success: false, error: '현장명을 입력해주세요.' };
    }

    try {
      let result;
      if (isNewMode) {
        result = await createSiteBriefing(formData);
      } else if (briefingId) {
        result = await updateSiteBriefing(briefingId, formData);
      } else {
        return { success: false, error: '현장설명회 ID가 없습니다.' };
      }

      if (!result.success) {
        return { success: false, error: result.error || '저장에 실패했습니다.' };
      }

      toast.success(isNewMode ? '현장설명회가 등록되었습니다.' : '수정이 완료되었습니다.');
      router.push('/ko/construction/project/bidding/site-briefings');
      router.refresh();
      return { success: true };
    } catch (error) {
      return { success: false, error: error instanceof Error ? error.message : '저장에 실패했습니다.' };
    }
  }, [isNewMode, briefingId, formData, router]);

  // 삭제 핸들러 (IntegratedDetailTemplate용)
  const handleDelete = useCallback(async (): Promise<{ success: boolean; error?: string }> => {
    if (!briefingId) {
      return { success: false, error: '현장설명회 ID가 없습니다.' };
    }

    try {
      const result = await deleteSiteBriefing(briefingId);

      if (!result.success) {
        return { success: false, error: result.error || '삭제에 실패했습니다.' };
      }

      toast.success('현장설명회가 삭제되었습니다.');
      router.push('/ko/construction/project/bidding/site-briefings');
      router.refresh();
      return { success: true };
    } catch (error) {
      return { success: false, error: error instanceof Error ? error.message : '삭제에 실패했습니다.' };
    }
  }, [briefingId, router]);

  // 현장 신규 등록 핸들러
  const handleCreateSite = useCallback(async () => {
    if (!newSiteName.trim()) {
      toast.error('현장명을 입력해주세요.');
      return;
    }
    if (!formData.partnerId) {
      toast.error('거래처를 먼저 선택해주세요.');
      return;
    }

    setIsCreatingSite(true);
    try {
      const result = await createSite({
        siteName: newSiteName.trim(),
        partnerId: formData.partnerId,
      });

      if (!result.success) {
        throw new Error(result.error || '현장 등록에 실패했습니다.');
      }

      toast.success('현장이 등록되었습니다.');

      // 현장 목록 새로고침
      const sitesResult = await getSiteList({ clientId: formData.partnerId, size: 100 });
      if (sitesResult.success && sitesResult.data) {
        setSites(sitesResult.data.items);
      }

      // 새로 등록된 현장을 선택
      setSiteInputValue(newSiteName.trim());
      handleChange('projectName', newSiteName.trim());

      // 다이얼로그 닫기 및 상태 초기화
      setShowNewSiteDialog(false);
      setNewSiteName('');
    } catch (error) {
      toast.error(error instanceof Error ? error.message : '현장 등록에 실패했습니다.');
    } finally {
      setIsCreatingSite(false);
    }
  }, [newSiteName, formData.partnerId, handleChange]);

  // 참여업체 추가 핸들러
  const handleAddCompany = useCallback(() => {
    const newCompany: ParticipatingCompany = {
      id: String(Date.now()),
      companyName: '',
      memo: '',
    };
    setFormData((prev) => ({
      ...prev,
      participatingCompanies: [...prev.participatingCompanies, newCompany],
    }));
  }, []);

  // 참여업체 삭제 핸들러
  const handleRemoveCompany = useCallback((companyId: string) => {
    setFormData((prev) => ({
      ...prev,
      participatingCompanies: prev.participatingCompanies.filter((c) => c.id !== companyId),
    }));
  }, []);

  // 참여업체 변경 핸들러
  const handleCompanyChange = useCallback(
    (companyId: string, field: keyof ParticipatingCompany, value: string) => {
      setFormData((prev) => ({
        ...prev,
        participatingCompanies: prev.participatingCompanies.map((c) =>
          c.id === companyId ? { ...c, [field]: value } : c
        ),
      }));
    },
    []
  );

  // 파일 추가 핸들러
  const handleFilesSelect = useCallback((files: File[]) => {
    setNewDocumentFiles((prev) => [...prev, ...files]);
  }, []);

  // 새 파일 삭제 핸들러
  const handleNewFileRemove = useCallback((index: number) => {
    setNewDocumentFiles((prev) => prev.filter((_, i) => i !== index));
  }, []);

  // 기존 문서 삭제 핸들러
  const handleExistingDocumentRemove = useCallback((docId: string | number) => {
    setFormData((prev) => ({
      ...prev,
      documents: prev.documents.filter((d) => d.id !== String(docId)),
    }));
  }, []);

  // 동적 config (모드에 따른 title 변경)
  // Note: IntegratedDetailTemplate이 모드에 따라 '등록'/'수정' 자동 추가
  const dynamicConfig = useMemo(() => {
    if (isNewMode) {
      return {
        ...siteBriefingConfig,
        title: '현장설명회',
        description: '새로운 현장설명회를 등록합니다',
        actions: {
          ...siteBriefingConfig.actions,
          submitLabel: '저장',
        },
      };
    }
    if (isEditMode) {
      return {
        ...siteBriefingConfig,
        title: '현장설명회',
        description: '현장설명회 정보를 수정합니다',
      };
    }
    return siteBriefingConfig;
  }, [isNewMode, isEditMode]);

  // 입력 필드 렌더링 헬퍼
  const renderField = (
    label: string,
    field: keyof SiteBriefingFormData,
    value: string | number,
    options?: {
      required?: boolean;
      type?: 'text' | 'tel' | 'email' | 'number' | 'date' | 'time';
      placeholder?: string;
      disabled?: boolean;
    }
  ) => {
    const { required, type = 'text', placeholder, disabled } = options || {};
    return (
      <div className="space-y-2">
        <Label className="text-sm font-medium text-gray-700">
          {label} {required && <span className="text-red-500">*</span>}
        </Label>
        <Input
          type={type}
          value={value}
          onChange={(e) =>
            handleChange(field, type === 'number' ? Number(e.target.value) : e.target.value)
          }
          placeholder={placeholder}
          disabled={isViewMode || disabled}
          className="bg-white"
        />
      </div>
    );
  };

  // 셀렉트 필드 렌더링 헬퍼
  const renderSelectField = (
    label: string,
    field: keyof SiteBriefingFormData,
    value: string,
    options: { value: string; label: string }[],
    required?: boolean
  ) => {
    return (
      <div className="space-y-2">
        <Label className="text-sm font-medium text-gray-700">
          {label} {required && <span className="text-red-500">*</span>}
        </Label>
        <Select value={value} onValueChange={(val) => handleChange(field, val)} disabled={isViewMode}>
          <SelectTrigger className="bg-white">
            <SelectValue placeholder="선택" />
          </SelectTrigger>
          <SelectContent>
            {options.map((option) => (
              <SelectItem key={option.value} value={option.value}>
                {option.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
    );
  };

  // 폼 내용 렌더링 함수
  const renderFormContent = () => (
    <>
      <div className="space-y-6">
        {/* 기본 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">기본 정보 *</CardTitle>
          </CardHeader>
          <CardContent className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {renderField('현설번호', 'briefingCode', formData.briefingCode, {
              placeholder: '123123',
            })}
            {/* 거래처명 - 실제 API 데이터 */}
            <div className="space-y-2">
              <Label className="text-sm font-medium text-gray-700">
                거래처명 <span className="text-red-500">*</span>
              </Label>
              <Select
                value={formData.partnerId}
                onValueChange={(val) => {
                  handleChange('partnerId', val);
                  // 거래처 변경 시 현장명 초기화
                  handleChange('projectName', '');
                  setSiteInputValue('');
                  // partnerName도 업데이트
                  const selectedPartner = partners.find((p) => p.id === val);
                  if (selectedPartner) {
                    handleChange('partnerName', selectedPartner.partnerName);
                  }
                }}
                disabled={isViewMode || isLoadingPartners}
              >
                <SelectTrigger className="bg-white">
                  <SelectValue placeholder={isLoadingPartners ? '로딩 중...' : '거래처 선택'} />
                </SelectTrigger>
                <SelectContent>
                  {partners.map((partner) => (
                    <SelectItem key={partner.id} value={partner.id}>
                      {partner.partnerName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            {renderField('현장설명회 일자', 'briefingDate', formData.briefingDate, {
              type: 'date',
              required: true,
            })}
            {/* 현장설명회 시간 */}
            <div className="space-y-2">
              <Label className="text-sm font-medium text-gray-700">현장설명회 시간</Label>
              <TimePicker
                value={formData.briefingTime}
                onChange={(value) => handleChange('briefingTime', value)}
                placeholder="시간 선택"
                disabled={isViewMode}
                minuteStep={1}
              />
            </div>
            {renderSelectField('구분', 'briefingType', formData.briefingType, BRIEFING_TYPE_OPTIONS)}
            {renderField('현장설명회 장소', 'location', formData.location, {
              placeholder: '장소명',
            })}
            {/* 참석자 - Multi-Select Combobox */}
            <div className="space-y-2">
              <Label className="text-sm font-medium text-gray-700">참석자</Label>
              {isViewMode ? (
                <div className="flex flex-wrap gap-2 min-h-[38px] p-2 border rounded-md bg-gray-50">
                  {formData.attendeeItems.length > 0 ? (
                    formData.attendeeItems.map((item) => (
                      <Badge key={item.id || item.name} variant="secondary">
                        {item.name}
                      </Badge>
                    ))
                  ) : (
                    <span className="text-gray-400 text-sm">참석자 없음</span>
                  )}
                </div>
              ) : (
                <Popover open={attendeePopoverOpen} onOpenChange={setAttendeePopoverOpen}>
                  <PopoverTrigger asChild>
                    <Button
                      variant="outline"
                      role="combobox"
                      aria-expanded={attendeePopoverOpen}
                      className="w-full justify-between min-h-[38px] h-auto"
                    >
                      <div className="flex flex-wrap gap-1 flex-1 text-left">
                        {formData.attendeeItems.length > 0 ? (
                          formData.attendeeItems.map((item) => (
                            <Badge
                              key={item.id || item.name}
                              variant="secondary"
                              className="mr-1"
                              onClick={(e) => {
                                e.stopPropagation();
                                handleAttendeeRemove(item.id || item.name);
                              }}
                            >
                              {item.name}
                              <X className="ml-1 h-3 w-3 cursor-pointer" />
                            </Badge>
                          ))
                        ) : (
                          <span className="text-muted-foreground">참석자 선택 또는 직접 입력</span>
                        )}
                      </div>
                      <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-full p-0" align="start">
                    <Command>
                      <CommandInput
                        placeholder="직원 검색 또는 직접 입력..."
                        value={attendeeSearchValue}
                        onValueChange={setAttendeeSearchValue}
                        onKeyDown={(e) => {
                          if (e.key === 'Enter' && attendeeSearchValue.trim()) {
                            e.preventDefault();
                            handleAttendeeAdd();
                          }
                        }}
                      />
                      <CommandList>
                        <CommandEmpty>
                          {attendeeSearchValue.trim() ? (
                            <button
                              type="button"
                              className="w-full px-2 py-1.5 text-sm text-left hover:bg-accent rounded"
                              onClick={handleAttendeeAdd}
                            >
                              &quot;{attendeeSearchValue}&quot; 추가
                            </button>
                          ) : (
                            '검색 결과가 없습니다.'
                          )}
                        </CommandEmpty>
                        <CommandGroup heading="직원 목록">
                          {employees
                            .filter((emp) =>
                              emp.name.toLowerCase().includes(attendeeSearchValue.toLowerCase())
                            )
                            .map((employee) => {
                              const isSelected = formData.attendeeItems.some(
                                (item) => item.id === employee.id
                              );
                              return (
                                <CommandItem
                                  key={employee.id}
                                  value={employee.name}
                                  onSelect={() => handleAttendeeSelect(employee)}
                                >
                                  <Check
                                    className={cn(
                                      'mr-2 h-4 w-4',
                                      isSelected ? 'opacity-100' : 'opacity-0'
                                    )}
                                  />
                                  {employee.name}
                                </CommandItem>
                              );
                            })}
                        </CommandGroup>
                      </CommandList>
                    </Command>
                  </PopoverContent>
                </Popover>
              )}
            </div>
            {renderSelectField('상태', 'attendanceStatus', formData.attendanceStatus, ATTENDANCE_STATUS_OPTIONS)}
          </CardContent>
        </Card>

        {/* 입찰 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">입찰 정보 *</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {/* 현장명 - 거래처 연동 Combobox */}
              <div className="space-y-2">
                <Label className="text-sm font-medium text-gray-700">
                  현장명 <span className="text-red-500">*</span>
                </Label>
                <div className="relative">
                  <Input
                    ref={siteInputRef}
                    type="text"
                    value={siteInputValue}
                    onChange={(e) => {
                      setSiteInputValue(e.target.value);
                      handleChange('projectName', e.target.value);
                      setShowSiteDropdown(true);
                    }}
                    onFocus={() => formData.partnerId && setShowSiteDropdown(true)}
                    onBlur={() => setTimeout(() => setShowSiteDropdown(false), 200)}
                    placeholder={
                      !formData.partnerId
                        ? '거래처를 먼저 선택해주세요'
                        : isLoadingSites
                          ? '현장 목록 로딩 중...'
                          : '현장명 입력 또는 선택'
                    }
                    disabled={isViewMode || !formData.partnerId}
                    className="bg-white pr-10"
                  />
                  {!isViewMode && formData.partnerId && (
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      className="absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7"
                      onClick={() => {
                        setNewSiteName(siteInputValue);
                        setShowNewSiteDialog(true);
                      }}
                      title="현장 신규 등록"
                    >
                      <Plus className="h-4 w-4" />
                    </Button>
                  )}
                  {/* 현장 드롭다운 */}
                  {showSiteDropdown && sites.length > 0 && (
                    <div className="absolute z-50 w-full mt-1 bg-white border rounded-md shadow-lg max-h-60 overflow-auto">
                      {sites
                        .filter((site) =>
                          site.siteName.toLowerCase().includes(siteInputValue.toLowerCase())
                        )
                        .map((site) => (
                          <button
                            key={site.id}
                            type="button"
                            className="w-full px-3 py-2 text-left text-sm hover:bg-gray-100 focus:bg-gray-100 focus:outline-none"
                            onMouseDown={(e) => {
                              e.preventDefault();
                              setSiteInputValue(site.siteName);
                              handleChange('projectName', site.siteName);
                              setShowSiteDropdown(false);
                            }}
                          >
                            <div className="font-medium">{site.siteName}</div>
                            {site.address && (
                              <div className="text-xs text-gray-500">{site.address}</div>
                            )}
                          </button>
                        ))}
                      {sites.filter((site) =>
                        site.siteName.toLowerCase().includes(siteInputValue.toLowerCase())
                      ).length === 0 && (
                        <div className="px-3 py-2 text-sm text-gray-500">
                          일치하는 현장이 없습니다. 신규 등록하려면 + 버튼을 클릭하세요.
                        </div>
                      )}
                    </div>
                  )}
                </div>
                {!formData.partnerId && !isViewMode && (
                  <p className="text-xs text-amber-600">거래처를 먼저 선택하면 해당 거래처의 현장 목록이 표시됩니다.</p>
                )}
              </div>
              {renderField('입찰일자', 'bidDate', formData.bidDate, {
                type: 'date',
              })}
              {renderField('개소', 'siteCount', formData.siteCount, {
                type: 'number',
              })}
              {/* 공사기간 */}
              <div className="space-y-2">
                <Label className="text-sm font-medium text-gray-700">공사기간</Label>
                <div className="flex items-center gap-2">
                  <DatePicker
                    value={formData.constructionStartDate}
                    onChange={(date) => handleChange('constructionStartDate', date)}
                    disabled={isViewMode}
                  />
                  <span className="text-muted-foreground">~</span>
                  <DatePicker
                    value={formData.constructionEndDate}
                    onChange={(date) => handleChange('constructionEndDate', date)}
                    disabled={isViewMode}
                  />
                </div>
              </div>
            </div>

            {/* 부가세 */}
            {renderSelectField('부가세', 'vatType', formData.vatType, VAT_TYPE_OPTIONS)}

            {/* 업무 보고 */}
            <div className="space-y-2">
              <Label className="text-sm font-medium text-gray-700">업무 보고</Label>
              <div className="flex gap-2">
                <Textarea
                  value={formData.workReport}
                  onChange={(e) => handleChange('workReport', e.target.value)}
                  placeholder="업무 보고 내용을 입력해주세요."
                  disabled={isViewMode}
                  className="flex-1 bg-white"
                  rows={3}
                />
                {!isViewMode && (
                  <Button
                    type="button"
                    variant="outline"
                    className="self-end"
                    onClick={() => toast.info('녹음 기능은 추후 구현 예정입니다.')}
                  >
                    <Mic className="h-4 w-4 mr-1" />
                    녹음
                  </Button>
                )}
              </div>
            </div>

            {/* 현장설명회 자료 */}
            <div className="space-y-4">
              <Label className="text-sm font-medium text-gray-700">현장설명회 자료</Label>
              {!isViewMode && (
                <FileDropzone
                  onFilesSelect={handleFilesSelect}
                  multiple
                  maxSize={10}
                  title="클릭하여 파일을 찾거나, 마우스로 파일을 끌어오세요."
                />
              )}
              <FileList
                files={newDocumentFiles.map((file): NewFile => ({ file }))}
                existingFiles={formData.documents.map((doc): ExistingFile => ({
                  id: doc.id,
                  name: doc.fileName,
                  size: doc.fileSize,
                  url: doc.fileUrl,
                }))}
                onRemove={handleNewFileRemove}
                onRemoveExisting={handleExistingDocumentRemove}
                showRemove={!isViewMode}
                emptyMessage="업로드된 파일이 없습니다"
              />
            </div>
          </CardContent>
        </Card>

        {/* 현장설명회 참여업체 및 메모 */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle className="text-lg">현장설명회 참여업체 및 메모</CardTitle>
            {!isViewMode && (
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={handleAddCompany}
              >
                <Plus className="h-4 w-4 mr-1" />
                추가
              </Button>
            )}
          </CardHeader>
          <CardContent>
            {formData.participatingCompanies.length === 0 ? (
              <p className="text-sm text-gray-500 text-center py-4">
                등록된 참여업체가 없습니다.
              </p>
            ) : (
              <div className="space-y-3">
                {formData.participatingCompanies.map((company, index) => (
                  <div key={company.id} className="flex items-start gap-3">
                    <div className="flex items-center justify-center w-8 h-8 bg-gray-100 rounded text-sm font-medium text-gray-600">
                      {index + 1}
                    </div>
                    <div className="flex-1 grid grid-cols-1 md:grid-cols-2 gap-3">
                      <div className="space-y-1">
                        <Label className="text-xs text-gray-500">참여업체</Label>
                        <Input
                          value={company.companyName}
                          onChange={(e) => handleCompanyChange(company.id, 'companyName', e.target.value)}
                          placeholder="업체명"
                          disabled={isViewMode}
                          className="bg-white"
                        />
                      </div>
                      <div className="space-y-1">
                        <Label className="text-xs text-gray-500">메모</Label>
                        <Input
                          value={company.memo}
                          onChange={(e) => handleCompanyChange(company.id, 'memo', e.target.value)}
                          placeholder="메모"
                          disabled={isViewMode}
                          className="bg-white"
                        />
                      </div>
                    </div>
                    {!isViewMode && (
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        className="h-8 w-8 text-gray-400 hover:text-red-500"
                        onClick={() => handleRemoveCompany(company.id)}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    )}
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </>
  );

  return (
    <>
      <IntegratedDetailTemplate
        config={dynamicConfig}
        mode={mode === 'new' ? 'create' : mode}
        initialData={{}}
        itemId={briefingId}
        isLoading={false}
        onSubmit={handleSubmit}
        onDelete={briefingId && isViewMode ? handleDelete : undefined}
        renderView={() => renderFormContent()}
        renderForm={() => renderFormContent()}
      />

      {/* 현장 신규 등록 다이얼로그 (특수 기능) */}
      <AlertDialog open={showNewSiteDialog} onOpenChange={setShowNewSiteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>현장 신규 등록</AlertDialogTitle>
            <AlertDialogDescription>
              선택한 거래처에 새로운 현장을 등록합니다.
              <br />
              등록된 현장은 현장관리 목록에도 추가됩니다.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <div className="py-4">
            <div className="space-y-2">
              <Label className="text-sm font-medium">거래처</Label>
              <Input
                value={partners.find((p) => p.id === formData.partnerId)?.partnerName || ''}
                disabled
                className="bg-gray-50"
              />
            </div>
            <div className="space-y-2 mt-4">
              <Label className="text-sm font-medium">
                현장명 <span className="text-red-500">*</span>
              </Label>
              <Input
                value={newSiteName}
                onChange={(e) => setNewSiteName(e.target.value)}
                placeholder="현장명을 입력하세요"
                disabled={isCreatingSite}
                autoFocus
              />
            </div>
          </div>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isCreatingSite}>취소</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleCreateSite}
              className="bg-blue-500 hover:bg-blue-600"
              disabled={isCreatingSite || !newSiteName.trim()}
            >
              {isCreatingSite && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
              등록
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}