import { useState } from "react";
import { PageLayout } from "./organisms/PageLayout";
import { PageHeader } from "./organisms/PageHeader";
import { Button } from "./ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Badge } from "./ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { 
  ShoppingCart,
  X,
  Package,
  Calendar,
  Truck,
  MapPin,
  User,
  Phone,
  CheckCircle,
  Clock,
  FileText,
  TrendingUp
} from "lucide-react";
import { SalesOrder } from "./contexts/DataContext";

interface SalesOrderViewWithShippingProps {
  orderId: string;
  onBack: () => void;
}

export function SalesOrderViewWithShipping({ orderId, onBack }: SalesOrderViewWithShippingProps) {
  // Mock 데이터 - 실제로는 orderId로 데이터를 가져와야 함
  const [order] = 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차 출고 - 후관'
      }
    ]
  });

  // 상태 뱃지
  const getStatusBadge = (status: SalesOrder['status']) => {
    switch (status) {
      case 'pending':
        return <Badge variant="outline" className="bg-gray-50 text-gray-700 border-gray-200">대기</Badge>;
      case 'confirmed':
        return <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">확정</Badge>;
      case 'production':
        return <Badge variant="outline" className="bg-orange-50 text-orange-700 border-orange-200">생산중</Badge>;
      case 'shipping':
        return <Badge variant="outline" className="bg-purple-50 text-purple-700 border-purple-200">출하중</Badge>;
      case 'completed':
        return <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">완료</Badge>;
      case 'cancelled':
        return <Badge variant="outline" className="bg-red-50 text-red-700 border-red-200">취소</Badge>;
      default:
        return <Badge variant="outline">-</Badge>;
    }
  };

  const getScheduleStatusBadge = (status: string) => {
    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 shippingProgress = order.totalQuantity > 0 
    ? Math.round((order.shippedQuantity / order.totalQuantity) * 100) 
    : 0;

  return (
    <PageLayout>
      <PageHeader
        title="수주 상세"
        description="수주 정보 및 분할 출고 이력 조회"
        icon={ShoppingCart}
        actions={
          <Button variant="outline" onClick={onBack}>
            <X className="h-4 w-4 mr-2" />
            닫기
          </Button>
        }
      />

      {/* 기본 정보 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle>기본 정보</CardTitle>
            {getStatusBadge(order.status)}
          </div>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <span className="text-sm text-muted-foreground">수주번호</span>
              <div className="mt-1">
                <code className="text-sm bg-gray-100 px-2 py-1 rounded">
                  {order.orderNumber}
                </code>
              </div>
            </div>
            <div>
              <span className="text-sm text-muted-foreground">수주일자</span>
              <div className="mt-1 flex items-center gap-2">
                <Calendar className="h-4 w-4 text-muted-foreground" />
                <span>{order.orderDate}</span>
              </div>
            </div>
            <div>
              <span className="text-sm text-muted-foreground">고객명</span>
              <div className="mt-1 font-medium">{order.customerName}</div>
            </div>
            <div>
              <span className="text-sm text-muted-foreground">프로젝트명</span>
              <div className="mt-1 font-medium">{order.projectName}</div>
            </div>
            <div>
              <span className="text-sm text-muted-foreground">최종 납기일</span>
              <div className="mt-1 flex items-center gap-2">
                <Calendar className="h-4 w-4 text-muted-foreground" />
                <span>{order.deliveryDate}</span>
              </div>
            </div>
            <div>
              <span className="text-sm text-muted-foreground">총 금액</span>
              <div className="mt-1 font-medium text-blue-600">
                {order.totalAmount.toLocaleString()}원
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 출고 진행 현황 */}
      {order.hasMultipleShipping && (
        <Card>
          <CardHeader>
            <CardTitle>출고 진행 현황</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {/* 진행률 바 */}
              <div>
                <div className="flex justify-between text-sm mb-2">
                  <span className="text-muted-foreground">출고 진행률</span>
                  <span className="font-medium">{shippingProgress}%</span>
                </div>
                <div className="w-full bg-gray-200 rounded-full h-3">
                  <div 
                    className="bg-blue-600 h-3 rounded-full transition-all duration-300"
                    style={{ width: `${shippingProgress}%` }}
                  />
                </div>
              </div>

              {/* 수량 정보 */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="p-4 bg-blue-50 rounded-lg">
                  <div className="flex items-center gap-2 mb-2">
                    <Package className="h-5 w-5 text-blue-600" />
                    <span className="text-sm text-muted-foreground">총 수주 수량</span>
                  </div>
                  <div className="text-2xl font-bold text-blue-600">
                    {order.totalQuantity.toLocaleString()}
                    <span className="text-sm font-normal text-muted-foreground ml-1">EA</span>
                  </div>
                </div>

                <div className="p-4 bg-green-50 rounded-lg">
                  <div className="flex items-center gap-2 mb-2">
                    <CheckCircle className="h-5 w-5 text-green-600" />
                    <span className="text-sm text-muted-foreground">누적 출고 수량</span>
                  </div>
                  <div className="text-2xl font-bold text-green-600">
                    {order.shippedQuantity.toLocaleString()}
                    <span className="text-sm font-normal text-muted-foreground ml-1">EA</span>
                  </div>
                </div>

                <div className="p-4 bg-orange-50 rounded-lg">
                  <div className="flex items-center gap-2 mb-2">
                    <Clock className="h-5 w-5 text-orange-600" />
                    <span className="text-sm text-muted-foreground">잔여 수량</span>
                  </div>
                  <div className="text-2xl font-bold text-orange-600">
                    {order.remainingQuantity.toLocaleString()}
                    <span className="text-sm font-normal text-muted-foreground ml-1">EA</span>
                  </div>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* 품목 정보 */}
      <Card>
        <CardHeader>
          <CardTitle>품목 정보</CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>품목명</TableHead>
                <TableHead className="text-right">수량</TableHead>
                <TableHead className="text-right">단가</TableHead>
                <TableHead className="text-right">금액</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {order.items.map((item) => (
                <TableRow key={item.id}>
                  <TableCell>{item.itemName}</TableCell>
                  <TableCell className="text-right">{item.quantity.toLocaleString()} EA</TableCell>
                  <TableCell className="text-right">{item.unitPrice.toLocaleString()}원</TableCell>
                  <TableCell className="text-right font-medium">
                    {item.totalPrice.toLocaleString()}원
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* 분할 출고 계획 및 이력 */}
      {order.hasMultipleShipping && order.shippingSchedules && (
        <Card>
          <CardHeader>
            <CardTitle>분할 출고 계획 및 이력</CardTitle>
          </CardHeader>
          <CardContent className="p-0">
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="text-center">차수</TableHead>
                    <TableHead>출하 예정일</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>특이사항</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {order.shippingSchedules.map((schedule) => (
                    <TableRow key={schedule.id}>
                      <TableCell className="text-center">
                        <Badge variant="outline">{schedule.scheduleNumber}차</Badge>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <Calendar className="h-4 w-4 text-muted-foreground" />
                          <span>{schedule.scheduledDate}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        {schedule.actualShippingDate ? (
                          <div className="flex items-center gap-2">
                            <CheckCircle className="h-4 w-4 text-green-600" />
                            <span>{schedule.actualShippingDate}</span>
                          </div>
                        ) : (
                          <span className="text-muted-foreground">-</span>
                        )}
                      </TableCell>
                      <TableCell className="text-right">
                        <span className="font-medium">{schedule.quantity.toLocaleString()}</span>
                        <span className="text-muted-foreground ml-1">EA</span>
                      </TableCell>
                      <TableCell className="text-right">
                        <span className="font-medium">{schedule.remainingQuantity.toLocaleString()}</span>
                        <span className="text-muted-foreground ml-1">EA</span>
                      </TableCell>
                      <TableCell className="max-w-[200px]">
                        <div className="flex items-start gap-2">
                          <MapPin className="h-4 w-4 text-muted-foreground flex-shrink-0 mt-0.5" />
                          <span className="text-sm">{schedule.shippingAddress}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <User className="h-4 w-4 text-muted-foreground" />
                          <span>{schedule.receiverName}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <Phone className="h-4 w-4 text-muted-foreground" />
                          <span className="text-sm">{schedule.receiverPhone}</span>
                        </div>
                      </TableCell>
                      <TableCell className="text-center">
                        {getScheduleStatusBadge(schedule.status)}
                      </TableCell>
                      <TableCell>
                        {schedule.shippingOrderId ? (
                          <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                            {schedule.shippingOrderId}
                          </code>
                        ) : (
                          <span className="text-muted-foreground">-</span>
                        )}
                      </TableCell>
                      <TableCell className="text-sm text-muted-foreground">
                        {schedule.note || '-'}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </CardContent>
        </Card>
      )}

      {/* 출고 이력 요약 */}
      {order.hasMultipleShipping && order.shippingSchedules && (
        <Card>
          <CardHeader>
            <CardTitle>출고 이력 요약</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {order.shippingSchedules
                .filter(s => s.status === 'shipped' || s.status === 'completed')
                .map((schedule, index) => (
                  <div 
                    key={schedule.id} 
                    className="flex items-start gap-4 p-4 bg-gray-50 rounded-lg"
                  >
                    <div className="flex-shrink-0">
                      <div className="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center">
                        <CheckCircle className="h-5 w-5 text-green-600" />
                      </div>
                    </div>
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <Badge variant="outline">{schedule.scheduleNumber}차 출고</Badge>
                        <span className="text-sm text-muted-foreground">
                          {schedule.actualShippingDate}
                        </span>
                      </div>
                      <div className="grid grid-cols-2 gap-2 text-sm">
                        <div>
                          <span className="text-muted-foreground">출고 수량:</span>
                          <span className="ml-2 font-medium">{schedule.quantity.toLocaleString()} EA</span>
                        </div>
                        <div>
                          <span className="text-muted-foreground">출고 후 잔량:</span>
                          <span className="ml-2 font-medium">{schedule.remainingQuantity.toLocaleString()} EA</span>
                        </div>
                        <div className="col-span-2">
                          <span className="text-muted-foreground">배송지:</span>
                          <span className="ml-2">{schedule.shippingAddress}</span>
                        </div>
                        {schedule.note && (
                          <div className="col-span-2">
                            <span className="text-muted-foreground">특이사항:</span>
                            <span className="ml-2">{schedule.note}</span>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                ))}
              {order.shippingSchedules.filter(s => s.status === 'shipped' || s.status === 'completed').length === 0 && (
                <div className="text-center py-8 text-muted-foreground">
                  아직 출고 이력이 없습니다.
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      )}
    </PageLayout>
  );
}
