import { useState } from "react";
import { PageLayout } from "./organisms/PageLayout";
import { PageHeader } from "./organisms/PageHeader";
import { StatCards } from "./organisms/StatCards";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
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 { 
  Truck, 
  Plus,
  Search,
  Package,
  Clock,
  CheckCircle,
  AlertTriangle,
  Calendar,
  MapPin,
  User,
  Phone,
  FileText
} from "lucide-react";
import { toast } from "sonner@2.0.3";
import { SalesOrder, ShippingSchedule, ShippingOrder, ShippingOrderItem } from "./contexts/DataContext";

export function ShippingScheduleManagement() {
  const [searchTerm, setSearchTerm] = useState("");
  const [isShippingDialogOpen, setIsShippingDialogOpen] = useState(false);
  const [selectedSchedule, setSelectedSchedule] = useState<{
    order: SalesOrder;
    schedule: ShippingSchedule;
  } | null>(null);

  // 출고 지시 폼 상태
  const [lotNumber, setLotNumber] = useState("");
  const [lotProductionDate, setLotProductionDate] = useState("");
  const [actualShippingDate, setActualShippingDate] = useState(new Date().toISOString().split('T')[0]);

  // Mock 데이터 - 분할 출고가 있는 수주 목록
  const [salesOrders] = useState<SalesOrder[]>([
    {
      id: 'SO-001',
      orderNumber: 'KD-PR-25001',
      customerName: '(주)한국건설',
      projectName: '서울 오피스빌딩',
      orderDate: '2025-01-15',
      deliveryDate: '2025-11-10',
      totalAmount: 45000000,
      totalQuantity: 100,
      shippedQuantity: 40,
      remainingQuantity: 60,
      status: 'shipping',
      hasMultipleShipping: true,
      items: [
        { id: '1', itemName: '셔터 세트', quantity: 100, unitPrice: 450000, totalPrice: 45000000 }
      ],
      shippingSchedules: [
        {
          id: 'SS-001-1',
          scheduleNumber: 1,
          scheduledDate: '2025-10-20',
          quantity: 40,
          remainingQuantity: 60,
          shippingAddress: '서울시 강남구 테헤란로 123',
          receiverName: '김담당',
          receiverPhone: '010-1234-5678',
          status: 'shipped',
          shippingOrderId: 'SH-001',
          actualShippingDate: '2025-10-20',
          note: '1차 출고 - 본관'
        },
        {
          id: 'SS-001-2',
          scheduleNumber: 2,
          scheduledDate: '2025-10-30',
          quantity: 30,
          remainingQuantity: 30,
          shippingAddress: '서울시 강남구 테헤란로 456',
          receiverName: '이담당',
          receiverPhone: '010-2345-6789',
          status: 'ready',
          note: '2차 출고 - 별관'
        },
        {
          id: 'SS-001-3',
          scheduleNumber: 3,
          scheduledDate: '2025-11-10',
          quantity: 30,
          remainingQuantity: 0,
          shippingAddress: '서울시 강남구 테헤란로 789',
          receiverName: '박담당',
          receiverPhone: '010-3456-7890',
          status: 'scheduled',
          note: '3차 출고 - 후관'
        }
      ]
    },
    {
      id: 'SO-002',
      orderNumber: 'KD-PR-25002',
      customerName: '(주)대한산업',
      projectName: '부산 공장 신축',
      orderDate: '2025-01-20',
      deliveryDate: '2025-12-15',
      totalAmount: 60000000,
      totalQuantity: 150,
      shippedQuantity: 0,
      remainingQuantity: 150,
      status: 'production',
      hasMultipleShipping: true,
      items: [
        { id: '2', itemName: '블라인드 세트', quantity: 150, unitPrice: 400000, totalPrice: 60000000 }
      ],
      shippingSchedules: [
        {
          id: 'SS-002-1',
          scheduleNumber: 1,
          scheduledDate: '2025-11-15',
          quantity: 50,
          remainingQuantity: 100,
          shippingAddress: '부산시 해운대구 센텀중앙로 100',
          receiverName: '최담당',
          receiverPhone: '010-4567-8901',
          status: 'scheduled',
          note: '1차 출고 - A동'
        },
        {
          id: 'SS-002-2',
          scheduleNumber: 2,
          scheduledDate: '2025-12-01',
          quantity: 50,
          remainingQuantity: 50,
          shippingAddress: '부산시 해운대구 센텀중앙로 200',
          receiverName: '정담당',
          receiverPhone: '010-5678-9012',
          status: 'scheduled',
          note: '2차 출고 - B동'
        },
        {
          id: 'SS-002-3',
          scheduleNumber: 3,
          scheduledDate: '2025-12-15',
          quantity: 50,
          remainingQuantity: 0,
          shippingAddress: '부산시 해운대구 센텀중앙로 300',
          receiverName: '한담당',
          receiverPhone: '010-6789-0123',
          status: 'scheduled',
          note: '3차 출고 - C동'
        }
      ]
    }
  ]);

  // 모든 출고 계획을 펼친 리스트 (테이블 표시용)
  const allSchedules = salesOrders
    .filter(order => order.hasMultipleShipping && order.shippingSchedules)
    .flatMap(order => 
      order.shippingSchedules!.map(schedule => ({
        order,
        schedule
      }))
    )
    .filter(item => {
      if (!searchTerm) return true;
      const search = searchTerm.toLowerCase();
      return (
        item.order.orderNumber.toLowerCase().includes(search) ||
        item.order.customerName.toLowerCase().includes(search) ||
        item.order.projectName.toLowerCase().includes(search)
      );
    });

  // 통계 계산
  const totalSchedules = allSchedules.length;
  const scheduledCount = allSchedules.filter(s => s.schedule.status === 'scheduled').length;
  const readyCount = allSchedules.filter(s => s.schedule.status === 'ready').length;
  const shippedCount = allSchedules.filter(s => s.schedule.status === 'shipped').length;

  // 상태 뱃지
  const getStatusBadge = (status: ShippingSchedule['status']) => {
    switch (status) {
      case 'scheduled':
        return <Badge variant="outline" className="bg-gray-50 text-gray-700 border-gray-200">예정</Badge>;
      case 'ready':
        return <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">준비완료</Badge>;
      case 'shipped':
        return <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">출고완료</Badge>;
      case 'completed':
        return <Badge variant="outline" className="bg-purple-50 text-purple-700 border-purple-200">인도완료</Badge>;
      default:
        return <Badge variant="outline">-</Badge>;
    }
  };

  // 출고 지시서 생성
  const generateShippingNumber = (orderNumber: string, scheduleNumber: number) => {
    const today = new Date();
    const year = today.getFullYear().toString().slice(-2);
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    return `KD-OT-${year}${month}${day}-${scheduleNumber.toString().padStart(2, '0')}`;
  };

  // 출고 지시 처리
  const handleCreateShippingOrder = () => {
    if (!selectedSchedule) return;

    if (!lotNumber.trim()) {
      toast.error("로트 번호를 입력해주세요.");
      return;
    }

    const { order, schedule } = selectedSchedule;
    const shippingNumber = generateShippingNumber(order.orderNumber, schedule.scheduleNumber);

    const shippingOrder: ShippingOrder = {
      id: `SH-${Date.now()}`,
      shippingNumber,
      salesOrderId: order.id,
      salesOrderNumber: order.orderNumber,
      scheduleNumber: schedule.scheduleNumber,
      customerName: order.customerName,
      projectName: order.projectName,
      shippingDate: actualShippingDate,
      shippingAddress: schedule.shippingAddress || '',
      receiverName: schedule.receiverName || '',
      receiverPhone: schedule.receiverPhone || '',
      status: 'shipped',
      createdAt: new Date().toISOString(),
      items: order.items.map(item => ({
        id: `SHI-${Date.now()}-${item.id}`,
        itemCode: 'AUTO-' + item.id,
        itemName: item.itemName,
        quantity: schedule.quantity,
        unit: 'SET',
        lotNumber,
        lotProductionDate: lotProductionDate || undefined
      })),
      note: schedule.note
    };

    console.log("출고 지시서 생성:", shippingOrder);
    toast.success(`출고 지시서가 생성되었습니다. (출고번호: ${shippingNumber})`);

    // 다이얼로그 닫기 및 초기화
    setIsShippingDialogOpen(false);
    setSelectedSchedule(null);
    setLotNumber("");
    setLotProductionDate("");
    setActualShippingDate(new Date().toISOString().split('T')[0]);
  };

  // 출고 지시 다이얼로그 열기
  const openShippingDialog = (order: SalesOrder, schedule: ShippingSchedule) => {
    setSelectedSchedule({ order, schedule });
    setIsShippingDialogOpen(true);
    setActualShippingDate(schedule.scheduledDate);
  };

  // 통계 데이터
  const stats = [
    {
      label: "전체 출고 계획",
      value: totalSchedules,
      icon: Package,
      iconColor: "text-blue-600"
    },
    {
      label: "예정",
      value: scheduledCount,
      icon: Calendar,
      iconColor: "text-gray-600"
    },
    {
      label: "준비완료",
      value: readyCount,
      icon: Clock,
      iconColor: "text-blue-600"
    },
    {
      label: "출고완료",
      value: shippedCount,
      icon: CheckCircle,
      iconColor: "text-green-600"
    }
  ];

  return (
    <PageLayout>
      <PageHeader
        title="분할 출고 관리"
        description="수주별 분할 출고 계획 조회 및 출고 지시"
        icon={Truck}
      />

      {/* 통계 카드 */}
      <StatCards stats={stats} />

      {/* 검색 */}
      <Card>
        <CardContent className="p-4 md:p-6">
          <div className="relative">
            <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>
        </CardContent>
      </Card>

      {/* 출고 계획 목록 */}
      <Card>
        <CardHeader>
          <CardTitle>출고 계획 목록 ({allSchedules.length}건)</CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>수주번호</TableHead>
                  <TableHead>고객명</TableHead>
                  <TableHead>프로젝트명</TableHead>
                  <TableHead className="text-center">차수</TableHead>
                  <TableHead>출하 예정일</TableHead>
                  <TableHead className="text-right">출하 수량</TableHead>
                  <TableHead className="text-right">출하 후 잔량</TableHead>
                  <TableHead>배송지</TableHead>
                  <TableHead>수령인</TableHead>
                  <TableHead>연락처</TableHead>
                  <TableHead className="text-center">상태</TableHead>
                  <TableHead>특이사항</TableHead>
                  <TableHead className="text-center">작업</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {allSchedules.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={13} className="text-center py-8 text-muted-foreground">
                      검색 결과가 없습니다.
                    </TableCell>
                  </TableRow>
                ) : (
                  allSchedules.map((item, index) => (
                    <TableRow key={`${item.order.id}-${item.schedule.id}`}>
                      <TableCell>
                        <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                          {item.order.orderNumber}
                        </code>
                      </TableCell>
                      <TableCell>{item.order.customerName}</TableCell>
                      <TableCell>{item.order.projectName}</TableCell>
                      <TableCell className="text-center">
                        <Badge variant="outline">{item.schedule.scheduleNumber}차</Badge>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <Calendar className="h-4 w-4 text-muted-foreground" />
                          <span>{item.schedule.scheduledDate}</span>
                        </div>
                      </TableCell>
                      <TableCell className="text-right">
                        <span className="font-medium">{item.schedule.quantity.toLocaleString()}</span>
                        <span className="text-muted-foreground ml-1">EA</span>
                      </TableCell>
                      <TableCell className="text-right">
                        <span className="font-medium">{item.schedule.remainingQuantity.toLocaleString()}</span>
                        <span className="text-muted-foreground ml-1">EA</span>
                      </TableCell>
                      <TableCell className="max-w-[200px] truncate">
                        <div className="flex items-center gap-2">
                          <MapPin className="h-4 w-4 text-muted-foreground flex-shrink-0" />
                          <span title={item.schedule.shippingAddress}>
                            {item.schedule.shippingAddress}
                          </span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <User className="h-4 w-4 text-muted-foreground" />
                          <span>{item.schedule.receiverName}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <Phone className="h-4 w-4 text-muted-foreground" />
                          <span>{item.schedule.receiverPhone}</span>
                        </div>
                      </TableCell>
                      <TableCell className="text-center">
                        {getStatusBadge(item.schedule.status)}
                      </TableCell>
                      <TableCell className="text-sm text-muted-foreground">
                        {item.schedule.note || '-'}
                      </TableCell>
                      <TableCell className="text-center">
                        {item.schedule.status === 'scheduled' || item.schedule.status === 'ready' ? (
                          <Button
                            size="sm"
                            onClick={() => openShippingDialog(item.order, item.schedule)}
                          >
                            <Truck className="h-4 w-4 mr-1" />
                            출고지시
                          </Button>
                        ) : item.schedule.status === 'shipped' ? (
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => {
                              toast.info(`출고번호: ${item.schedule.shippingOrderId || 'N/A'}`);
                            }}
                          >
                            <FileText className="h-4 w-4 mr-1" />
                            조회
                          </Button>
                        ) : (
                          <Badge variant="outline" className="bg-green-50 text-green-700">
                            완료
                          </Badge>
                        )}
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      {/* 출고 지시 다이얼로그 */}
      <Dialog open={isShippingDialogOpen} onOpenChange={setIsShippingDialogOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>출고 지시서 생성</DialogTitle>
            <DialogDescription>
              출고 정보를 입력하고 출고 지시서를 생성합니다.
            </DialogDescription>
          </DialogHeader>

          {selectedSchedule && (
            <div className="space-y-4">
              {/* 수주 정보 */}
              <Card>
                <CardHeader className="pb-3">
                  <CardTitle className="text-sm">수주 정보</CardTitle>
                </CardHeader>
                <CardContent className="space-y-2 text-sm">
                  <div className="grid grid-cols-2 gap-2">
                    <div>
                      <span className="text-muted-foreground">수주번호:</span>
                      <code className="ml-2 bg-gray-100 px-2 py-1 rounded text-xs">
                        {selectedSchedule.order.orderNumber}
                      </code>
                    </div>
                    <div>
                      <span className="text-muted-foreground">출고차수:</span>
                      <Badge variant="outline" className="ml-2">
                        {selectedSchedule.schedule.scheduleNumber}차
                      </Badge>
                    </div>
                    <div>
                      <span className="text-muted-foreground">고객명:</span>
                      <span className="ml-2 font-medium">{selectedSchedule.order.customerName}</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">프로젝트:</span>
                      <span className="ml-2 font-medium">{selectedSchedule.order.projectName}</span>
                    </div>
                    <div className="col-span-2">
                      <span className="text-muted-foreground">품목:</span>
                      <span className="ml-2 font-medium">{selectedSchedule.order.items[0]?.itemName}</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">출하 수량:</span>
                      <span className="ml-2 font-medium text-blue-600">
                        {selectedSchedule.schedule.quantity.toLocaleString()} EA
                      </span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">출하 후 잔량:</span>
                      <span className="ml-2 font-medium">
                        {selectedSchedule.schedule.remainingQuantity.toLocaleString()} EA
                      </span>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* 배송 정보 */}
              <Card>
                <CardHeader className="pb-3">
                  <CardTitle className="text-sm">배송 정보</CardTitle>
                </CardHeader>
                <CardContent className="space-y-2 text-sm">
                  <div>
                    <span className="text-muted-foreground">배송지:</span>
                    <div className="mt-1 p-2 bg-gray-50 rounded text-sm">
                      {selectedSchedule.schedule.shippingAddress}
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-2">
                    <div>
                      <span className="text-muted-foreground">수령인:</span>
                      <span className="ml-2">{selectedSchedule.schedule.receiverName}</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">연락처:</span>
                      <span className="ml-2">{selectedSchedule.schedule.receiverPhone}</span>
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* 출고 정보 입력 */}
              <div className="space-y-4">
                <div>
                  <Label>실제 출고일 *</Label>
                  <Input
                    type="date"
                    value={actualShippingDate}
                    onChange={(e) => setActualShippingDate(e.target.value)}
                  />
                </div>
                <div>
                  <Label>로트 번호 *</Label>
                  <Input
                    value={lotNumber}
                    onChange={(e) => setLotNumber(e.target.value)}
                    placeholder="예: LOT-25-001"
                  />
                  <p className="text-xs text-muted-foreground mt-1">
                    * 출고하는 제품의 생산 로트 번호를 입력하세요
                  </p>
                </div>
                <div>
                  <Label>로트 생산일</Label>
                  <Input
                    type="date"
                    value={lotProductionDate}
                    onChange={(e) => setLotProductionDate(e.target.value)}
                  />
                </div>
              </div>

              {/* 버튼 */}
              <div className="flex justify-end gap-2 pt-4">
                <Button variant="outline" onClick={() => setIsShippingDialogOpen(false)}>
                  취소
                </Button>
                <Button onClick={handleCreateShippingOrder}>
                  <Truck className="h-4 w-4 mr-2" />
                  출고 지시
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </PageLayout>
  );
}
