/**
 * 출하관리
 * 출하 목록 및 출고순위 관리
 */

import { useState, useMemo } from "react";
import { 
  Truck, Package, Search, Download, Calendar, Edit, FileText, 
  TrendingUp, AlertCircle, CheckCircle, Clock, DollarSign,
  ArrowUpDown, MoreVertical, Copy, History, Plus, Trash2
} from "lucide-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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Badge } from "./ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "./ui/dialog";
import { HoverCard, HoverCardContent, HoverCardTrigger } from "./ui/hover-card";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "./ui/dropdown-menu";
import { toast } from "sonner@2.0.3";
import { Checkbox } from "./ui/checkbox";
import { ShippingRegistration } from "./ShippingRegistration";

// 출하 데이터 타입
interface ShippingItem {
  id: string;
  shippingNo: string;        // 출하번호
  orderLot: string;          // 수주LOT
  splitLot?: string;         // 분할LOT
  buyer: string;             // 발주처
  site: string;              // 현장
  quantity: number;          // 수량
  scheduledDate: string;     // 출고예정일
  priority: number;          // 출고순위
  deliveryMethod: string;    // 배송방식
  paymentStatus: 'pending' | 'partial' | 'completed'; // 입금상태
  shippingStatus: 'ready' | 'preparing' | 'partial' | 'completed'; // 출하상태
  creditGrade?: 'A' | 'B' | 'C'; // 신용등급
  workCompleted: boolean;    // 작업완료여부
  arrivedAtZone: boolean;    // 출고구역 도착
  previousShippings?: Array<{ // 이전출고이력
    date: string;
    quantity: number;
    shippingNo: string;
  }>;
}

