/**
 * 현장 관리 - IntegratedListTemplateV2 적용
 * 
 * 기준정보 -> 디자인시스템관리 -> 템플릿의 IntegratedListTemplateV2를 적용한 현장 관리 페이지입니다.
 * - PageHeader, StatCards, SearchFilter, 체크박스
 * - 데스크톱: TabsList + DataTable
 * - 모바일: 커스텀 버튼 탭 + 카드 리스트
 * - 완전한 반응형 지원
 */

import { useState, useMemo } from "react";
import { 
  MapPin, 
  Plus, 
  Eye, 
  Edit,
  Trash2,
  Building2,
  TrendingUp,
  Clock,
  CheckCircle,
  AlertTriangle,
  FileText,
  ArrowLeft,
  Upload,
  Download,
  Paperclip,
  X
} from "lucide-react";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Label } from "./ui/label";
import { Input } from "./ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Textarea } from "./ui/textarea";
import { Separator } from "./ui/separator";
import { Checkbox } from "./ui/checkbox";
import { IntegratedListTemplateV2, TabOption, TableColumn } from "./templates/IntegratedListTemplateV2";
import { ResponsiveFormTemplate, FormSection, FormField, FormFieldGrid } from "./templates/ResponsiveFormTemplate";
import { TableRow, TableCell } from "./ui/table";
import { toast } from "sonner@2.0.3";
import { useData } from "./contexts/DataContext";
import type { Site, SiteAttachment } from "./contexts/DataContext";

type ViewMode = "list" | "create" | "edit" | "view";

