import { useState } from "react";
import { PageLayout } from "./organisms/PageLayout";
import { PageHeader } from "./organisms/PageHeader";
import { DetailViewActions } from "./organisms/DetailViewActions";
import { Button } from "./ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Badge } from "./ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Separator } from "./ui/separator";
import { 
  ShoppingCart, 
  Edit, 
  Printer,
  ArrowLeft,
  Building,
  User,
  Phone,
  Calendar,
  Package,
  Truck,
  CreditCard,
  FileText,
  CheckCircle,
  Clock,
  MapPin,
  DollarSign
} from "lucide-react";
import { toast } from "sonner@2.0.3";

interface ProductItem {
  no: number;
  productCode: string;
  category: string;
  model: string;
  quantity: number;
  price: number;
  unit: string;
  shipmentQuantity: number;
  shipmentStatus: string;
  note: string;
  amount: number;
}

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

export function SalesOrderView({ orderId, onBack, onEdit }: SalesOrderViewProps) {

  // 샘플 데이터
  const orderData = {
    orderNo: "90",
    orderDate: "2025-12-02",
    orderTime: "07:25",
    deliveryDate: "2025-07-25",
    confirmDate: "2025-07-25",
    productCode: "KQT501",
    productName: "로스코트베드 1.0 (에폭시 4호+이경 플래너클로저 추가)",
    status: "완료",
    approvalStatus: "승인",
    
    // 고객사 정보
    clientCode: "총판2대리점",
    clientName: "총판2대리점",
    salesPerson: "김예슬",
    clientPhone: "010-5487-2886",
    requestCode: "1001",
    subCode: "ACCOUNT",
    
    // 배송 정보
    shippingMethod: "직접배송",
    shippingStatus: "배송완료",
    receiverName: "홍길동",
    receiverPhone: "010-5487-2880",
    shippingAddress: "서울시 강남구 테헤란로 123",
    
    // 결제 정보
    paymentType: "현금결제(선)",
    billingType: "세금계산서",
    supplyPrice: 318100,
    vatAmount: 31810,
    totalAmount: 349910,
    
    // 특이사항
    internalMemo: "★우리샤넷은 A=기존백마유리B회사(대구 안산사옵1호 공무사 우선노력1) 업소예정(주택) 전화번호는 옆줄로 연락(문의/수리)",
    deliveryMemo: "2,3일 출고 필요 / 가산성 스탠드 디 힌지모즈 사용량",
    shippingMemo: "보안사 다음 선택지 없음",
    
    // 기타
    registeredBy: "김예슬",
    registeredAt: "2025-12-02 07:25:33",
    modifiedBy: "김예슬",
    modifiedAt: "2025-12-02 09:15:22",
    printed: true,
    printedAt: "2025-12-02 10:30:00"
  };

  const products: ProductItem[] = [
    {
      no: 1,
      productCode: "EST-01",
      category: "EGI 1:87 BOX",
      model: "BOSS",
      quantity: 4350,
      price: 1,
      unit: "판매",
      shipmentQuantity: 4350,
      shipmentStatus: "출고완료",
      note: "EGI 1:87 BOX(5st:s4349ea43b4.0..등 18t",
      amount: 4350
    }
  ];

  const handleEdit = () => {
    onEdit();
  };

  const handlePrint = () => {
    toast.success("수주서를 인쇄합니다");
  };

  const handleBack = () => {
    onBack();
  };

  const getStatusColor = (status: string): "default" | "secondary" | "destructive" | "outline" => {
    switch (status) {
      case "완료": return "default";
      case "진행": return "outline";
      case "보류": return "secondary";
      case "취소": return "destructive";
      default: return "default";
    }
  };

  const getApprovalColor = (status: string): "default" | "secondary" | "destructive" | "outline" => {
    switch (status) {
      case "승인": return "default";
      case "대기": return "secondary";
      case "거부": return "destructive";
      default: return "outline";
    }
  };

  return (
    <PageLayout>
      <PageHeader
        title="수주 상세"
        description={`수주번호: ${orderData.orderNo}`}
        icon={ShoppingCart}
        leftActions={
          <Button variant="outline" onClick={handlePrint}>
            <Printer className="h-4 w-4 mr-2" />
            인쇄
          </Button>
        }
        rightActions={
          <DetailViewActions
            onBackClick={handleBack}
            onEditClick={handleEdit}
            backLabel="목록"
            editLabel="수정"
          />
        }
      />

      <div className="space-y-6">
        {/* 상태 정보 */}
        <Card>
          <CardContent className="pt-6">
            <div className="flex flex-wrap items-center gap-4">
              <div className="flex items-center gap-2">
                <span className="text-sm text-muted-foreground">수주 상태:</span>
                <Badge variant={getStatusColor(orderData.status)} className="text-base px-3 py-1">
                  {orderData.status}
                </Badge>
              </div>
              <Separator orientation="vertical" className="h-6" />
              <div className="flex items-center gap-2">
                <span className="text-sm text-muted-foreground">승인 상태:</span>
                <Badge variant={getApprovalColor(orderData.approvalStatus)} className="text-base px-3 py-1">
                  {orderData.approvalStatus}
                </Badge>
              </div>
              <Separator orientation="vertical" className="h-6" />
              <div className="flex items-center gap-2">
                <span className="text-sm text-muted-foreground">인쇄:</span>
                {orderData.printed ? (
                  <div className="flex items-center gap-1 text-green-600">
                    <CheckCircle className="h-4 w-4" />
                    <span className="text-sm">인쇄완료 ({orderData.printedAt})</span>
                  </div>
                ) : (
                  <div className="flex items-center gap-1 text-yellow-600">
                    <Clock className="h-4 w-4" />
                    <span className="text-sm">미인쇄</span>
                  </div>
                )}
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 기본 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <FileText className="h-5 w-5" />
              기본 정보
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
              <div>
                <div className="text-sm text-muted-foreground mb-1">수주번호</div>
                <div className="font-semibold">{orderData.orderNo}</div>
              </div>
              <div>
                <div className="text-sm text-muted-foreground mb-1">수주일자</div>
                <div className="font-semibold">{orderData.orderDate} {orderData.orderTime}</div>
              </div>
              <div>
                <div className="text-sm text-muted-foreground mb-1">납기일자</div>
                <div className="font-semibold">{orderData.deliveryDate}</div>
              </div>
              <div>
                <div className="text-sm text-muted-foreground mb-1">발주 확인일</div>
                <div className="font-semibold">{orderData.confirmDate}</div>
              </div>
              <div className="lg:col-span-2">
                <div className="text-sm text-muted-foreground mb-1">제품 코드</div>
                <div className="font-semibold">{orderData.productCode}</div>
              </div>
              <div className="lg:col-span-2">
                <div className="text-sm text-muted-foreground mb-1">제품명</div>
                <div className="font-semibold">{orderData.productName}</div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 고객사 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Building className="h-5 w-5" />
              고객사 정보
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
              <div>
                <div className="text-sm text-muted-foreground mb-1">고객사 코드</div>
                <div className="font-semibold">{orderData.clientCode}</div>
              </div>
              <div>
                <div className="text-sm text-muted-foreground mb-1">고객사명</div>
                <div className="font-semibold">{orderData.clientName}</div>
              </div>
              <div>
                <div className="text-sm text-muted-foreground mb-1">담당 영업자</div>
                <div className="font-semibold flex items-center gap-1">
                  <User className="h-4 w-4 text-muted-foreground" />
                  {orderData.salesPerson}
                </div>
              </div>
              <div>
                <div className="text-sm text-muted-foreground mb-1">전화번호</div>
                <div className="font-semibold flex items-center gap-1">
                  <Phone className="h-4 w-4 text-muted-foreground" />
                  {orderData.clientPhone}
                </div>
              </div>
              <div>
                <div className="text-sm text-muted-foreground mb-1">신청자 Code</div>
                <div className="font-semibold">{orderData.requestCode}</div>
              </div>
              <div>
                <div className="text-sm text-muted-foreground mb-1">전차 Code</div>
                <div className="font-semibold">{orderData.subCode}</div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 배송 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Truck className="h-5 w-5" />
              배송 정보
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <div className="text-sm text-muted-foreground mb-1">배달 방법</div>
                <div className="font-semibold">{orderData.shippingMethod}</div>
              </div>
              <div>
                <div className="text-sm text-muted-foreground mb-1">배송 상태</div>
                <div>
                  <Badge variant="success">{orderData.shippingStatus}</Badge>
                </div>
              </div>
              <div>
                <div className="text-sm text-muted-foreground mb-1">수신자명</div>
                <div className="font-semibold">{orderData.receiverName}</div>
              </div>
              <div>
                <div className="text-sm text-muted-foreground mb-1">수신자 전화번호</div>
                <div className="font-semibold flex items-center gap-1">
                  <Phone className="h-4 w-4 text-muted-foreground" />
                  {orderData.receiverPhone}
                </div>
              </div>
              <div className="md:col-span-2">
                <div className="text-sm text-muted-foreground mb-1">배송지 주소</div>
                <div className="font-semibold flex items-center gap-1">
                  <MapPin className="h-4 w-4 text-muted-foreground" />
                  {orderData.shippingAddress}
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 결제 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <CreditCard className="h-5 w-5" />
              결제 정보
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <div className="text-sm text-muted-foreground mb-1">판매 방법</div>
                <div className="font-semibold">{orderData.paymentType}</div>
              </div>
              <div>
                <div className="text-sm text-muted-foreground mb-1">세금계산서 발행</div>
                <div className="font-semibold">{orderData.billingType}</div>
              </div>
            </div>

            <Separator className="my-6" />

            <div className="space-y-3">
              <div className="flex justify-between items-center">
                <span className="text-muted-foreground">공급가액</span>
                <span className="font-semibold">₩{orderData.supplyPrice.toLocaleString()}</span>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-muted-foreground">부가세 (10%)</span>
                <span className="font-semibold">₩{orderData.vatAmount.toLocaleString()}</span>
              </div>
              <Separator />
              <div className="flex justify-between items-center">
                <span className="text-lg font-semibold">합계금액</span>
                <span className="text-2xl font-bold text-primary">
                  ₩{orderData.totalAmount.toLocaleString()}
                </span>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 제품 목록 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Package className="h-5 w-5" />
              제품 목록
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-[50px]">No</TableHead>
                    <TableHead>제품코드</TableHead>
                    <TableHead>카테고리</TableHead>
                    <TableHead>모델(명)</TableHead>
                    <TableHead className="text-right">수량</TableHead>
                    <TableHead className="text-right">단가</TableHead>
                    <TableHead>단위</TableHead>
                    <TableHead className="text-right">출고수량</TableHead>
                    <TableHead>출고상태</TableHead>
                    <TableHead className="text-right">금액</TableHead>
                    <TableHead>비고</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {products.map((product) => (
                    <TableRow key={product.no}>
                      <TableCell>{product.no}</TableCell>
                      <TableCell className="font-medium">{product.productCode}</TableCell>
                      <TableCell>{product.category}</TableCell>
                      <TableCell>{product.model}</TableCell>
                      <TableCell className="text-right">{product.quantity.toLocaleString()}</TableCell>
                      <TableCell className="text-right">₩{product.price.toLocaleString()}</TableCell>
                      <TableCell>{product.unit}</TableCell>
                      <TableCell className="text-right">{product.shipmentQuantity.toLocaleString()}</TableCell>
                      <TableCell>
                        <Badge variant={product.shipmentStatus === "출고완료" ? "success" : "secondary"}>
                          {product.shipmentStatus}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-right font-semibold">
                        ₩{product.amount.toLocaleString()}
                      </TableCell>
                      <TableCell className="text-sm text-muted-foreground">{product.note}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </CardContent>
        </Card>

        {/* 특이사항 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <FileText className="h-5 w-5" />
              특이사항
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <div className="text-sm font-semibold text-red-600 mb-2">
                내부 특이사항 / 가산서 스트레스 적 힌지모즈 사용량
              </div>
              <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-900">
                {orderData.internalMemo}
              </div>
            </div>
            <div>
              <div className="text-sm font-semibold text-blue-600 mb-2">
                발주자 등급회 / 보고조처 노트
              </div>
              <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg text-sm text-blue-900">
                {orderData.deliveryMemo}
              </div>
            </div>
            <div>
              <div className="text-sm font-semibold text-muted-foreground mb-2">
                배송 관련 특이사항
              </div>
              <div className="p-3 bg-muted/50 border rounded-lg text-sm">
                {orderData.shippingMemo}
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 이력 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Clock className="h-5 w-5" />
              이력 정보
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <div className="text-sm text-muted-foreground mb-1">등록자</div>
                <div className="font-semibold">{orderData.registeredBy}</div>
              </div>
              <div>
                <div className="text-sm text-muted-foreground mb-1">등록일시</div>
                <div className="font-semibold">{orderData.registeredAt}</div>
              </div>
              <div>
                <div className="text-sm text-muted-foreground mb-1">수정자</div>
                <div className="font-semibold">{orderData.modifiedBy}</div>
              </div>
              <div>
                <div className="text-sm text-muted-foreground mb-1">수정일시</div>
                <div className="font-semibold">{orderData.modifiedAt}</div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 하단 버튼 */}
        <div className="flex justify-between">
          <Button variant="outline" size="lg" onClick={handleBack}>
            <ArrowLeft className="h-4 w-4 mr-2" />
            목록으로
          </Button>
          <div className="flex gap-2">
            <Button variant="outline" size="lg" onClick={handlePrint}>
              <Printer className="h-4 w-4 mr-2" />
              인쇄
            </Button>
            <Button size="lg" onClick={handleEdit}>
              <Edit className="h-4 w-4 mr-2" />
              수정
            </Button>
          </div>
        </div>
      </div>
    </PageLayout>
  );
}