import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "./ui/dialog";
import { Plus, Download } from "lucide-react";
import { QuoteCreation } from "./QuoteCreation";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Badge } from "./ui/badge";
import { useData } from "./contexts/DataContext";

// 견적 목록 컴포넌트
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">
      <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>
  );
}

export function SalesManagement() {
  const [isQuoteCreationOpen, setIsQuoteCreationOpen] = useState(false);

  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>
            <Button 
              className="bg-primary text-primary-foreground"
              onClick={() => setIsQuoteCreationOpen(true)}
            >
              <Plus className="h-4 w-4 mr-2" />
              신규 등록
            </Button>
          </div>
        </div>
      </div>

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

      {/* 견적 목록 */}
      <div className="bg-card border border-border/20 rounded-xl p-6">
        <h2 className="text-xl font-bold mb-4">견적 목록</h2>
        <QuoteList />
      </div>
    </div>
  );
}