import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Badge } from "./ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "./ui/dialog";
import { Label } from "./ui/label";
import { PageLayout } from "./organisms/PageLayout";
import { PageHeader } from "./organisms/PageHeader";
import { StatCards } from "./organisms/StatCards";
import { 
  Search, 
  Plus, 
  Download, 
  Filter, 
  ShoppingCart, 
  Calendar, 
  Package, 
  Truck, 
  CheckCircle,
  Eye,
  Edit,
  Clock,
  FileText,
  Mail,
  TrendingUp,
  AlertTriangle,
  RefreshCw,
  Split,
  DollarSign,
  CheckSquare
} from "lucide-react";
import { toast } from "sonner@2.0.3";
import { useData } from "./contexts/DataContext";
import type { SalesOrder } from "./contexts/DataContext";

export function OrderManagement() {
  const { salesOrders, quotes } = useData();
  const [activeTab, setActiveTab] = useState("list");
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedStatus, setSelectedStatus] = useState("all");
  const [selectedOrder, setSelectedOrder] = useState<SalesOrder | null>(null);
  const [showOrderDetail, setShowOrderDetail] = useState(false);
  const [showQuoteSelectDialog, setShowQuoteSelectDialog] = useState(false);
  const [showCreateOrderForm, setShowCreateOrderForm] = useState(false);
  const [selectedQuoteId, setSelectedQuoteId] = useState<string | null>(null);

  // 확정된 견적 목록 (status가 'finalized')
  const finalizedQuotes = quotes?.filter(q => q.isFinal && q.status === 'finalized') || [];

  // 상태별 필터링
  const getStatusLabel = (status: string) => {
    const statusMap: Record<string, string> = {
      registered: "수주등록",
      contract_completed: "수주계약완료",
      production_ordered: "생산지시완료",
      shipping: "출고중",
      completed: "완료",
      cancelled: "취소"
    };
    return statusMap[status] || status;
  };

  const getStatusColor = (status: string) => {
    const colorMap: Record<string, string> = {
      registered: "bg-blue-100 text-blue-800",
      contract_completed: "bg-green-100 text-green-800",
      production_ordered: "bg-purple-100 text-purple-800",
      shipping: "bg-orange-100 text-orange-800",
      completed: "bg-gray-100 text-gray-800",
      cancelled: "bg-red-100 text-red-800"
    };
    return colorMap[status] || "bg-gray-100 text-gray-800";
  };

  // 입금 상태 라벨
  const getDepositStatusLabel = (status: string) => {
    const statusMap: Record<string, string> = {
      pending: "미입금",
      partial: "부분입금",
      completed: "입금완료"
    };
    return statusMap[status] || status;
  };

  const getDepositStatusColor = (status: string) => {
    const colorMap: Record<string, string> = {
      pending: "bg-red-100 text-red-800",
      partial: "bg-yellow-100 text-yellow-800",
      completed: "bg-green-100 text-green-800"
    };
    return colorMap[status] || "bg-gray-100 text-gray-800";
  };

  // 세금계산서 상태 라벨
  const getTaxStatusLabel = (status: string) => {
    const statusMap: Record<string, string> = {
      not_issued: "미발행",
      issued: "발행완료",
      completed: "처리완료"
    };
    return statusMap[status] || status;
  };

  // 필터링된 수주 목록
  const filteredOrders = salesOrders?.filter(order => {
    const matchesSearch = 
      order.orderNumber.toLowerCase().includes(searchTerm.toLowerCase()) ||
      order.customerName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      order.projectName.toLowerCase().includes(searchTerm.toLowerCase());
    
    const matchesStatus = selectedStatus === "all" || order.status === selectedStatus;
    
    return matchesSearch && matchesStatus;
  }) || [];

  // 통계 계산
  const stats = [
    {
      title: "총 수주",
      value: salesOrders?.length.toString() || "0",
      description: "전체 수주 건수",
      icon: ShoppingCart,
      trend: "+12%",
      trendLabel: "전월 대비"
    },
    {
      title: "수주계약완료",
      value: salesOrders?.filter(o => o.status === 'contract_completed').length.toString() || "0",
      description: "계약 완료 건수",
      icon: CheckCircle,
      trend: "+8%",
      trendLabel: "전월 대비"
    },
    {
      title: "생산지시대기",
      value: salesOrders?.filter(o => o.status === 'contract_completed').length.toString() || "0",
      description: "생산 대기 건수",
      icon: Clock,
      trend: "5건",
      trendLabel: "긴급"
    },
    {
      title: "분할출고",
      value: salesOrders?.filter(o => o.hasMultipleShipping).length.toString() || "0",
      description: "분할 출고 건수",
      icon: Split,
      trend: `${salesOrders?.reduce((sum, o) => sum + o.divisionCount, 0) || 0}차`,
      trendLabel: "총 분할"
    }
  ];

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

  // 날짜 포맷팅
  const formatDate = (dateStr: string) => {
    if (!dateStr) return '-';
    const date = new Date(dateStr);
    return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}.${String(date.getDate()).padStart(2, '0')}`;
  };

  // 수주 상세 보기
  const handleViewOrder = (order: SalesOrder) => {
    setSelectedOrder(order);
    setShowOrderDetail(true);
  };

  // 수주 등록 (견적에서 변환)
  const handleCreateFromQuote = () => {
    if (finalizedQuotes.length > 0) {
      setShowQuoteSelectDialog(true);
    } else {
      toast.info("확정된 견적이 없습니다. 새로운 견적을 생성하세요.");
    }
  };

  // 견적 선택 후 수주 등록
  const handleSelectQuote = (quoteId: string) => {
    setSelectedQuoteId(quoteId);
    setShowQuoteSelectDialog(false);
    setShowCreateOrderForm(true);
  };

  // 수주 등록 버튼 클릭 (견적 선택 또는 직접 입력 선택)
  const handleCreateOrderClick = () => {
    setShowQuoteSelectDialog(true);
  };

  // 직접 입력으로 수주 등록
  const handleDirectCreate = () => {
    setSelectedQuoteId(null);
    setShowQuoteSelectDialog(false);
    setShowCreateOrderForm(true);
  };

  // 수주계약서 발송
  const handleSendContract = (order: SalesOrder) => {
    toast.success(`${order.customerName}에게 수주계약서를 발송했습니다.`);
  };

  // 거래��세표 발송
  const handleSendSpecification = (order: SalesOrder) => {
    toast.success(`${order.customerName}에게 거래명세표를 발송했습니다.`);
  };

  // 생산지시
  const handleProductionOrder = (order: SalesOrder) => {
    if (order.depositStatus !== 'completed' || order.taxInvoiceStatus === 'not_issued') {
      toast.error("입금 및 세금계산서 확인이 필요합니다.");
      return;
    }
    toast.success("생산지시가 완료되었습니다.");
  };

  return (
    <PageLayout>
      <PageHeader
        title="수주관리"
        subtitle="견적 기반 수주 등록 및 분할 출하 관리"
        icon={ShoppingCart}
      />

      <StatCards stats={stats} />

      <div className="space-y-4">
        {/* 검색 및 필터 */}
        <Card>
          <CardContent className="pt-6">
            <div className="flex flex-col lg:flex-row gap-4">
              <div className="flex-1 relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                <Input
                  placeholder="수주번호, 고객명, 프로젝트명 검색..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10"
                />
              </div>
              
              <Select value={selectedStatus} onValueChange={setSelectedStatus}>
                <SelectTrigger className="w-full lg:w-[200px]">
                  <SelectValue placeholder="상태 선택" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">전체 상태</SelectItem>
                  <SelectItem value="registered">수주등록</SelectItem>
                  <SelectItem value="contract_completed">수주계약완료</SelectItem>
                  <SelectItem value="production_ordered">생산지시완료</SelectItem>
                  <SelectItem value="shipping">출고중</SelectItem>
                  <SelectItem value="completed">완료</SelectItem>
                </SelectContent>
              </Select>

              <div className="flex gap-2">
                <Button onClick={handleCreateOrderClick}>
                  <Plus className="w-4 h-4 mr-2" />
                  수주 등록
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 수주 목록 테이블 */}
        <Card>
          <CardHeader>
            <div className="flex justify-between items-center">
              <CardTitle>수주 목록</CardTitle>
              <div className="flex gap-2">
                <Button variant="outline" size="sm">
                  <Download className="w-4 h-4 mr-2" />
                  엑셀 다운로드
                </Button>
                <Button variant="outline" size="sm">
                  <RefreshCw className="w-4 h-4 mr-2" />
                  새로고침
                </Button>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-[120px]">수주번호</TableHead>
                    <TableHead>고객명</TableHead>
                    <TableHead>프로젝트명</TableHead>
                    <TableHead>수주일</TableHead>
                    <TableHead>납품예정일</TableHead>
                    <TableHead className="text-right">수주금액</TableHead>
                    <TableHead className="text-center">분할여부</TableHead>
                    <TableHead className="text-center">상태</TableHead>
                    <TableHead className="text-center">입금</TableHead>
                    <TableHead className="text-center">세금계산서</TableHead>
                    <TableHead>담당자</TableHead>
                    <TableHead className="text-center w-[200px]">작업</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredOrders.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={12} className="text-center py-8 text-gray-500">
                        수주 내역이 없습니다.
                      </TableCell>
                    </TableRow>
                  ) : (
                    filteredOrders.map((order) => (
                      <TableRow key={order.id}>
                        <TableCell className="font-mono text-sm">
                          {order.orderNumber}
                        </TableCell>
                        <TableCell>{order.customerName}</TableCell>
                        <TableCell>{order.projectName}</TableCell>
                        <TableCell>{formatDate(order.orderDate)}</TableCell>
                        <TableCell>{formatDate(order.deliveryDate)}</TableCell>
                        <TableCell className="text-right font-medium">
                          {formatAmount(order.totalAmount)}
                        </TableCell>
                        <TableCell className="text-center">
                          {order.hasMultipleShipping ? (
                            <Badge variant="outline" className="bg-blue-50">
                              <Split className="w-3 h-3 mr-1" />
                              {order.divisionCount}차 분할
                            </Badge>
                          ) : (
                            <Badge variant="outline">일괄</Badge>
                          )}
                        </TableCell>
                        <TableCell className="text-center">
                          <Badge className={getStatusColor(order.status)}>
                            {getStatusLabel(order.status)}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-center">
                          <Badge className={getDepositStatusColor(order.depositStatus)}>
                            {getDepositStatusLabel(order.depositStatus)}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-center">
                          <Badge variant={order.taxInvoiceStatus === 'completed' ? 'default' : 'outline'}>
                            {getTaxStatusLabel(order.taxInvoiceStatus)}
                          </Badge>
                        </TableCell>
                        <TableCell>{order.manager}</TableCell>
                        <TableCell>
                          <div className="flex gap-1 justify-center">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleViewOrder(order)}
                            >
                              <Eye className="w-4 h-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleSendContract(order)}
                            >
                              <FileText className="w-4 h-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleSendSpecification(order)}
                            >
                              <Mail className="w-4 h-4" />
                            </Button>
                            {order.status === 'contract_completed' && (
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => handleProductionOrder(order)}
                                className="text-green-600"
                              >
                                <CheckSquare className="w-4 h-4" />
                              </Button>
                            )}
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>
          </CardContent>
        </Card>

        {/* 수주 상세 정보 (선택 시 표시) */}
        {showOrderDetail && selectedOrder && (
          <Card>
            <CardHeader>
              <div className="flex justify-between items-center">
                <CardTitle>수주 상세 정보</CardTitle>
                <Button variant="ghost" size="sm" onClick={() => setShowOrderDetail(false)}>
                  닫기
                </Button>
              </div>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {/* 기본 정보 */}
                <div className="space-y-4">
                  <h3 className="font-semibold border-b pb-2">기본 정보</h3>
                  <div className="grid grid-cols-2 gap-2 text-sm">
                    <div className="text-gray-600">수주번호:</div>
                    <div className="font-medium">{selectedOrder.orderNumber}</div>
                    
                    <div className="text-gray-600">견적번호:</div>
                    <div className="font-medium">{selectedOrder.quoteNumber || '-'}</div>
                    
                    <div className="text-gray-600">고객명:</div>
                    <div className="font-medium">{selectedOrder.customerName}</div>
                    
                    <div className="text-gray-600">프로젝트:</div>
                    <div className="font-medium">{selectedOrder.projectName}</div>
                    
                    <div className="text-gray-600">현장명:</div>
                    <div className="font-medium">{selectedOrder.siteName || '-'}</div>
                    
                    <div className="text-gray-600">등록자:</div>
                    <div className="font-medium">{selectedOrder.registeredBy}</div>
                    
                    <div className="text-gray-600">담당 영업:</div>
                    <div className="font-medium">{selectedOrder.manager}</div>
                  </div>
                </div>

                {/* 금액 정보 */}
                <div className="space-y-4">
                  <h3 className="font-semibold border-b pb-2">금액 정보</h3>
                  <div className="grid grid-cols-2 gap-2 text-sm">
                    <div className="text-gray-600">원 금액:</div>
                    <div className="font-medium">{formatAmount(selectedOrder.originalAmount)}</div>
                    
                    <div className="text-gray-600">할인율:</div>
                    <div className="font-medium text-red-600">{selectedOrder.discountRate}%</div>
                    
                    <div className="text-gray-600">할인 금액:</div>
                    <div className="font-medium text-red-600">-{formatAmount(selectedOrder.discountAmount)}</div>
                    
                    <div className="text-gray-600">최종 금액:</div>
                    <div className="text-lg font-bold text-blue-600">{formatAmount(selectedOrder.totalAmount)}</div>
                    
                    <div className="text-gray-600">입금액:</div>
                    <div className="font-medium">{formatAmount(selectedOrder.depositAmount)}</div>
                    
                    <div className="text-gray-600">입금 상태:</div>
                    <div>
                      <Badge className={getDepositStatusColor(selectedOrder.depositStatus)}>
                        {getDepositStatusLabel(selectedOrder.depositStatus)}
                      </Badge>
                    </div>
                  </div>
                </div>

                {/* 배송 정보 */}
                <div className="space-y-4">
                  <h3 className="font-semibold border-b pb-2">배송 정보</h3>
                  <div className="grid grid-cols-2 gap-2 text-sm">
                    <div className="text-gray-600">배송지:</div>
                    <div className="font-medium col-span-1">{selectedOrder.shippingAddress}</div>
                    
                    <div className="text-gray-600">수령인:</div>
                    <div className="font-medium">{selectedOrder.receiverName}</div>
                    
                    <div className="text-gray-600">연락처:</div>
                    <div className="font-medium">{selectedOrder.receiverPhone}</div>
                    
                    <div className="text-gray-600">배송방식:</div>
                    <div className="font-medium">
                      {selectedOrder.shippingMethod === 'direct' ? '직송' : 
                       selectedOrder.shippingMethod === 'cargo' ? '화물' : '택배'}
                    </div>
                    
                    <div className="text-gray-600">납품예정일:</div>
                    <div className="font-medium">{formatDate(selectedOrder.deliveryDate)}</div>
                  </div>
                </div>

                {/* 분할 정보 */}
                {selectedOrder.hasMultipleShipping && (
                  <div className="space-y-4">
                    <h3 className="font-semibold border-b pb-2">분할 출고 정보</h3>
                    <div className="space-y-2">
                      {selectedOrder.shippingLots?.map((lot) => (
                        <div key={lot.id} className="p-3 bg-gray-50 rounded-lg">
                          <div className="flex justify-between items-center mb-2">
                            <span className="font-medium">{lot.lotNumber}</span>
                            <Badge className={getStatusColor(lot.status)}>
                              {lot.scheduleNumber}차 출고
                            </Badge>
                          </div>
                          <div className="text-sm text-gray-600">
                            <div>출고예정: {formatDate(lot.scheduledDate)}</div>
                            <div>품목 수: {lot.items.length}개</div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>

              {/* 문서 발송 이력 */}
              {selectedOrder.documentSendHistory && selectedOrder.documentSendHistory.length > 0 && (
                <div className="mt-6">
                  <h3 className="font-semibold border-b pb-2 mb-4">문서 발송 이력</h3>
                  <div className="space-y-2">
                    {selectedOrder.documentSendHistory.map((history) => (
                      <div key={history.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg text-sm">
                        <div className="flex items-center gap-4">
                          <Badge variant="outline">
                            {history.documentType === 'contract' ? '수주계약서' : '거래명세표'}
                          </Badge>
                          <span className="text-gray-600">발송일: {formatDate(history.sentDate)}</span>
                          <span className="text-gray-600">발송자: {history.sentBy}</span>
                          <span className="text-gray-600">수신자: {history.sentTo}</span>
                          <span className="text-gray-600">
                            방법: {history.sentMethod === 'email' ? '이메일' : 
                                  history.sentMethod === 'fax' ? '팩스' : '카카오톡'}
                          </span>
                        </div>
                        <Badge className={history.status === 'confirmed' ? 'bg-green-100 text-green-800' : ''}>
                          {history.status === 'sent' ? '발송완료' : 
                           history.status === 'confirmed' ? '확인완료' : '발송실패'}
                        </Badge>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        )}
      </div>

      {/* 견적 선택 다이얼로그 */}
      <Dialog open={showQuoteSelectDialog} onOpenChange={setShowQuoteSelectDialog}>
        <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>수주 등록 방법 선택</DialogTitle>
          </DialogHeader>
          
          <div className="space-y-4">
            <div className="bg-blue-50 p-3 rounded-lg border border-blue-200">
              <p className="text-sm text-blue-800">
                <strong>확정된 견적 {finalizedQuotes.length}건</strong>을 선택하거나 직접 입력으로 수주를 등록할 수 있습니다.
              </p>
            </div>

            {/* 직접 입력 옵션 */}
            <Card className="border-2 border-blue-200 hover:shadow-md transition-shadow cursor-pointer bg-blue-50/30" 
                  onClick={handleDirectCreate}>
              <CardContent className="p-4">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-4">
                    <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                      <Plus className="w-6 h-6 text-blue-600" />
                    </div>
                    <div>
                      <h3 className="font-semibold text-lg">직접 입력으로 수�� 등록</h3>
                      <p className="text-sm text-muted-foreground">견적 없이 바로 수주를 등록합니다</p>
                    </div>
                  </div>
                  <Button size="sm" onClick={(e) => {
                    e.stopPropagation();
                    handleDirectCreate();
                  }}>
                    등록하기
                  </Button>
                </div>
              </CardContent>
            </Card>

            {/* 견적에서 불러오기 */}
            {finalizedQuotes.length > 0 && (
              <>
                <div className="relative">
                  <div className="absolute inset-0 flex items-center">
                    <span className="w-full border-t" />
                  </div>
                  <div className="relative flex justify-center text-xs uppercase">
                    <span className="bg-background px-2 text-muted-foreground">또는 견적에서 불러오기</span>
                  </div>
                </div>

                <div className="space-y-3">
                  {finalizedQuotes.map((quote) => (
                    <Card key={quote.id} className="hover:shadow-md transition-shadow cursor-pointer" 
                          onClick={() => handleSelectQuote(quote.id)}>
                      <CardContent className="p-4">
                        <div className="flex items-start justify-between">
                          <div className="flex-1 space-y-2">
                            <div className="flex items-center gap-3">
                              <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">
                                확정 완료
                              </Badge>
                              <span className="font-mono text-sm text-gray-600">
                                {quote.quoteNumber}
                              </span>
                              {quote.currentRevision > 0 && (
                                <Badge variant="outline" className="text-xs">
                                  V{quote.currentRevision}
                                </Badge>
                              )}
                            </div>
                            
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                              <div>
                                <Label className="text-xs text-muted-foreground">고객명</Label>
                                <p className="font-medium">{quote.customerName}</p>
                              </div>
                              <div>
                                <Label className="text-xs text-muted-foreground">프로젝트명</Label>
                                <p className="font-medium">{quote.projectName}</p>
                              </div>
                              <div>
                                <Label className="text-xs text-muted-foreground">견적일</Label>
                                <p className="text-sm">{formatDate(quote.quoteDate)}</p>
                              </div>
                              <div>
                                <Label className="text-xs text-muted-foreground">견적금액</Label>
                                <p className="font-medium text-blue-600">{formatAmount(quote.totalAmount)}</p>
                              </div>
                              {quote.finalizedDate && (
                                <div>
                                  <Label className="text-xs text-muted-foreground">확정일</Label>
                                  <p className="text-sm">{formatDate(quote.finalizedDate)}</p>
                                </div>
                              )}
                              {quote.finalizedBy && (
                                <div>
                                  <Label className="text-xs text-muted-foreground">확정자</Label>
                                  <p className="text-sm">{quote.finalizedBy}</p>
                                </div>
                              )}
                            </div>
                          </div>
                          
                          <Button size="sm" onClick={(e) => {
                            e.stopPropagation();
                            handleSelectQuote(quote.id);
                          }}>
                            <CheckCircle className="w-4 h-4 mr-2" />
                            선택
                          </Button>
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              </>
            )}

            {finalizedQuotes.length === 0 && (
              <div className="text-center py-8 text-gray-500 border border-dashed rounded-lg">
                <FileText className="w-12 h-12 mx-auto mb-4 text-gray-400" />
                <p className="font-medium">확정된 견적이 없습니다</p>
                <p className="text-sm mt-2">위의 "직접 입력으로 수주 등록"을 이용해주세요</p>
              </div>
            )}
          </div>
        </DialogContent>
      </Dialog>

    </PageLayout>
  );
}