import { useState, useMemo } from "react";
import { Button } from "./ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Dialog, DialogContent, DialogTitle, DialogDescription, DialogHeader } from "./ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Plus, Download, FileText, ShoppingCart, TrendingUp, DollarSign } from "lucide-react";
import { QuoteCreation } from "./QuoteCreation";
import { QuoteManagement3List } from "./QuoteManagement3List";
import { OrderRegistration } from "./OrderRegistration";
import { useData } from "./contexts/DataContext";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Badge } from "./ui/badge";
import { MobileCard } from "./organisms/MobileCard";

// 견적 목록 컴포넌트
function QuoteList() {
  const { quotes } = useData();
  
  const getStatusBadge = (status: string) => {
    const statusMap: Record<string, { label: string; variant: "default" | "secondary" | "destructive" | "outline" }> = {
      draft: { label: "초안", variant: "secondary" },
      sent: { label: "발송완료", variant: "default" },
      approved: { label: "승인", variant: "default" },
      rejected: { label: "거절", variant: "destructive" },
      expired: { label: "만료", variant: "outline" }
    };
    const statusInfo = statusMap[status] || { label: status, variant: "outline" };
    return <Badge variant={statusInfo.variant}>{statusInfo.label}</Badge>;
  };

  return (
    <div className="rounded-md border">
      {/* 데스크톱 테이블 */}
      <div className="hidden md:block">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>견적번호</TableHead>
              <TableHead>고객사</TableHead>
              <TableHead>프로젝트명</TableHead>
              <TableHead>견적일</TableHead>
              <TableHead>유효기한</TableHead>
              <TableHead className="text-right">견적금액</TableHead>
              <TableHead>상태</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {quotes.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                  등록된 견적이 없습니다.
                </TableCell>
              </TableRow>
            ) : (
              quotes.map((quote) => (
                <TableRow key={quote.id}>
                  <TableCell className="font-medium">{quote.quoteNumber}</TableCell>
                  <TableCell>{quote.customerName}</TableCell>
                  <TableCell>{quote.projectName}</TableCell>
                  <TableCell>{quote.quoteDate}</TableCell>
                  <TableCell>{quote.validUntil}</TableCell>
                  <TableCell className="text-right">{quote.totalAmount.toLocaleString()}원</TableCell>
                  <TableCell>{getStatusBadge(quote.status)}</TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* 모바일 카드 */}
      <div className="md:hidden space-y-3 p-4">
        {quotes.length === 0 ? (
          <div className="text-center py-8 text-muted-foreground">
            등록된 견적이 없습니다.
          </div>
        ) : (
          quotes.map((quote) => (
            <MobileCard
              key={quote.id}
              title={quote.quoteNumber}
              subtitle={quote.customerName}
              badge={{
                label: quote.status === 'draft' ? '초안' :
                       quote.status === 'sent' ? '발송완료' :
                       quote.status === 'approved' ? '승인' :
                       quote.status === 'rejected' ? '거절' :
                       quote.status === 'expired' ? '만료' : quote.status,
                variant: quote.status === 'approved' ? 'default' :
                        quote.status === 'rejected' ? 'destructive' : 'outline'
              }}
              fields={[
                { label: '프로젝트명', value: quote.projectName },
                { label: '견적일', value: quote.quoteDate },
                { label: '유효기한', value: quote.validUntil },
                { label: '견적금액', value: `${quote.totalAmount.toLocaleString()}원` }
              ]}
            />
          ))
        )}
      </div>
    </div>
  );
}

// 수주 목록 컴포넌트
function OrderList() {
  const { salesOrders } = useData();
  
  const getStatusBadge = (status: string) => {
    const statusMap: Record<string, { label: string; variant: "default" | "secondary" | "destructive" | "outline" }> = {
      registered: { label: "수주등록", variant: "secondary" },
      contract_completed: { label: "계약완료", variant: "default" },
      in_production: { label: "생산중", variant: "default" },
      shipping: { label: "출하중", variant: "default" },
      completed: { label: "완료", variant: "default" }
    };
    const statusInfo = statusMap[status] || { label: status, variant: "outline" };
    return <Badge variant={statusInfo.variant}>{statusInfo.label}</Badge>;
  };

  return (
    <div className="rounded-md border">
      {/* 데스크톱 테이블 */}
      <div className="hidden md:block">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>수주번호</TableHead>
              <TableHead>고객사</TableHead>
              <TableHead>프로젝트명</TableHead>
              <TableHead>수주일</TableHead>
              <TableHead>납기일</TableHead>
              <TableHead className="text-right">수주금액</TableHead>
              <TableHead>상태</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {salesOrders.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                  등록된 수주가 없습니다.
                </TableCell>
              </TableRow>
            ) : (
              salesOrders.map((order) => (
                <TableRow key={order.id}>
                  <TableCell className="font-medium">{order.orderNumber}</TableCell>
                  <TableCell>{order.customerName}</TableCell>
                  <TableCell>{order.projectName}</TableCell>
                  <TableCell>{order.orderDate}</TableCell>
                  <TableCell>{order.deliveryDate}</TableCell>
                  <TableCell className="text-right">{order.totalAmount.toLocaleString()}원</TableCell>
                  <TableCell>{getStatusBadge(order.status)}</TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* 모바일 카드 */}
      <div className="md:hidden space-y-3 p-4">
        {salesOrders.length === 0 ? (
          <div className="text-center py-8 text-muted-foreground">
            등록된 수주가 없습니다.
          </div>
        ) : (
          salesOrders.map((order) => (
            <MobileCard
              key={order.id}
              title={order.orderNumber}
              subtitle={order.customerName}
              badge={{
                label: order.status === 'registered' ? '수주등록' :
                       order.status === 'contract_completed' ? '계약완료' :
                       order.status === 'in_production' ? '생산중' :
                       order.status === 'shipping' ? '출하중' :
                       order.status === 'completed' ? '완료' : order.status,
                variant: order.status === 'completed' ? 'default' : 'outline'
              }}
              fields={[
                { label: '프로젝트명', value: order.projectName },
                { label: '수주일', value: order.orderDate },
                { label: '납기일', value: order.deliveryDate },
                { label: '수주금액', value: `${order.totalAmount.toLocaleString()}원` }
              ]}
            />
          ))
        )}
      </div>
    </div>
  );
}

export function SalesManagement() {
  const { salesOrders, quotes } = useData();
  const [isQuoteCreationOpen, setIsQuoteCreationOpen] = useState(false);
  const [isOrderRegistrationOpen, setIsOrderRegistrationOpen] = useState(false);
  const [activeTab, setActiveTab] = useState("quote");

  // 실제 데이터로부터 대시보드 통계 계산
  const dashboardData = useMemo(() => {
    const now = new Date();
    const thisMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
    
    // 이번 달 매출 (완료된 주문)
    const monthlyOrders = salesOrders.filter(order => 
      order.orderDate.startsWith(thisMonth) && 
      (order.status === 'completed' || order.status === 'shipping')
    );
    const monthlyRevenue = monthlyOrders.reduce((sum, order) => sum + order.totalAmount, 0);
    
    // 이번 달 견적 수
    const monthlyQuotes = quotes.filter(quote => quote.quoteDate.startsWith(thisMonth));
    const quoteCount = monthlyQuotes.length;
    
    // 이번 달 수주 수
    const orderCount = salesOrders.filter(order => 
      order.orderDate.startsWith(thisMonth)
    ).length;
    
    // 수주 전환율
    const conversionRate = quoteCount > 0 ? Math.round((orderCount / quoteCount) * 100) : 0;
    
    return {
      monthlyRevenue,
      quoteCount,
      orderCount,
      conversionRate
    };
  }, [salesOrders, quotes]);

  return (
    <div className="p-4 md:p-6 space-y-6">
      {/* 헤더 */}
      <div className="bg-card border border-border/20 rounded-xl p-6">
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div>
            <h1 className="text-3xl font-bold text-foreground mb-2">판매관리</h1>
            <p className="text-muted-foreground">견적, 수주, 거래처 및 설치 일정 통합 관리</p>
          </div>
          <div className="flex space-x-3">
            <Button variant="outline" className="border-border/50">
              <Download className="h-4 w-4 mr-2" />
              Excel 다운로드
            </Button>
            {activeTab === "quote" && (
              <Button 
                className="bg-primary text-primary-foreground"
                onClick={() => setIsQuoteCreationOpen(true)}
              >
                <Plus className="h-4 w-4 mr-2" />
                신규 등록
              </Button>
            )}
            {activeTab === "order" && (
              <Button 
                className="bg-primary text-primary-foreground"
                onClick={() => setIsOrderRegistrationOpen(true)}
              >
                <Plus className="h-4 w-4 mr-2" />
                수주 등록하기
              </Button>
            )}
          </div>
        </div>
      </div>

      {/* 판매 대시보드 */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <Card className="border-0 shadow-sm hover:shadow-md transition-all duration-300">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-xs sm:text-sm font-medium text-muted-foreground">월간 매출</CardTitle>
            <div className="w-8 h-8 sm:w-10 sm:h-10 bg-gradient-to-br from-blue-500 to-blue-600 rounded-lg flex items-center justify-center">
              <DollarSign className="h-4 w-4 sm:h-5 sm:w-5 text-white" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-lg sm:text-2xl font-bold">{(dashboardData.monthlyRevenue / 100000000).toFixed(1)}억원</div>
            <p className="text-xs text-muted-foreground mt-1">
              이번달 매출액
            </p>
          </CardContent>
        </Card>

        <Card className="border-0 shadow-sm hover:shadow-md transition-all duration-300">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-xs sm:text-sm font-medium text-muted-foreground">견적 건수</CardTitle>
            <div className="w-8 h-8 sm:w-10 sm:h-10 bg-gradient-to-br from-purple-500 to-purple-600 rounded-lg flex items-center justify-center">
              <FileText className="h-4 w-4 sm:h-5 sm:w-5 text-white" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-lg sm:text-2xl font-bold">{dashboardData.quoteCount}건</div>
            <p className="text-xs text-muted-foreground mt-1">
              이번달 견적 발행
            </p>
          </CardContent>
        </Card>

        <Card className="border-0 shadow-sm hover:shadow-md transition-all duration-300">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-xs sm:text-sm font-medium text-muted-foreground">수주 건수</CardTitle>
            <div className="w-8 h-8 sm:w-10 sm:h-10 bg-gradient-to-br from-green-500 to-green-600 rounded-lg flex items-center justify-center">
              <ShoppingCart className="h-4 w-4 sm:h-5 sm:w-5 text-white" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-lg sm:text-2xl font-bold">{dashboardData.orderCount}건</div>
            <p className="text-xs text-muted-foreground mt-1">
              이번달 수주 확정
            </p>
          </CardContent>
        </Card>

        <Card className="border-0 shadow-sm hover:shadow-md transition-all duration-300">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-xs sm:text-sm font-medium text-muted-foreground">수주 전환율</CardTitle>
            <div className="w-8 h-8 sm:w-10 sm:h-10 bg-gradient-to-br from-orange-500 to-orange-600 rounded-lg flex items-center justify-center">
              <TrendingUp className="h-4 w-4 sm:h-5 sm:w-5 text-white" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-lg sm:text-2xl font-bold">{dashboardData.conversionRate}%</div>
            <p className="text-xs text-muted-foreground mt-1">
              견적 대비 수주율
            </p>
          </CardContent>
        </Card>
      </div>

      {/* 견적 산출하기 모달 */}
      <Dialog open={isQuoteCreationOpen} onOpenChange={setIsQuoteCreationOpen}>
        <DialogContent className="max-w-[95vw] w-[95vw] max-h-[95vh] h-[95vh] overflow-hidden p-0" aria-describedby="quote-creation-description">
          <DialogHeader className="sr-only">
            <DialogTitle>견적 산출하기</DialogTitle>
            <DialogDescription id="quote-creation-description">
              새로운 견적을 산출하기 위한 정보를 입력합니다.
            </DialogDescription>
          </DialogHeader>
          <div className="h-full overflow-y-auto">
            <QuoteCreation onClose={() => setIsQuoteCreationOpen(false)} />
          </div>
        </DialogContent>
      </Dialog>

      {/* 수주 등록하기 모달 */}
      <Dialog open={isOrderRegistrationOpen} onOpenChange={setIsOrderRegistrationOpen}>
        <DialogContent className="max-w-[95vw] w-[95vw] max-h-[95vh] overflow-y-auto p-6" aria-describedby="order-registration-description">
          <DialogHeader className="sr-only">
            <DialogTitle>수주 등록하기</DialogTitle>
            <DialogDescription id="order-registration-description">
              새로운 수주를 등록합니다.
            </DialogDescription>
          </DialogHeader>
          <OrderRegistration 
            onComplete={() => setIsOrderRegistrationOpen(false)} 
            onCancel={() => setIsOrderRegistrationOpen(false)} 
          />
        </DialogContent>
      </Dialog>

      {/* 견적/수주 탭 */}
      <div className="bg-card border border-border/20 rounded-xl p-6">
        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList className="grid w-full max-w-md grid-cols-2">
            <TabsTrigger value="quote">견적 목록</TabsTrigger>
            <TabsTrigger value="order">수주 목록</TabsTrigger>
          </TabsList>

          <TabsContent value="quote" className="mt-6">
            <QuoteList />
          </TabsContent>

          <TabsContent value="order" className="mt-6">
            <OrderList />
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
}