import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Textarea } from "./ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Badge } from "./ui/badge";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "./ui/dialog";
import { PageLayout } from "./organisms/PageLayout";
import { PageHeader } from "./organisms/PageHeader";
import { 
  ShoppingCart, 
  Plus,
  Save,
  X,
  Search,
  FileText,
  Calendar,
  User,
  Building,
  Phone,
  Truck,
  Split,
  DollarSign,
  ArrowLeft
} from "lucide-react";
import { toast } from "sonner@2.0.3";
import { useData } from "./contexts/DataContext";
import type { Quote, SalesOrder, ShippingLot, ShippingLotItem } from "./contexts/DataContext";

interface OrderRegistrationProps {
  preSelectedQuote?: Quote;
  onComplete?: () => void;
  onCancel?: () => void;
}

export function OrderRegistration({ preSelectedQuote, onComplete, onCancel }: OrderRegistrationProps = {}) {
  const { quotes, addSalesOrder } = useData();
  
  // 견적 선택 모달
  const [showQuoteSelector, setShowQuoteSelector] = useState(false);
  const [selectedQuote, setSelectedQuote] = useState<Quote | null>(preSelectedQuote || null);
  const [searchQuoteTerm, setSearchQuoteTerm] = useState("");
  
  // 사전 선택된 견적이 있으면 자동으로 정보 입력
  useEffect(() => {
    if (preSelectedQuote) {
      handleSelectQuote(preSelectedQuote);
    }
  }, [preSelectedQuote]);
  
  // 수주 정보
  const [orderNumber, setOrderNumber] = useState("");
  const [orderDate, setOrderDate] = useState(new Date().toISOString().split('T')[0]);
  const [deliveryDate, setDeliveryDate] = useState("");
  
  // 고객 정보 (견적에서 자동 입력)
  const [customerName, setCustomerName] = useState("");
  const [customerCode, setCustomerCode] = useState("");
  const [projectName, setProjectName] = useState("");
  const [siteName, setSiteName] = useState("");
  
  // 배송 정보
  const [shippingAddress, setShippingAddress] = useState("");
  const [shippingAddressDetail, setShippingAddressDetail] = useState("");
  const [receiverName, setReceiverName] = useState("");
  const [receiverPhone, setReceiverPhone] = useState("");
  const [shippingMethod, setShippingMethod] = useState<'direct' | 'cargo' | 'express'>('direct');
  
  // 금액 정보
  const [originalAmount, setOriginalAmount] = useState(0);
  const [discountRate, setDiscountRate] = useState(0);
  const [discountAmount, setDiscountAmount] = useState(0);
  const [totalAmount, setTotalAmount] = useState(0);
  
  // 담당자 정보
  const [manager, setManager] = useState("");
  const [registeredBy, setRegisteredBy] = useState("김영업"); // 현재 로그인 사용자
  
  // 분할 출고
  const [hasMultipleShipping, setHasMultipleShipping] = useState(false);
  const [divisionType, setDivisionType] = useState<'location' | 'floor' | 'material'>('location');
  const [shippingLots, setShippingLots] = useState<ShippingLot[]>([]);
  
  // 메모
  const [note, setNote] = useState("");

  // 견적 필터링 - 거부되지 않은 모든 견적 표시 (초안 제외)
  const filteredQuotes = quotes?.filter(quote => 
    (quote.status === 'sent' || quote.status === 'approved' || quote.status === 'finalized' || quote.status === 'converted') &&
    (quote.quoteNumber.toLowerCase().includes(searchQuoteTerm.toLowerCase()) ||
     quote.customerName.toLowerCase().includes(searchQuoteTerm.toLowerCase()) ||
     quote.projectName.toLowerCase().includes(searchQuoteTerm.toLowerCase()))
  ) || [];

  // 견적 선택 처리
  const handleSelectQuote = (quote: Quote) => {
    setSelectedQuote(quote);
    
    // 견적 정보를 수주 정보로 복사
    setCustomerName(quote.customerName);
    setCustomerCode(quote.client || "");
    setProjectName(quote.projectName);
    setSiteName(quote.site || quote.siteName || "");
    setOriginalAmount(quote.totalAmount || quote.amount || 0);
    setTotalAmount(quote.totalAmount || quote.amount || 0);
    setManager(quote.manager || quote.author || "");
    
    // 견적번호 기반으로 수주번호 생성
    const today = new Date();
    const dateStr = `${String(today.getMonth() + 1).padStart(2, '0')}${String(today.getDate()).padStart(2, '0')}`;
    const newOrderNumber = `KD-OR-${today.getFullYear().toString().slice(-2)}${dateStr}-01`;
    setOrderNumber(newOrderNumber);
    
    setShowQuoteSelector(false);
    toast.success(`견적 ${quote.quoteNumber}을(를) 불러왔습니다.`);
  };

  // 할인율 변경 처리
  const handleDiscountRateChange = (rate: number) => {
    setDiscountRate(rate);
    const discount = Math.floor(originalAmount * (rate / 100));
    setDiscountAmount(discount);
    setTotalAmount(originalAmount - discount);
  };

  // 할인 금액 변경 처리
  const handleDiscountAmountChange = (amount: number) => {
    setDiscountAmount(amount);
    const rate = originalAmount > 0 ? (amount / originalAmount) * 100 : 0;
    setDiscountRate(Math.round(rate * 100) / 100);
    setTotalAmount(originalAmount - amount);
  };

  // 분할 로트 추가
  const handleAddShippingLot = () => {
    if (!hasMultipleShipping) return;
    
    const newLot: ShippingLot = {
      id: `lot-${Date.now()}`,
      lotNumber: `${orderNumber}-${shippingLots.length + 1}`,
      scheduleNumber: shippingLots.length + 1,
      divisionType: divisionType,
      scheduledDate: "",
      items: [],
      status: 'scheduled'
    };
    
    setShippingLots([...shippingLots, newLot]);
  };

  // 분할 로트 삭제
  const handleRemoveShippingLot = (lotId: string) => {
    setShippingLots(shippingLots.filter(lot => lot.id !== lotId));
  };

  // 수주 저장
  const handleSaveOrder = () => {
    // 유효성 검사
    if (!orderNumber) {
      toast.error("수주번호를 입력해주세요.");
      return;
    }
    if (!customerName) {
      toast.error("고객명을 입력해주세요.");
      return;
    }
    if (!projectName) {
      toast.error("프로젝트명을 입력해주세요.");
      return;
    }
    if (!deliveryDate) {
      toast.error("납품예정일을 입력해주세요.");
      return;
    }
    if (!shippingAddress) {
      toast.error("배송지 주소를 입력해주세요.");
      return;
    }
    if (!receiverName) {
      toast.error("수령인을 입력해주세요.");
      return;
    }
    if (!receiverPhone) {
      toast.error("수령인 연락처를 입력해주세요.");
      return;
    }

    const newOrder: SalesOrder = {
      id: `order-${Date.now()}`,
      orderNumber: orderNumber,
      quoteId: selectedQuote?.id,
      quoteNumber: selectedQuote?.quoteNumber,
      customerName: customerName,
      customerCode: customerCode,
      projectName: projectName,
      siteName: siteName,
      orderDate: orderDate,
      deliveryDate: deliveryDate,
      originalAmount: originalAmount,
      discountRate: discountRate,
      discountAmount: discountAmount,
      totalAmount: totalAmount,
      totalQuantity: selectedQuote?.quantity || 0,
      shippedQuantity: 0,
      remainingQuantity: selectedQuote?.quantity || 0,
      shippingAddress: shippingAddress,
      shippingAddressDetail: shippingAddressDetail,
      receiverName: receiverName,
      receiverPhone: receiverPhone,
      shippingMethod: shippingMethod,
      status: 'registered',
      depositStatus: 'pending',
      depositAmount: 0,
      taxInvoiceStatus: 'not_issued',
      registeredBy: registeredBy,
      manager: manager,
      items: selectedQuote?.bomCalculations?.map(bom => ({
        id: bom.id,
        itemCode: bom.itemCode,
        itemName: bom.itemName,
        quantity: bom.calculatedQuantity,
        shippedQuantity: 0,
        remainingQuantity: bom.calculatedQuantity,
        unit: bom.unit,
        unitPrice: bom.unitPrice,
        totalPrice: bom.totalPrice
      })) || [],
      shippingLots: hasMultipleShipping ? shippingLots : undefined,
      hasMultipleShipping: hasMultipleShipping,
      divisionCount: hasMultipleShipping ? shippingLots.length : 0,
      currentRevision: 0,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      note: note
    };

    addSalesOrder(newOrder);
    toast.success("수주가 등록되었습니다.");
    
    // 완료 콜백 호출
    if (onComplete) {
      onComplete();
    } else {
      // 폼 초기화
      handleReset();
    }
  };

  // 폼 초기화
  const handleReset = () => {
    if (onCancel) {
      onCancel();
    } else {
      setSelectedQuote(null);
      setOrderNumber("");
      setCustomerName("");
      setCustomerCode("");
      setProjectName("");
      setSiteName("");
      setDeliveryDate("");
      setShippingAddress("");
      setShippingAddressDetail("");
      setReceiverName("");
      setReceiverPhone("");
      setShippingMethod('direct');
      setOriginalAmount(0);
      setDiscountRate(0);
      setDiscountAmount(0);
      setTotalAmount(0);
      setManager("");
      setHasMultipleShipping(false);
      setShippingLots([]);
      setNote("");
    }
  };

  // 금액 포맷팅
  const formatAmount = (amount: number) => {
    return amount.toLocaleString();
  };

  return (
    <PageLayout>
      <PageHeader
        title="수주 등록"
        subtitle="견적 기반 수주 등록 및 배송 정보 입력"
        icon={ShoppingCart}
        actions={
          onCancel && (
            <Button variant="outline" onClick={onCancel}>
              <ArrowLeft className="w-4 h-4 mr-2" />
              목록으로
            </Button>
          )
        }
      />

      <div className="space-y-6">
        {/* 견적 선택 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <FileText className="w-5 h-5" />
              확정된 견적 불러오기
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex gap-4">
              {selectedQuote ? (
                <div className="flex-1 p-4 bg-blue-50 rounded-lg">
                  <div className="flex justify-between items-start">
                    <div>
                      <div className="flex items-center gap-2 mb-2">
                        <Badge className="bg-blue-600">선택된 견적</Badge>
                        <span className="font-mono">{selectedQuote.quoteNumber}</span>
                      </div>
                      <div className="text-sm space-y-1">
                        <div><span className="text-gray-600">고객:</span> {selectedQuote.customerName}</div>
                        <div><span className="text-gray-600">프로젝트:</span> {selectedQuote.projectName}</div>
                        <div><span className="text-gray-600">금액:</span> ₩{formatAmount(selectedQuote.totalAmount || selectedQuote.amount || 0)}</div>
                      </div>
                    </div>
                    {!preSelectedQuote && (
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => setSelectedQuote(null)}
                      >
                        <X className="w-4 h-4" />
                      </Button>
                    )}
                  </div>
                </div>
              ) : (
                <Button onClick={() => setShowQuoteSelector(true)} className="flex-1" size="lg">
                  <Search className="w-4 h-4 mr-2" />
                  확정된 견적 불러오기
                </Button>
              )}
            </div>
          </CardContent>
        </Card>

        {/* 기본 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Building className="w-5 h-5" />
              기본 정보
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label htmlFor="orderNumber">수주번호 *</Label>
                <Input
                  id="orderNumber"
                  value={orderNumber}
                  onChange={(e) => setOrderNumber(e.target.value)}
                  placeholder="KD-OR-251029-01"
                />
              </div>
              
              <div>
                <Label htmlFor="orderDate">수주일 *</Label>
                <Input
                  id="orderDate"
                  type="date"
                  value={orderDate}
                  onChange={(e) => setOrderDate(e.target.value)}
                />
              </div>
              
              <div>
                <Label htmlFor="customerName">고객명 *</Label>
                <Input
                  id="customerName"
                  value={customerName}
                  onChange={(e) => setCustomerName(e.target.value)}
                  placeholder="고객명"
                  disabled={!!selectedQuote}
                />
              </div>
              
              <div>
                <Label htmlFor="customerCode">고객코드</Label>
                <Input
                  id="customerCode"
                  value={customerCode}
                  onChange={(e) => setCustomerCode(e.target.value)}
                  placeholder="CUS-001"
                  disabled={!!selectedQuote}
                />
              </div>
              
              <div>
                <Label htmlFor="projectName">프로젝트명 *</Label>
                <Input
                  id="projectName"
                  value={projectName}
                  onChange={(e) => setProjectName(e.target.value)}
                  placeholder="프로젝트명"
                  disabled={!!selectedQuote}
                />
              </div>
              
              <div>
                <Label htmlFor="siteName">현장명</Label>
                <Input
                  id="siteName"
                  value={siteName}
                  onChange={(e) => setSiteName(e.target.value)}
                  placeholder="현장명"
                />
              </div>
              
              <div>
                <Label htmlFor="deliveryDate">납품예정일 *</Label>
                <Input
                  id="deliveryDate"
                  type="date"
                  value={deliveryDate}
                  onChange={(e) => setDeliveryDate(e.target.value)}
                />
              </div>
              
              <div>
                <Label htmlFor="manager">담당 영업 *</Label>
                <Input
                  id="manager"
                  value={manager}
                  onChange={(e) => setManager(e.target.value)}
                  placeholder="담당자명"
                />
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 배송 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Truck className="w-5 h-5" />
              배송 정보
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="md:col-span-2">
                <Label htmlFor="shippingAddress">배송지 주소 *</Label>
                <Input
                  id="shippingAddress"
                  value={shippingAddress}
                  onChange={(e) => setShippingAddress(e.target.value)}
                  placeholder="배송지 주소"
                />
              </div>
              
              <div className="md:col-span-2">
                <Label htmlFor="shippingAddressDetail">상세 주소</Label>
                <Input
                  id="shippingAddressDetail"
                  value={shippingAddressDetail}
                  onChange={(e) => setShippingAddressDetail(e.target.value)}
                  placeholder="상세 주소"
                />
              </div>
              
              <div>
                <Label htmlFor="receiverName">수령인 *</Label>
                <Input
                  id="receiverName"
                  value={receiverName}
                  onChange={(e) => setReceiverName(e.target.value)}
                  placeholder="수령인 이름"
                />
              </div>
              
              <div>
                <Label htmlFor="receiverPhone">수령인 연락처 *</Label>
                <Input
                  id="receiverPhone"
                  value={receiverPhone}
                  onChange={(e) => setReceiverPhone(e.target.value)}
                  placeholder="010-0000-0000"
                />
              </div>
              
              <div>
                <Label htmlFor="shippingMethod">배송 방식 *</Label>
                <Select value={shippingMethod} onValueChange={(value: any) => setShippingMethod(value)}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="direct">직송</SelectItem>
                    <SelectItem value="cargo">화물</SelectItem>
                    <SelectItem value="express">택배</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 금액 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <DollarSign className="w-5 h-5" />
              금액 정보
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label htmlFor="originalAmount">원 금액</Label>
                <div className="relative">
                  <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">₩</span>
                  <Input
                    id="originalAmount"
                    type="number"
                    value={originalAmount}
                    onChange={(e) => setOriginalAmount(Number(e.target.value))}
                    className="pl-8"
                    disabled={!!selectedQuote}
                  />
                </div>
              </div>
              
              <div>
                <Label htmlFor="discountRate">할인율 (%)</Label>
                <Input
                  id="discountRate"
                  type="number"
                  value={discountRate}
                  onChange={(e) => handleDiscountRateChange(Number(e.target.value))}
                  min="0"
                  max="100"
                  step="0.1"
                />
              </div>
              
              <div>
                <Label htmlFor="discountAmount">할인 금액</Label>
                <div className="relative">
                  <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">₩</span>
                  <Input
                    id="discountAmount"
                    type="number"
                    value={discountAmount}
                    onChange={(e) => handleDiscountAmountChange(Number(e.target.value))}
                    className="pl-8"
                  />
                </div>
              </div>
              
              <div>
                <Label htmlFor="totalAmount">최종 금액</Label>
                <div className="relative">
                  <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500">₩</span>
                  <Input
                    id="totalAmount"
                    type="number"
                    value={totalAmount}
                    className="pl-8 font-bold text-blue-600"
                    disabled
                  />
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 분할 출고 */}
        <Card>
          <CardHeader>
            <div className="flex justify-between items-center">
              <CardTitle className="flex items-center gap-2">
                <Split className="w-5 h-5" />
                분할 출고 설정
              </CardTitle>
              <div className="flex items-center gap-2">
                <Label htmlFor="hasMultipleShipping" className="cursor-pointer">분할 출고</Label>
                <input
                  type="checkbox"
                  id="hasMultipleShipping"
                  checked={hasMultipleShipping}
                  onChange={(e) => setHasMultipleShipping(e.target.checked)}
                  className="w-4 h-4"
                />
              </div>
            </div>
          </CardHeader>
          {hasMultipleShipping && (
            <CardContent>
              <div className="space-y-4">
                <div>
                  <Label htmlFor="divisionType">분할 기준</Label>
                  <Select value={divisionType} onValueChange={(value: any) => setDivisionType(value)}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="location">개소별</SelectItem>
                      <SelectItem value="floor">층별</SelectItem>
                      <SelectItem value="material">자재별</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                
                <Button onClick={handleAddShippingLot} variant="outline">
                  <Plus className="w-4 h-4 mr-2" />
                  분할 로트 추가
                </Button>
                
                {shippingLots.length > 0 && (
                  <div className="space-y-2">
                    {shippingLots.map((lot, index) => (
                      <div key={lot.id} className="p-4 border rounded-lg">
                        <div className="flex justify-between items-center mb-2">
                          <Badge>{index + 1}차 출고</Badge>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleRemoveShippingLot(lot.id)}
                          >
                            <X className="w-4 h-4" />
                          </Button>
                        </div>
                        <div className="grid grid-cols-2 gap-2">
                          <div>
                            <Label>로트번호</Label>
                            <Input value={lot.lotNumber} disabled />
                          </div>
                          <div>
                            <Label>출고예정일</Label>
                            <Input 
                              type="date"
                              value={lot.scheduledDate}
                              onChange={(e) => {
                                const updated = shippingLots.map(l => 
                                  l.id === lot.id ? { ...l, scheduledDate: e.target.value } : l
                                );
                                setShippingLots(updated);
                              }}
                            />
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </CardContent>
          )}
        </Card>

        {/* 메모 */}
        <Card>
          <CardHeader>
            <CardTitle>메모</CardTitle>
          </CardHeader>
          <CardContent>
            <Textarea
              value={note}
              onChange={(e) => setNote(e.target.value)}
              placeholder="특이사항이나 메모를 입력하세요"
              rows={4}
            />
          </CardContent>
        </Card>

        {/* 저장 버튼 */}
        <div className="flex justify-end gap-2">
          <Button variant="outline" onClick={handleReset}>
            <X className="w-4 h-4 mr-2" />
            취소
          </Button>
          <Button onClick={handleSaveOrder}>
            <Save className="w-4 h-4 mr-2" />
            수주 등록
          </Button>
        </div>
      </div>

      {/* 견적 선택 모달 */}
      <Dialog open={showQuoteSelector} onOpenChange={setShowQuoteSelector}>
        <DialogContent className="max-w-5xl max-h-[85vh] overflow-hidden flex flex-col">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <FileText className="w-5 h-5 text-blue-600" />
              확정된 견적 선택
            </DialogTitle>
            <DialogDescription>
              견적관리에서 최종 확정 또는 승인된 견적을 선택하여 수주를 등록합니다.
            </DialogDescription>
          </DialogHeader>
          
          <div className="flex-1 space-y-4 overflow-auto">
            {/* 검색 */}
            <div className="sticky top-0 bg-white z-10 pb-4">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                <Input
                  placeholder="견적번호, 고객명, 프로젝트명으로 검색..."
                  value={searchQuoteTerm}
                  onChange={(e) => setSearchQuoteTerm(e.target.value)}
                  className="pl-10"
                />
              </div>
              
              {/* 검색 결과 요약 */}
              <div className="mt-2 text-sm text-gray-600">
                총 {filteredQuotes.length}개의 확정된 견적
              </div>
            </div>
            
            {/* 견적 목록 */}
            <div className="border rounded-lg overflow-hidden">
              <Table>
                <TableHeader>
                  <TableRow className="bg-gray-50">
                    <TableHead className="w-[140px]">견적번호</TableHead>
                    <TableHead className="w-[120px]">고객명</TableHead>
                    <TableHead className="w-[180px]">프로젝트명</TableHead>
                    <TableHead className="w-[100px]">견적일</TableHead>
                    <TableHead className="w-[120px] text-right">견적금액</TableHead>
                    <TableHead className="w-[80px]">담당자</TableHead>
                    <TableHead className="w-[90px]">상태</TableHead>
                    <TableHead className="w-[80px] text-center">선택</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredQuotes.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={8} className="text-center py-12">
                        <div className="flex flex-col items-center gap-3 text-gray-500">
                          <FileText className="w-12 h-12 text-gray-300" />
                          <div>
                            <p className="font-medium">확정된 견적이 없습니다</p>
                            <p className="text-sm mt-1">
                              견적관리에서 견적을 확정한 후 수주를 등록할 수 있습니다.
                            </p>
                          </div>
                        </div>
                      </TableCell>
                    </TableRow>
                  ) : (
                    filteredQuotes.map((quote) => (
                      <TableRow 
                        key={quote.id}
                        className="hover:bg-gray-50 cursor-pointer"
                        onClick={() => handleSelectQuote(quote)}
                      >
                        <TableCell className="font-mono text-sm">{quote.quoteNumber}</TableCell>
                        <TableCell className="font-medium">{quote.customerName}</TableCell>
                        <TableCell>{quote.projectName}</TableCell>
                        <TableCell className="text-sm text-gray-600">{quote.quoteDate}</TableCell>
                        <TableCell className="text-right font-medium">
                          ₩{formatAmount(quote.totalAmount || quote.amount || 0)}
                        </TableCell>
                        <TableCell className="text-sm text-gray-600">
                          {quote.manager || quote.author || '-'}
                        </TableCell>
                        <TableCell>
                          <Badge className={quote.status === 'finalized' ? "bg-green-600" : "bg-blue-600"}>
                            {quote.status === 'finalized' ? "최종확정" : "승인완료"}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-center">
                          <Button
                            size="sm"
                            onClick={(e) => {
                              e.stopPropagation();
                              handleSelectQuote(quote);
                            }}
                          >
                            선택
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>
            
            {/* 안내 메시지 */}
            {filteredQuotes.length > 0 && (
              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <div className="flex gap-2">
                  <div className="text-blue-600 mt-0.5">
                    <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
                    </svg>
                  </div>
                  <div className="flex-1">
                    <p className="text-sm font-medium text-blue-900">견적 선택 안내</p>
                    <ul className="text-sm text-blue-800 mt-1 space-y-1">
                      <li>• 견적을 선택하면 고객정보와 프로젝트 정보가 자동으로 입력됩니다.</li>
                      <li>• 행을 클릭하거나 '선택' 버튼을 눌러 견적을 선택할 수 있습니다.</li>
                      <li>• 확정된 견적만 수주 등록이 가능합니다.</li>
                    </ul>
                  </div>
                </div>
              </div>
            )}
          </div>
        </DialogContent>
      </Dialog>
    </PageLayout>
  );
}