export function SiteManagement() {
  const { sites, addSite, updateSite, deleteSite, salesOrders } = useData();
  const [currentView, setCurrentView] = useState<ViewMode>("list");
  const [selectedSite, setSelectedSite] = useState<Site | null>(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [currentTab, setCurrentTab] = useState<string>("all");
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 10;
  
  // 폼 상태
  const [formData, setFormData] = useState<Partial<Site>>({
    siteName: "",
    keyAddress: "",
    clientCode: "",
    clientName: "",
    siteCategory: "신축",
    contractStartDate: "",
    contractEndDate: "",
    salesManager: "",
    siteManager: "",
    accumulatedOrderAmount: 0,
    totalCost: 0,
    status: "수주중",
    specialNotes: "",
    attachments: []
  });

  // ============= 통계 =============
  const stats = useMemo(() => [
    {
      label: "전체 현장",
      value: sites.length,
      icon: MapPin,
      iconColor: "text-blue-600"
    },
    {
      label: "진행중",
      value: sites.filter(s => s.status === '진행중').length,
      icon: Clock,
      iconColor: "text-orange-600"
    },
    {
      label: "완료",
      value: sites.filter(s => s.status === '완료').length,
      icon: CheckCircle,
      iconColor: "text-green-600"
    },
    {
      label: "총 수주액",
      value: `${(sites.reduce((sum, s) => sum + (s.accumulatedOrderAmount || 0), 0) / 100000000).toFixed(1)}억`,
      icon: TrendingUp,
      iconColor: "text-purple-600"
    }
  ], [sites]);

  // ============= 탭 구성 =============
  const tabs: TabOption[] = [
    {
      value: "all",
      label: "전체",
      count: sites.length,
      color: "blue",
    },
    {
      value: "수주중",
      label: "수주중",
      count: sites.filter(s => s.status === '수주중').length,
      color: "blue",
    },
    {
      value: "진행중",
      label: "진행중",
      count: sites.filter(s => s.status === '진행중').length,
      color: "orange",
    },
    {
      value: "일시중단",
      label: "일시중단",
      count: sites.filter(s => s.status === '일시중단').length,
      color: "gray",
    },
    {
      value: "완료",
      label: "완료",
      count: sites.filter(s => s.status === '완료').length,
      color: "green",
    },
    {
      value: "취소",
      label: "취소",
      count: sites.filter(s => s.status === '취소').length,
      color: "red",
    },
  ];

  // ============= 필터링 =============
  const filteredSites = useMemo(() => {
    return sites.filter(site => {
      const searchLower = searchTerm.toLowerCase();
      const matchesSearch =
        !searchTerm ||
        (site.siteCode || "").toLowerCase().includes(searchLower) ||
        (site.siteName || "").toLowerCase().includes(searchLower) ||
        (site.clientName || "").toLowerCase().includes(searchLower) ||
        (site.keyAddress || "").toLowerCase().includes(searchLower);

      let matchesTab = true;
      if (currentTab !== "all") {
        matchesTab = site.status === currentTab;
      }

      return matchesSearch && matchesTab;
    });
  }, [sites, searchTerm, currentTab]);

  // 페이지네이션
  const totalPages = Math.ceil(filteredSites.length / itemsPerPage);
  const paginatedSites = filteredSites.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  // ============= 핸들러 =============
  const handleView = (site: Site) => {
    setSelectedSite(site);
    setCurrentView("view");
  };

  const handleEdit = (site: Site) => {
    setSelectedSite(site);
    setFormData(site);
    setCurrentView("edit");
  };

  const handleDelete = (site: Site) => {
    if (window.confirm(`"${site.siteName}" 현장을 삭제하시겠습니까?`)) {
      deleteSite(site.id);
      toast.success("현장이 삭제되었습니다.");
    }
  };

  const handleSaveSite = () => {
    if (!formData.siteName?.trim()) {
      toast.error("현장명을 입력해주세요.");
      return;
    }
    if (!formData.keyAddress?.trim()) {
      toast.error("위치를 입력해주세요.");
      return;
    }

    if (currentView === "edit" && selectedSite) {
      updateSite(selectedSite.id, formData as Site);
      toast.success("현장 정보가 수정되었습니다.");
    } else {
      const newSite: Site = {
        id: `SITE-${Date.now()}`,
        siteCode: `ST-${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, '0')}-${String(sites.length + 1).padStart(3, '0')}`,
        siteName: formData.siteName!,
        keyAddress: formData.keyAddress!,
        clientCode: formData.clientCode || "",
        clientName: formData.clientName || "",
        siteCategory: formData.siteCategory || "신축",
        contractStartDate: formData.contractStartDate || "",
        contractEndDate: formData.contractEndDate || "",
        salesManager: formData.salesManager || "",
        siteManager: formData.siteManager || "",
        accumulatedOrderAmount: formData.accumulatedOrderAmount || 0,
        totalCost: formData.totalCost || 0,
        status: formData.status || "수주중",
        specialNotes: formData.specialNotes || "",
        attachments: formData.attachments || []
      };
      addSite(newSite);
      toast.success("새 현장이 등록되었습니다.");
    }

    setCurrentView("list");
    resetForm();
  };

  const resetForm = () => {
    setFormData({
      siteName: "",
      keyAddress: "",
      clientCode: "",
      clientName: "",
      siteCategory: "신축",
      contractStartDate: "",
      contractEndDate: "",
      salesManager: "",
      siteManager: "",
      accumulatedOrderAmount: 0,
      totalCost: 0,
      status: "수주중",
      specialNotes: "",
      attachments: []
    });
    setSelectedSite(null);
  };

  // 체크박스 선택
  const toggleSelection = (id: string) => {
    const newSelection = new Set(selectedItems);
    if (newSelection.has(id)) {
      newSelection.delete(id);
    } else {
      newSelection.add(id);
    }
    setSelectedItems(newSelection);
  };

  const toggleSelectAll = () => {
    if (selectedItems.size === paginatedSites.length && paginatedSites.length > 0) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(paginatedSites.map((s) => s.id)));
    }
  };

  // 파일 업로드
  const handleFileUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files;
    if (!files || files.length === 0) return;

    const newAttachments: SiteAttachment[] = [];

    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      
      if (file.size > 10 * 1024 * 1024) {
        toast.error(`${file.name}은(는) 10MB를 초과합니다.`);
        continue;
      }

      const reader = new FileReader();
      reader.onload = (e) => {
        const attachment: SiteAttachment = {
          id: `ATT-${Date.now()}-${i}`,
          fileName: file.name,
          fileSize: file.size,
          fileType: file.type,
          uploadDate: new Date().toISOString().split('T')[0],
          fileData: e.target?.result as string
        };
        newAttachments.push(attachment);

        if (newAttachments.length === files.length) {
          setFormData({
            ...formData,
            attachments: [...(formData.attachments || []), ...newAttachments]
          });
          toast.success(`${newAttachments.length}개 파일이 추가되었습니다.`);
        }
      };
      reader.readAsDataURL(file);
    }
  };

  const handleRemoveAttachment = (attachmentId: string) => {
    setFormData({
      ...formData,
      attachments: (formData.attachments || []).filter(a => a.id !== attachmentId)
    });
    toast.success("파일이 삭제되었습니다.");
  };

  const handleDownloadAttachment = (attachment: SiteAttachment) => {
    if (!attachment.fileData) {
      toast.error("파일 데이터가 없습니다.");
      return;
    }

    const link = document.createElement('a');
    link.href = attachment.fileData;
    link.download = attachment.fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    toast.success(`${attachment.fileName} 다운로드 완료`);
  };

  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
  };

  // 상태 뱃지 컬러
  const getStatusBadgeClass = (status: string) => {
    const variants: { [key: string]: string } = {
      '수주중': "bg-blue-50 text-blue-700 border-blue-200",
      '진행중': "bg-orange-50 text-orange-700 border-orange-200",
      '일시중단': "bg-yellow-50 text-yellow-700 border-yellow-200",
      '완료': "bg-green-50 text-green-700 border-green-200",
      '취소': "bg-red-50 text-red-700 border-red-200",
    };
    return variants[status] || variants['수주중'];
  };

  const getCategoryBadgeClass = (category: string) => {
    const colors: { [key: string]: string } = {
      '신축': 'bg-blue-50 text-blue-700 border-blue-200',
      '증축': 'bg-green-50 text-green-700 border-green-200',
      '보강': 'bg-purple-50 text-purple-700 border-purple-200',
      'OEM': 'bg-orange-50 text-orange-700 border-orange-200',
      '기타': 'bg-gray-50 text-gray-700 border-gray-200'
    };
    return colors[category] || colors['기타'];
  };

  // ============= 테이블 컬럼 =============
  const tableColumns: TableColumn[] = [
    { key: "rowNumber", label: "번호", className: "px-4" },
    { key: "siteCode", label: "현장코드", className: "px-4" },
    { key: "siteName", label: "현장명", className: "px-4" },
    { key: "clientName", label: "거래처", className: "px-4" },
    { key: "siteCategory", label: "카테고리", className: "px-4" },
    { key: "keyAddress", label: "위치", className: "px-4" },
    { key: "contractPeriod", label: "계약기간", className: "px-4" },
    { key: "accumulatedOrderAmount", label: "누적수주액", className: "px-4" },
    { key: "status", label: "상태", className: "px-4" },
    { key: "actions", label: "작업", className: "px-4" },
  ];

  // 테이블 행 렌더링
  const renderTableRow = (site: Site, index: number, globalIndex: number) => {
    const itemId = site.id;
    const isSelected = selectedItems.has(itemId);

    return (
      <TableRow key={site.id} className={isSelected ? "bg-blue-50" : ""}>
        <TableCell>
          <Checkbox
            checked={isSelected}
            onCheckedChange={() => toggleSelection(itemId)}
          />
        </TableCell>
        <TableCell>{globalIndex + 1}</TableCell>
        <TableCell>
          <code className="text-xs bg-gray-100 px-2 py-1 rounded font-mono">
            {site.siteCode}
          </code>
        </TableCell>
        <TableCell>
          <span className="font-medium">{site.siteName}</span>
        </TableCell>
        <TableCell>{site.clientName || "-"}</TableCell>
        <TableCell>
          <Badge variant="outline" className={getCategoryBadgeClass(site.siteCategory)}>
            {site.siteCategory}
          </Badge>
        </TableCell>
        <TableCell>
          <span className="text-sm text-muted-foreground">{site.keyAddress || "-"}</span>
        </TableCell>
        <TableCell>
          {site.contractStartDate ? (
            <span className="text-sm">
              {site.contractStartDate} ~ {site.contractEndDate || "진행중"}
            </span>
          ) : (
            "-"
          )}
        </TableCell>
        <TableCell className="text-right">
          <span className="font-medium">
            ₩{(site.accumulatedOrderAmount || 0).toLocaleString()}
          </span>
        </TableCell>
        <TableCell>
          <Badge variant="outline" className={getStatusBadgeClass(site.status)}>
            {site.status}
          </Badge>
        </TableCell>
        <TableCell>
          <div className="flex gap-1">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => handleView(site)}
            >
              <Eye className="h-4 w-4" />
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => handleEdit(site)}
            >
              <Edit className="h-4 w-4" />
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => handleDelete(site)}
            >
              <Trash2 className="h-4 w-4 text-red-500" />
            </Button>
          </div>
        </TableCell>
      </TableRow>
    );
  };

  // 모바일 카드 렌더링
  const renderMobileCard = (site: Site, index: number, globalIndex: number, isSelected: boolean, onToggle: () => void) => {
    return (
      <Card key={site.id} className={`p-4 ${isSelected ? "border-blue-500 bg-blue-50" : ""}`}>
        <div className="space-y-3">
          <div className="flex items-start gap-3">
            <Checkbox
              checked={isSelected}
              onCheckedChange={onToggle}
              className="mt-1"
            />
            <div className="flex-1">
              <div className="flex items-center gap-2 mb-1">
                <code className="text-xs bg-gray-100 px-2 py-1 rounded font-mono">
                  {site.siteCode}
                </code>
                <Badge variant="outline" className={getStatusBadgeClass(site.status)}>
                  {site.status}
                </Badge>
              </div>
              <div className="text-sm text-muted-foreground space-y-1">
                <div className="font-medium text-foreground">{site.siteName}</div>
                <div>거래처: {site.clientName || "-"}</div>
                <div>위치: {site.keyAddress || "-"}</div>
                <div>카테고리: {site.siteCategory}</div>
                <div className="font-medium text-foreground">
                  누적수주액: ₩{(site.accumulatedOrderAmount || 0).toLocaleString()}
                </div>
                {site.contractStartDate && (
                  <div>계약기간: {site.contractStartDate} ~ {site.contractEndDate || "진행중"}</div>
                )}
              </div>
            </div>
          </div>

          <div className="flex gap-2 flex-wrap pt-2 border-t">
            <Button
              size="sm"
              variant="outline"
              onClick={() => handleView(site)}
            >
              <Eye className="h-4 w-4 mr-1" />
              상세
            </Button>
            <Button
              size="sm"
              variant="outline"
              onClick={() => handleEdit(site)}
            >
              <Edit className="h-4 w-4 mr-1" />
              수정
            </Button>
            <Button
              size="sm"
              variant="outline"
              onClick={() => handleDelete(site)}
            >
              <Trash2 className="h-4 w-4 mr-1" />
              삭제
            </Button>
          </div>
        </div>
      </Card>
    );
  };

  // ============= 렌더링 =============

  // 목록 화면
  if (currentView === "list") {
    return (
      <IntegratedListTemplateV2
        title="현장 관리"
        description="현장 정보를 등록하고 관리합니다"
        icon={MapPin}
        headerActions={
          <Button onClick={() => setCurrentView("create")}>
            <Plus className="w-4 h-4 mr-2" />
            현장 등록
          </Button>
        }
        stats={stats}
        searchValue={searchTerm}
        onSearchChange={setSearchTerm}
        searchPlaceholder="현장코드, 현장명, 거래처, 위치로 검색..."
        tabs={tabs}
        activeTab={currentTab}
        onTabChange={(value) => {
          setCurrentTab(value);
          setCurrentPage(1);
        }}
        tableColumns={tableColumns}
        tableTitle={`${tabs.find(t => t.value === currentTab)?.label || "전체"} (${filteredSites.length}개)`}
        data={paginatedSites}
        selectedItems={selectedItems}
        onToggleSelection={toggleSelection}
        onToggleSelectAll={toggleSelectAll}
        getItemId={(site) => site.id}
        renderTableRow={renderTableRow}
        renderMobileCard={renderMobileCard}
        pagination={{
          currentPage,
          totalPages,
          totalItems: filteredSites.length,
          itemsPerPage,
          onPageChange: setCurrentPage,
        }}
      />
    );
  }

  // 상세보기 화면
  if (currentView === "view" && selectedSite) {
    return (
      <div className="space-y-6 p-6">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="sm" onClick={() => { setCurrentView("list"); resetForm(); }}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            목록으로
          </Button>
          <div className="flex-1">
            <div className="flex items-center gap-3">
              <MapPin className="w-6 h-6 text-primary" />
              <div>
                <h1 className="text-2xl font-semibold">현장 상세정보</h1>
                <p className="text-sm text-muted-foreground">{selectedSite.siteCode}</p>
              </div>
            </div>
          </div>
          <div className="flex gap-2">
            <Button variant="outline" onClick={() => handleEdit(selectedSite)}>
              <Edit className="w-4 h-4 mr-2" />
              수정
            </Button>
            <Button variant="outline" onClick={() => handleDelete(selectedSite)}>
              <Trash2 className="w-4 h-4 mr-2" />
              삭제
            </Button>
          </div>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>기본 정보</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label className="text-muted-foreground">현장코드</Label>
                <p className="font-mono">{selectedSite.siteCode}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">현장명</Label>
                <p className="font-semibold">{selectedSite.siteName}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">위치</Label>
                <p>{selectedSite.keyAddress}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">카테고리</Label>
                <p>{selectedSite.siteCategory}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">거래처</Label>
                <p>{selectedSite.clientName || "-"}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">상태</Label>
                <p>{selectedSite.status}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">계약 시작일</Label>
                <p>{selectedSite.contractStartDate || "-"}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">계약 종료일</Label>
                <p>{selectedSite.contractEndDate || "-"}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">영업 담당자</Label>
                <p>{selectedSite.salesManager || "-"}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">현장 담당자</Label>
                <p>{selectedSite.siteManager || "-"}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">누적 수주액</Label>
                <p className="font-semibold">₩{(selectedSite.accumulatedOrderAmount || 0).toLocaleString()}</p>
              </div>
              <div>
                <Label className="text-muted-foreground">총 비용</Label>
                <p className="font-semibold">₩{(selectedSite.totalCost || 0).toLocaleString()}</p>
              </div>
            </div>
            {selectedSite.specialNotes && (
              <div>
                <Label className="text-muted-foreground">특이사항</Label>
                <p className="mt-1">{selectedSite.specialNotes}</p>
              </div>
            )}
          </CardContent>
        </Card>

        {selectedSite.attachments && selectedSite.attachments.length > 0 && (
          <Card>
            <CardHeader>
              <CardTitle>첨부파일 ({selectedSite.attachments.length})</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                {selectedSite.attachments.map((attachment) => (
                  <div key={attachment.id} className="flex items-center justify-between p-3 border rounded-lg">
                    <div className="flex items-center gap-3">
                      <Paperclip className="h-4 w-4 text-muted-foreground" />
                      <div>
                        <p className="text-sm font-medium">{attachment.fileName}</p>
                        <p className="text-xs text-muted-foreground">
                          {formatFileSize(attachment.fileSize)} • {attachment.uploadDate}
                        </p>
                      </div>
                    </div>
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={() => handleDownloadAttachment(attachment)}
                    >
                      <Download className="h-4 w-4" />
                    </Button>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        )}
      </div>
    );
  }

  // 등록/수정 화면
  return (
    <ResponsiveFormTemplate
      title={currentView === "edit" ? "현장 수정" : "현장 등록"}
      description={currentView === "edit" ? selectedSite?.siteCode : "새로운 현장을 등록합니다"}
      icon={MapPin}
      onSave={handleSaveSite}
      onCancel={() => { setCurrentView("list"); resetForm(); }}
      saveText={currentView === "edit" ? "수정" : "등록"}
      cancelText="목록으로"
      maxWidth="full"
    >
      <FormSection title="기본 정보">
        <FormFieldGrid columns={2}>
          <FormField label="현장명" required>
            <Input
              value={formData.siteName}
              onChange={(e) => setFormData({ ...formData, siteName: e.target.value })}
              placeholder="현장명 입력"
            />
          </FormField>
          <FormField label="위치" required>
            <Input
              value={formData.keyAddress}
              onChange={(e) => setFormData({ ...formData, keyAddress: e.target.value })}
              placeholder="현장 위치 입력"
            />
          </FormField>
          <FormField label="거래처명">
            <Input
              value={formData.clientName}
              onChange={(e) => setFormData({ ...formData, clientName: e.target.value })}
              placeholder="거래처명 입력"
            />
          </FormField>
          <FormField label="카테고리">
            <Select
              value={formData.siteCategory}
              onValueChange={(value) => setFormData({ ...formData, siteCategory: value })}
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="신축">신축</SelectItem>
                <SelectItem value="증축">증축</SelectItem>
                <SelectItem value="보강">보강</SelectItem>
                <SelectItem value="OEM">OEM</SelectItem>
                <SelectItem value="기타">기타</SelectItem>
              </SelectContent>
            </Select>
          </FormField>
          <FormField label="계약 시작일">
            <Input
              type="date"
              value={formData.contractStartDate}
              onChange={(e) => setFormData({ ...formData, contractStartDate: e.target.value })}
            />
          </FormField>
          <FormField label="계약 종료일">
            <Input
              type="date"
              value={formData.contractEndDate}
              onChange={(e) => setFormData({ ...formData, contractEndDate: e.target.value })}
            />
          </FormField>
          <FormField label="영업 담당자">
            <Input
              value={formData.salesManager}
              onChange={(e) => setFormData({ ...formData, salesManager: e.target.value })}
              placeholder="영업 담당자명"
            />
          </FormField>
          <FormField label="현장 담당자">
            <Input
              value={formData.siteManager}
              onChange={(e) => setFormData({ ...formData, siteManager: e.target.value })}
              placeholder="현장 담당자명"
            />
          </FormField>
          <FormField label="누적 수주액">
            <Input
              type="number"
              value={formData.accumulatedOrderAmount}
              onChange={(e) => setFormData({ ...formData, accumulatedOrderAmount: parseInt(e.target.value) || 0 })}
              min="0"
            />
          </FormField>
          <FormField label="총 비용">
            <Input
              type="number"
              value={formData.totalCost}
              onChange={(e) => setFormData({ ...formData, totalCost: parseInt(e.target.value) || 0 })}
              min="0"
            />
          </FormField>
          <FormField label="상태">
            <Select
              value={formData.status}
              onValueChange={(value) => setFormData({ ...formData, status: value })}
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="수주중">수주중</SelectItem>
                <SelectItem value="진행중">진행중</SelectItem>
                <SelectItem value="일시중단">일시중단</SelectItem>
                <SelectItem value="완료">완료</SelectItem>
                <SelectItem value="취소">취소</SelectItem>
              </SelectContent>
            </Select>
          </FormField>
        </FormFieldGrid>
        <FormField label="특이사항">
          <Textarea
            value={formData.specialNotes}
            onChange={(e) => setFormData({ ...formData, specialNotes: e.target.value })}
            placeholder="특이사항 입력..."
            rows={4}
          />
        </FormField>
      </FormSection>

      <FormSection title="첨부파일" icon={Paperclip}>
        <div>
          <Label htmlFor="file-upload" className="cursor-pointer">
            <div className="border-2 border-dashed rounded-lg p-6 text-center hover:bg-muted/50 transition-colors">
              <Upload className="h-8 w-8 mx-auto mb-2 text-muted-foreground" />
              <p className="text-sm text-muted-foreground">
                클릭하여 파일 업로드 (최대 10MB)
              </p>
            </div>
            <Input
              id="file-upload"
              type="file"
              multiple
              onChange={handleFileUpload}
              className="hidden"
            />
          </Label>
        </div>

        {formData.attachments && formData.attachments.length > 0 && (
          <div className="space-y-2">
            <Label>업로드된 파일 ({formData.attachments.length})</Label>
            {formData.attachments.map((attachment) => (
              <div key={attachment.id} className="flex items-center justify-between p-3 border rounded-lg">
                <div className="flex items-center gap-3">
                  <Paperclip className="h-4 w-4 text-muted-foreground" />
                  <div>
                    <p className="text-sm font-medium">{attachment.fileName}</p>
                    <p className="text-xs text-muted-foreground">
                      {formatFileSize(attachment.fileSize)} • {attachment.uploadDate}
                    </p>
                  </div>
                </div>
                <div className="flex gap-2">
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => handleDownloadAttachment(attachment)}
                  >
                    <Download className="h-4 w-4" />
                  </Button>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => handleRemoveAttachment(attachment.id)}
                  >
                    <X className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            ))}
          </div>
        )}
      </FormSection>
    </ResponsiveFormTemplate>
  );
}