export function ShipmentManagement() {
  const [viewMode, setViewMode] = useState<'list' | 'register'>('list');
  const [editingShipping, setEditingShipping] = useState<any>(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [filterStatus, setFilterStatus] = useState<string>("all");
  const [filterDelivery, setFilterDelivery] = useState<string>("all");
  const [filterPayment, setFilterPayment] = useState<string>("all");
  const [filterBuyer, setFilterBuyer] = useState<string>("all");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  
  const [selectedItems, setSelectedItems] = useState<string[]>([]);
  const [priorityDialogOpen, setPriorityDialogOpen] = useState(false);
  const [historyDialogOpen, setHistoryDialogOpen] = useState(false);
  const [selectedHistory, setSelectedHistory] = useState<ShippingItem | null>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);

  // Mock 데이터
  const [shippingData, setShippingData] = useState<ShippingItem[]>([
    {
      id: "1",
      shippingNo: "SH-2025-001",
      orderLot: "ORD-2025-A001",
      splitLot: "SPLIT-001",
      buyer: "한빛에스티",
      site: "반포3지구2공구(117동)",
      quantity: 50,
      scheduledDate: "2025-11-28",
      priority: 1,
      deliveryMethod: "택배(직불)",
      paymentStatus: "completed",
      shippingStatus: "ready",
      creditGrade: "A",
      workCompleted: true,
      arrivedAtZone: true,
      previousShippings: [
        { date: "2025-11-20", quantity: 30, shippingNo: "SH-2025-001-1" },
        { date: "2025-11-22", quantity: 20, shippingNo: "SH-2025-001-2" }
      ]
    },
    {
      id: "2",
      shippingNo: "SH-2025-002",
      orderLot: "ORD-2025-A002",
      buyer: "주일기업",
      site: "플라이크은평",
      quantity: 100,
      scheduledDate: "2025-11-29",
      priority: 2,
      deliveryMethod: "직접수령(선불)",
      paymentStatus: "partial",
      shippingStatus: "preparing",
      creditGrade: "B",
      workCompleted: true,
      arrivedAtZone: false
    },
    {
      id: "3",
      shippingNo: "SH-2025-003",
      orderLot: "ORD-2025-A003",
      buyer: "성지금속",
      site: "한국체대부산경기장",
      quantity: 75,
      scheduledDate: "2025-11-30",
      priority: 3,
      deliveryMethod: "상차(선불)",
      paymentStatus: "pending",
      shippingStatus: "preparing",
      creditGrade: "C",
      workCompleted: false,
      arrivedAtZone: false
    },
    {
      id: "4",
      shippingNo: "SH-2025-004",
      orderLot: "ORD-2025-A004",
      splitLot: "SPLIT-002",
      buyer: "삼진오토도어",
      site: "강진종합초교(1차)",
      quantity: 120,
      scheduledDate: "2025-12-01",
      priority: 4,
      deliveryMethod: "경동화물(선불)",
      paymentStatus: "completed",
      shippingStatus: "partial",
      creditGrade: "A",
      workCompleted: true,
      arrivedAtZone: true,
      previousShippings: [
        { date: "2025-11-25", quantity: 60, shippingNo: "SH-2025-004-1" }
      ]
    },
    {
      id: "5",
      shippingNo: "SH-2025-005",
      orderLot: "ORD-2025-A005",
      buyer: "대한건설",
      site: "송도신도시 2단지",
      quantity: 80,
      scheduledDate: "2025-12-02",
      priority: 5,
      deliveryMethod: "부불출고",
      paymentStatus: "pending",
      shippingStatus: "ready",
      creditGrade: "B",
      workCompleted: true,
      arrivedAtZone: true
    }
  ]);

  // 대시보드 통계
  const dashboardStats = useMemo(() => {
    return {
      totalShipping: shippingData.length,
      readyToShip: shippingData.filter(s => s.shippingStatus === 'ready').length,
      preparing: shippingData.filter(s => s.shippingStatus === 'preparing').length,
      pendingPayment: shippingData.filter(s => s.paymentStatus === 'pending' && (s.creditGrade === 'B' || s.creditGrade === 'C')).length
    };
  }, [shippingData]);

  // 필터링된 데이터
  const filteredData = useMemo(() => {
    return shippingData.filter(item => {
      // 검색어 필터
      if (searchTerm && !item.shippingNo.toLowerCase().includes(searchTerm.toLowerCase()) &&
          !item.buyer.toLowerCase().includes(searchTerm.toLowerCase()) &&
          !item.site.toLowerCase().includes(searchTerm.toLowerCase())) {
        return false;
      }
      
      // 상태 필터
      if (filterStatus !== "all" && item.shippingStatus !== filterStatus) return false;
      
      // 배송방식 필터
      if (filterDelivery !== "all" && !item.deliveryMethod.includes(filterDelivery)) return false;
      
      // 입금상태 필터
      if (filterPayment !== "all" && item.paymentStatus !== filterPayment) return false;
      
      // 거래처 필터
      if (filterBuyer !== "all" && item.buyer !== filterBuyer) return false;
      
      return true;
    });
  }, [shippingData, searchTerm, filterStatus, filterDelivery, filterPayment, filterBuyer]);

  // 거래처 목록 추출
  const buyerList = useMemo(() => {
    return Array.from(new Set(shippingData.map(item => item.buyer)));
  }, [shippingData]);

  // 상태별 색상
  const getStatusBadge = (status: string) => {
    const statusMap: Record<string, { label: string; className: string }> = {
      ready: { label: "출고준비", className: "bg-blue-100 text-blue-700 border-blue-200" },
      preparing: { label: "준비중", className: "bg-yellow-100 text-yellow-700 border-yellow-200" },
      partial: { label: "분할출고", className: "bg-purple-100 text-purple-700 border-purple-200" },
      completed: { label: "출고완료", className: "bg-green-100 text-green-700 border-green-200" }
    };
    return statusMap[status] || statusMap.ready;
  };

  const getPaymentBadge = (status: string) => {
    const statusMap: Record<string, { label: string; className: string }> = {
      pending: { label: "미입금", className: "bg-red-100 text-red-700 border-red-200" },
      partial: { label: "부분입금", className: "bg-orange-100 text-orange-700 border-orange-200" },
      completed: { label: "입금완료", className: "bg-green-100 text-green-700 border-green-200" }
    };
    return statusMap[status] || statusMap.pending;
  };

  // 출고순위 변경
  const handlePriorityChange = () => {
    if (selectedItems.length === 0) {
      toast.error("항목을 선택해주세요");
      return;
    }
    setPriorityDialogOpen(true);
  };

  // 이전 출고이력 조회
  const handleViewHistory = (item: ShippingItem) => {
    setSelectedHistory(item);
    setHistoryDialogOpen(true);
  };

  // 출고증 발행
  const handlePrintShippingDoc = () => {
    if (selectedItems.length === 0) {
      toast.error("항목을 선택해주세요");
      return;
    }
    toast.success(`${selectedItems.length}건의 출고증을 발행합니다`);
  };

  // 엑셀 다운로드
  const handleExcelDownload = () => {
    toast.success("엑셀 다운로드를 시작합니다");
  };

  // 체크박스 토글
  const toggleSelectItem = (id: string) => {
    setSelectedItems(prev => 
      prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id]
    );
  };

  const toggleSelectAll = () => {
    if (selectedItems.length === filteredData.length) {
      setSelectedItems([]);
    } else {
      setSelectedItems(filteredData.map(item => item.id));
    }
  };

  return (
    <div className="p-6 space-y-6">
      {viewMode === 'register' ? (
        <ShippingRegistration
          editingShipping={editingShipping}
          onSave={(data) => {
            // TODO: 실제 저장 로직
            console.log('Saving shipping:', data);
            setViewMode('list');
            setEditingShipping(null);
          }}
          onCancel={() => {
            setViewMode('list');
            setEditingShipping(null);
          }}
        />
      ) : (
        <>
          {/* 헤더 */}
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-3xl font-bold">출하관리</h1>
              <p className="text-muted-foreground mt-1">출하 목록 및 출고순위 관리</p>
            </div>
            <Button onClick={() => setViewMode('register')}>
              <Plus className="h-4 w-4 mr-2" />
              출하 등록
            </Button>
          </div>

          {/* 대시보드 카드 */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">전체 출하</CardTitle>
                <Package className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">{dashboardStats.totalShipping}</div>
                <p className="text-xs text-muted-foreground">총 출하 건수</p>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">출고준비</CardTitle>
                <CheckCircle className="h-4 w-4 text-blue-600" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold text-blue-600">{dashboardStats.readyToShip}</div>
                <p className="text-xs text-muted-foreground">출고 가능</p>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">준비중</CardTitle>
                <Clock className="h-4 w-4 text-yellow-600" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold text-yellow-600">{dashboardStats.preparing}</div>
                <p className="text-xs text-muted-foreground">작업 진행중</p>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">입금확인 필요</CardTitle>
                <AlertCircle className="h-4 w-4 text-red-600" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold text-red-600">{dashboardStats.pendingPayment}</div>
                <p className="text-xs text-muted-foreground">신용등급 B/C</p>
              </CardContent>
            </Card>
          </div>

          {/* 필터 영역 */}
          <Card>
            <CardHeader>
              <CardTitle>검색 및 필터</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-6 gap-4">
                {/* 기간 */}
                <div className="md:col-span-2">
                  <Label>출고예정일</Label>
                  <div className="flex gap-2 mt-1">
                    <Input 
                      type="date" 
                      value={startDate}
                      onChange={(e) => setStartDate(e.target.value)}
                      placeholder="시작일"
                    />
                    <Input 
                      type="date" 
                      value={endDate}
                      onChange={(e) => setEndDate(e.target.value)}
                      placeholder="종료일"
                    />
                  </div>
                </div>

                {/* 출고상태 */}
                <div>
                  <Label>출고상태</Label>
                  <Select value={filterStatus} onValueChange={setFilterStatus}>
                    <SelectTrigger className="mt-1">
                      <SelectValue placeholder="전체" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">전체</SelectItem>
                      <SelectItem value="ready">출고준비</SelectItem>
                      <SelectItem value="preparing">준비중</SelectItem>
                      <SelectItem value="partial">분할출고</SelectItem>
                      <SelectItem value="completed">출고완료</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                {/* 배송방식 */}
                <div>
                  <Label>배송방식</Label>
                  <Select value={filterDelivery} onValueChange={setFilterDelivery}>
                    <SelectTrigger className="mt-1">
                      <SelectValue placeholder="전체" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">전체</SelectItem>
                      <SelectItem value="택배">택배</SelectItem>
                      <SelectItem value="직접수령">직접수령</SelectItem>
                      <SelectItem value="상차">상차</SelectItem>
                      <SelectItem value="화물">화물</SelectItem>
                      <SelectItem value="부불">부불출고</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                {/* 입금상태 */}
                <div>
                  <Label>입금상태</Label>
                  <Select value={filterPayment} onValueChange={setFilterPayment}>
                    <SelectTrigger className="mt-1">
                      <SelectValue placeholder="전체" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">전체</SelectItem>
                      <SelectItem value="pending">미입금</SelectItem>
                      <SelectItem value="partial">부분입금</SelectItem>
                      <SelectItem value="completed">입금완료</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                {/* 거래처 */}
                <div>
                  <Label>거래처</Label>
                  <Select value={filterBuyer} onValueChange={setFilterBuyer}>
                    <SelectTrigger className="mt-1">
                      <SelectValue placeholder="전체" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">전체</SelectItem>
                      {buyerList.map(buyer => (
                        <SelectItem key={buyer} value={buyer}>{buyer}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>

              {/* 검색 및 버튼 */}
              <div className="flex flex-col md:flex-row gap-3 mt-4">
                <div className="relative flex-1">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <Input
                    placeholder="출하번호, 발주처, 현장명으로 검색..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-9"
                  />
                </div>
                <div className="flex gap-2 flex-wrap">
                  <Button onClick={() => {
                    setSearchTerm("");
                    setFilterStatus("all");
                    setFilterDelivery("all");
                    setFilterPayment("all");
                    setFilterBuyer("all");
                    setStartDate("");
                    setEndDate("");
                  }}>
                    <Search className="h-4 w-4 mr-2" />
                    조회
                  </Button>
                  <Button variant="outline" onClick={handlePriorityChange}>
                    <ArrowUpDown className="h-4 w-4 mr-2" />
                    출고순위변경
                  </Button>
                  <Button variant="outline">
                    <Truck className="h-4 w-4 mr-2" />
                    배송조율
                  </Button>
                  <Button variant="outline" onClick={handlePrintShippingDoc}>
                    <FileText className="h-4 w-4 mr-2" />
                    출고증발행
                  </Button>
                  <Button variant="outline" onClick={handleExcelDownload}>
                    <Download className="h-4 w-4 mr-2" />
                    엑셀
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* 일괄 삭제 확인 다이얼로그 */}
          <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
            <DialogContent>
              <DialogHeader>
                <DialogTitle className="flex items-center gap-2 text-red-600">
                  <AlertCircle className="h-5 w-5" />
                  일괄 삭제 확인
                </DialogTitle>
                <DialogDescription>
                  선택한 {selectedItems.length}개의 항목을 삭제하시겠습니까?
                </DialogDescription>
              </DialogHeader>
              <div className="space-y-4 py-4">
                <div className="p-4 bg-red-50 border border-red-200 rounded-lg">
                  <p className="text-sm text-red-800">
                    <strong>⚠️ 경고:</strong> 삭제된 데이터는 복구할 수 없습니다. 신중하게 확인 후 진행해주세요.
                  </p>
                </div>
                <div className="text-sm space-y-1">
                  <p className="font-semibold">삭제 대상:</p>
                  <ul className="list-disc list-inside pl-2 space-y-1 text-muted-foreground">
                    {selectedItems.slice(0, 3).map(id => {
                      const item = shippingData.find(s => s.id === id);
                      return item ? (
                        <li key={id}>
                          {item.shippingNo} - {item.buyer} ({item.site})
                        </li>
                      ) : null;
                    })}
                    {selectedItems.length > 3 && (
                      <li className="text-xs">외 {selectedItems.length - 3}건...</li>
                    )}
                  </ul>
                </div>
              </div>
              <DialogFooter>
                <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
                  취소
                </Button>
                <Button 
                  variant="destructive" 
                  onClick={() => {
                    setShippingData(prev => prev.filter(item => !selectedItems.includes(item.id)));
                    toast.success(`${selectedItems.length}개 항목이 삭제되었습니다`);
                    setSelectedItems([]);
                    setDeleteDialogOpen(false);
                  }}
                >
                  삭제
                </Button>
              </DialogFooter>
            </DialogContent>
          </Dialog>

          {/* 테이블 */}
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle>출하 목록 ({filteredData.length}건)</CardTitle>
                <div className="flex items-center gap-3">
                  {selectedItems.length > 0 && (
                    <span className="text-sm text-muted-foreground">
                      {selectedItems.length}건 선택됨
                    </span>
                  )}
                  {selectedItems.length >= 2 && (
                    <Button
                      variant="destructive"
                      size="sm"
                      onClick={() => setDeleteDialogOpen(true)}
                      className="gap-2"
                    >
                      <Trash2 className="h-4 w-4" />
                      일괄 삭제
                    </Button>
                  )}
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <div className="border rounded-lg overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-muted/50">
                      <TableHead className="w-[50px]">
                        <Checkbox
                          checked={selectedItems.length === filteredData.length && filteredData.length > 0}
                          onCheckedChange={toggleSelectAll}
                        />
                      </TableHead>
                      <TableHead className="text-center w-[60px]">번호</TableHead>
                      <TableHead className="text-center">출하번호</TableHead>
                      <TableHead className="text-center">수주LOT</TableHead>
                      <TableHead className="text-center">분할LOT</TableHead>
                      <TableHead className="text-center">발주처</TableHead>
                      <TableHead className="text-center">현장</TableHead>
                      <TableHead className="text-center">수량</TableHead>
                      <TableHead className="text-center">출고예정일</TableHead>
                      <TableHead className="text-center">출고순위</TableHead>
                      <TableHead className="text-center">배송방식</TableHead>
                      <TableHead className="text-center">입금상태</TableHead>
                      <TableHead className="text-center">출하상태</TableHead>
                      <TableHead className="text-center">작업상태</TableHead>
                      <TableHead className="text-center">이전출고이력</TableHead>
                      <TableHead className="text-center w-[80px]">액션</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredData.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={16} className="text-center py-8 text-muted-foreground">
                          조회된 데이터가 없습니다
                        </TableCell>
                      </TableRow>
                    ) : (
                      filteredData.map((item, index) => {
                        const statusBadge = getStatusBadge(item.shippingStatus);
                        const paymentBadge = getPaymentBadge(item.paymentStatus);
                        const needsPaymentCheck = (item.creditGrade === 'B' || item.creditGrade === 'C') && item.paymentStatus === 'pending';

                        return (
                          <TableRow key={item.id} className="hover:bg-muted/30">
                            <TableCell onClick={(e) => e.stopPropagation()}>
                              <Checkbox
                                checked={selectedItems.includes(item.id)}
                                onCheckedChange={() => toggleSelectItem(item.id)}
                              />
                            </TableCell>
                            <TableCell className="text-center text-muted-foreground">
                              {filteredData.length - index}
                            </TableCell>
                            <TableCell className="text-center font-mono text-sm">
                              {item.shippingNo}
                            </TableCell>
                            <TableCell className="text-center font-mono text-sm">
                              {item.orderLot}
                            </TableCell>
                            <TableCell className="text-center font-mono text-sm">
                              {item.splitLot ? (
                                <Badge variant="outline" className="bg-purple-50">
                                  {item.splitLot}
                                </Badge>
                              ) : (
                                <span className="text-muted-foreground">-</span>
                              )}
                            </TableCell>
                            <TableCell className="text-center">
                              <div className="flex items-center justify-center gap-2">
                                {item.buyer}
                                {item.creditGrade && (
                                  <Badge 
                                    variant="outline" 
                                    className={`text-xs ${
                                      item.creditGrade === 'A' ? 'bg-green-50' : 
                                      item.creditGrade === 'B' ? 'bg-yellow-50' : 
                                      'bg-red-50'
                                    }`}
                                  >
                                    {item.creditGrade}
                                  </Badge>
                                )}
                              </div>
                            </TableCell>
                            <TableCell className="text-center max-w-[200px] truncate">
                              {item.site}
                            </TableCell>
                            <TableCell className="text-center font-semibold">
                              {item.quantity}
                            </TableCell>
                            <TableCell className="text-center text-sm">
                              {item.scheduledDate}
                            </TableCell>
                            <TableCell className="text-center">
                              <Badge variant="outline" className="font-semibold">
                                {item.priority}위
                              </Badge>
                            </TableCell>
                            <TableCell className="text-center text-sm">
                              {item.deliveryMethod}
                            </TableCell>
                            <TableCell className="text-center">
                              <div className="flex flex-col items-center gap-1">
                                <Badge className={`${paymentBadge.className} border`}>
                                  {paymentBadge.label}
                                </Badge>
                                {needsPaymentCheck && (
                                  <span className="text-xs text-red-600 flex items-center gap-1">
                                    <AlertCircle className="h-3 w-3" />
                                    확인필요
                                  </span>
                                )}
                              </div>
                            </TableCell>
                            <TableCell className="text-center">
                              <Badge className={`${statusBadge.className} border`}>
                                {statusBadge.label}
                              </Badge>
                            </TableCell>
                            <TableCell className="text-center">
                              <div className="flex flex-col items-center gap-1">
                                <div className="flex items-center gap-2">
                                  <span className="text-xs">작업:</span>
                                  {item.workCompleted ? (
                                    <CheckCircle className="h-4 w-4 text-green-600" />
                                  ) : (
                                    <Clock className="h-4 w-4 text-yellow-600" />
                                  )}
                                </div>
                                <div className="flex items-center gap-2">
                                  <span className="text-xs">도착:</span>
                                  {item.arrivedAtZone ? (
                                    <CheckCircle className="h-4 w-4 text-green-600" />
                                  ) : (
                                    <Clock className="h-4 w-4 text-yellow-600" />
                                  )}
                                </div>
                              </div>
                            </TableCell>
                            <TableCell className="text-center">
                              {item.previousShippings && item.previousShippings.length > 0 ? (
                                <HoverCard>
                                  <HoverCardTrigger asChild>
                                    <Button 
                                      variant="ghost" 
                                      size="sm"
                                      onClick={() => handleViewHistory(item)}
                                    >
                                      <History className="h-4 w-4 mr-1" />
                                      {item.previousShippings.length}건
                                    </Button>
                                  </HoverCardTrigger>
                                  <HoverCardContent className="w-80">
                                    <div className="space-y-2">
                                      <h4 className="font-semibold text-sm">이전 출고이력</h4>
                                      {item.previousShippings.map((history, idx) => (
                                        <div key={idx} className="flex justify-between text-xs border-b pb-1">
                                          <span>{history.date}</span>
                                          <span>{history.shippingNo}</span>
                                          <span className="font-semibold">{history.quantity}개</span>
                                        </div>
                                      ))}
                                    </div>
                                  </HoverCardContent>
                                </HoverCard>
                              ) : (
                                <span className="text-muted-foreground text-sm">-</span>
                              )}
                            </TableCell>
                            <TableCell className="text-center">
                              <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                  <Button variant="ghost" size="sm">
                                    <MoreVertical className="h-4 w-4" />
                                  </Button>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent align="end">
                                  <DropdownMenuItem>
                                    <Edit className="h-4 w-4 mr-2" />
                                    수정
                                  </DropdownMenuItem>
                                  <DropdownMenuItem onClick={() => handleViewHistory(item)}>
                                    <History className="h-4 w-4 mr-2" />
                                    출고이력
                                  </DropdownMenuItem>
                                  <DropdownMenuItem>
                                    <FileText className="h-4 w-4 mr-2" />
                                    출고증 발행
                                  </DropdownMenuItem>
                                </DropdownMenuContent>
                              </DropdownMenu>
                            </TableCell>
                          </TableRow>
                        );
                      })
                    )}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>

          {/* 출고순위 변경 다이얼로그 */}
          <Dialog open={priorityDialogOpen} onOpenChange={setPriorityDialogOpen}>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>출고순위 변경</DialogTitle>
                <DialogDescription>
                  선택한 {selectedItems.length}건의 출고순위를 변경합니다
                </DialogDescription>
              </DialogHeader>
              <div className="space-y-4 py-4">
                <div>
                  <Label>새로운 순위</Label>
                  <Input type="number" min="1" placeholder="순위 입력" className="mt-2" />
                </div>
                <div className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg text-sm">
                  <p className="text-yellow-800">
                    💡 순위가 변경되면 기존 순위는 자동으로 조정됩니다
                  </p>
                </div>
              </div>
              <DialogFooter>
                <Button variant="outline" onClick={() => setPriorityDialogOpen(false)}>
                  취소
                </Button>
                <Button onClick={() => {
                  toast.success("출고순위가 변경되었습니다");
                  setPriorityDialogOpen(false);
                }}>
                  변경
                </Button>
              </DialogFooter>
            </DialogContent>
          </Dialog>

          {/* 이전 출고이력 다이얼로그 */}
          <Dialog open={historyDialogOpen} onOpenChange={setHistoryDialogOpen}>
            <DialogContent className="max-w-2xl">
              <DialogHeader>
                <DialogTitle>이전 출고이력</DialogTitle>
                <DialogDescription>
                  {selectedHistory?.shippingNo} - {selectedHistory?.orderLot}
                </DialogDescription>
              </DialogHeader>
              <div className="space-y-4 py-4">
                <div className="grid grid-cols-2 gap-4 p-4 bg-muted rounded-lg">
                  <div>
                    <span className="text-sm text-muted-foreground">발주처:</span>
                    <span className="font-semibold ml-2">{selectedHistory?.buyer}</span>
                  </div>
                  <div>
                    <span className="text-sm text-muted-foreground">현장:</span>
                    <span className="font-semibold ml-2">{selectedHistory?.site}</span>
                  </div>
                  <div>
                    <span className="text-sm text-muted-foreground">총 수량:</span>
                    <span className="font-semibold ml-2">{selectedHistory?.quantity}</span>
                  </div>
                  <div>
                    <span className="text-sm text-muted-foreground">분할 출고:</span>
                    <span className="font-semibold ml-2">
                      {selectedHistory?.previousShippings && selectedHistory.previousShippings.length > 0 ? 'O' : 'X'}
                    </span>
                  </div>
                </div>

                {selectedHistory?.previousShippings && selectedHistory.previousShippings.length > 0 ? (
                  <div className="border rounded-lg overflow-hidden">
                    <Table>
                      <TableHeader>
                        <TableRow className="bg-muted/50">
                          <TableHead className="text-center">출고일</TableHead>
                          <TableHead className="text-center">출하번호</TableHead>
                          <TableHead className="text-center">출고수량</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {selectedHistory.previousShippings.map((history, idx) => (
                          <TableRow key={idx}>
                            <TableCell className="text-center">{history.date}</TableCell>
                            <TableCell className="text-center font-mono text-sm">{history.shippingNo}</TableCell>
                            <TableCell className="text-center font-semibold">{history.quantity}</TableCell>
                          </TableRow>
                        ))}
                        <TableRow className="bg-muted/30 font-semibold">
                          <TableCell className="text-center" colSpan={2}>합계</TableCell>
                          <TableCell className="text-center">
                            {selectedHistory.previousShippings.reduce((sum, h) => sum + h.quantity, 0)}
                          </TableCell>
                        </TableRow>
                      </TableBody>
                    </Table>
                  </div>
                ) : (
                  <div className="text-center py-8 text-muted-foreground">
                    이전 출고이력이 없습니다
                  </div>
                )}
              </div>
              <DialogFooter>
                <Button onClick={() => setHistoryDialogOpen(false)}>
                  닫기
                </Button>
              </DialogFooter>
            </DialogContent>
          </Dialog>
        </>
      )}
    </div>
  );
}