import { useState } from "react";
import { Card, CardContent } from "./ui/card";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { BadgeSm, getQuoteStatusBadge } from "./atoms/BadgeSm";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "./ui/dialog";
import { Separator } from "./ui/separator";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { 
  Plus,
  Eye,
  Edit,
  Trash2,
  FileText,
  CheckCircle,
  History,
  Lock,
  Calculator
} from "lucide-react";
import { QuoteData } from "./QuoteManagement3Write";
import { PageLayout } from "./organisms/PageLayout";
import { PageHeader } from "./organisms/PageHeader";
import { StatCards } from "./organisms/StatCards";
import { SearchFilter } from "./organisms/SearchFilter";
import { EmptyState } from "./organisms/EmptyState";
import { MobileCard } from "./organisms/MobileCard";
import type { QuoteRevision } from "./contexts/DataContext";
import { QuoteCalculationReport } from "./QuoteCalculationReport";

export function QuoteManagement3List({ 
  quotes, 
  onNew,
  onView,
  onEdit, 
  onDelete,
  onFinalize
}: { 
  quotes: QuoteData[];
  onNew: () => void;
  onView?: (id: string) => void;
  onEdit: (quote: QuoteData) => void;
  onDelete: (id: string) => void;
  onFinalize?: (id: string) => void;
}) {
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedQuote, setSelectedQuote] = useState<QuoteData | null>(null);
  const [isDetailDialogOpen, setIsDetailDialogOpen] = useState(false);
  const [isRevisionHistoryOpen, setIsRevisionHistoryOpen] = useState(false);
  const [isCalculationReportOpen, setIsCalculationReportOpen] = useState(false);
  const [selectedRevisionNumber, setSelectedRevisionNumber] = useState<number | null>(null);

  // 데이터 로깅
  console.log("📊 견적 목록 데이터:", quotes.map(q => ({
    id: q.id,
    quoteNumber: q.quoteNumber,
    currentRevision: q.currentRevision,
    revisionsCount: q.revisions?.length || 0,
    isFinal: q.isFinal,
    status: q.status
  })));

  // 🔧 샘플 데이터 제거 - 실제 DataContext 데이터만 사용
  const allQuotes = quotes;
  
  console.log("🔍 QuoteManagement3List - 전체 견적:", allQuotes.length, "개");
  console.log("📋 전체 견적 목록:", allQuotes.map(q => ({ id: q.id, quoteNumber: q.quoteNumber })));

  const handleViewDetail = (quote: QuoteData) => {
    // onView가 있으면 페이지로 이동, 없으면 다이얼로그 표시
    if (onView) {
      onView(quote.id);
    } else {
      setSelectedQuote(quote);
      setSelectedRevisionNumber(null); // 현재 버전 (null = 최신)
      setIsDetailDialogOpen(true);
    }
  };

  const handleViewRevisionHistory = (quote: QuoteData) => {
    setSelectedQuote(quote);
    setIsRevisionHistoryOpen(true);
  };

  const handleViewCalculationReport = (quote: QuoteData) => {
    setSelectedQuote(quote);
    setIsCalculationReportOpen(true);
  };

  // 검색 필터링
  const filteredQuotes = allQuotes.filter(quote => {
    const searchLower = searchTerm.toLowerCase();
    return (
      quote.quoteNumber?.toLowerCase().includes(searchLower) ||
      quote.client?.toLowerCase().includes(searchLower) ||
      quote.manager?.toLowerCase().includes(searchLower) ||
      quote.productCode?.toLowerCase().includes(searchLower) ||
      quote.remarks?.toLowerCase().includes(searchLower) ||
      quote.site?.toLowerCase().includes(searchLower)
    );
  });

  // 통계
  const stats = [
    {
      label: "총 견적서",
      value: allQuotes.length,
      icon: FileText,
      iconColor: "text-blue-600"
    },
    {
      label: "수주 전환",
      value: allQuotes.filter(q => q.status === 'converted').length,
      icon: CheckCircle,
      iconColor: "text-purple-600"
    },
    {
      label: "최종 확정",
      value: allQuotes.filter(q => q.isFinal).length,
      icon: CheckCircle,
      iconColor: "text-green-600"
    },
    {
      label: "총 견적금액",
      value: `${Math.round(allQuotes.reduce((sum, q) => sum + (q.amount || 0), 0) / 10000)}만원`,
      icon: FileText,
      iconColor: "text-orange-600"
    }
  ];

  // 금액 포맷팅
  const formatAmount = (amount: number) => {
    return amount.toLocaleString('ko-KR');
  };

  // 수정 차수 Badge
  const getRevisionBadge = (quote: QuoteData) => {
    return getQuoteStatusBadge({
      status: quote.status,
      isFinal: quote.isFinal,
      currentRevision: quote.currentRevision
    });
  };

  return (
    <PageLayout>
      {/* 헤더 */}
      <PageHeader 
        title="견적 관리"
        description="작성된 견적서 목록을 확인하고 관리합니다"
        icon={FileText}
        actions={
          <Button onClick={onNew}>
            <Plus className="w-4 h-4 mr-2" />
            견적 등록
          </Button>
        }
      />

      {/* 검색 및 필터 */}
      <SearchFilter 
        searchValue={searchTerm}
        onSearchChange={setSearchTerm}
        searchPlaceholder="견적번호, 발주처, 담당자, 제품코드, 현장명으로 검색..."
      />

      {/* 통계 카드 */}
      <StatCards stats={stats} />

      {/* 견적 목록 */}
      {filteredQuotes.length === 0 ? (
        <EmptyState 
          icon={FileText}
          title={searchTerm ? '검색 결과가 없습니다' : '작성된 견적서가 없습니다'}
          description={searchTerm ? '다른 검색어를 시도해보세요' : '첫 견적서를 작성하여 시작하세요'}
          action={!searchTerm ? {
            label: '첫 견적서 작성하기',
            onClick: onNew
          } : undefined}
        />
      ) : (
        <>
          {/* 데스크톱 테이블 */}
          <Card className="hidden md:block">
            <CardContent className="p-0">
              {/* 데스크톱: 테이블 뷰 */}
              <div className="hidden md:block">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-[60px] text-center">번호</TableHead>
                      <TableHead className="w-[120px]">접수일</TableHead>
                      <TableHead className="w-[150px]">견적번호</TableHead>
                      <TableHead className="w-[110px]">상태</TableHead>
                      <TableHead className="w-[100px]">제품코드</TableHead>
                      <TableHead className="w-[70px] text-center">수량</TableHead>
                      <TableHead className="w-[120px] text-right">금액</TableHead>
                      <TableHead className="w-[150px]">발주처</TableHead>
                      <TableHead className="w-[150px]">현장명</TableHead>
                      <TableHead className="w-[100px]">담당자</TableHead>
                      <TableHead className="min-w-[200px]">비고</TableHead>
                      <TableHead className="w-[140px] text-right">관리</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {[...filteredQuotes].reverse().map((quote, index) => (
                      <TableRow 
                        key={quote.id}
                        className="cursor-pointer hover:bg-muted/30 transition-colors"
                        onClick={() => handleViewDetail(quote)}
                      >
                        <TableCell className="text-center">
                          {filteredQuotes.length - index}
                        </TableCell>
                        <TableCell>
                          {quote.registrationDate || '-'}
                        </TableCell>
                        <TableCell className="text-blue-600">
                          {quote.quoteNumber || '-'}
                        </TableCell>
                        <TableCell>
                          <div className="flex flex-wrap gap-1">
                            {getRevisionBadge(quote)}
                          </div>
                        </TableCell>
                        <TableCell>
                          {quote.productCode || '-'}
                        </TableCell>
                        <TableCell className="text-center">
                          {quote.quantity || 0}
                        </TableCell>
                        <TableCell className="text-right">
                          {formatAmount(quote.amount || 0)}
                        </TableCell>
                        <TableCell>
                          {quote.client || '-'}
                        </TableCell>
                        <TableCell>
                          {quote.site || '-'}
                        </TableCell>
                        <TableCell>
                          {quote.manager || '-'}
                        </TableCell>
                        <TableCell>
                          {quote.remarks || '-'}
                        </TableCell>
                        <TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
                          <div className="flex justify-end gap-1">
                            <Button 
                              variant="ghost" 
                              size="sm"
                              onClick={() => handleViewRevisionHistory(quote)}
                              title="수정 이력"
                            >
                              <History className="w-4 h-4 text-orange-600" />
                            </Button>
                            <Button 
                              variant="ghost" 
                              size="sm"
                              onClick={() => handleViewCalculationReport(quote)}
                              title="산출내역서"
                            >
                              <Calculator className="w-4 h-4 text-blue-600" />
                            </Button>
                            <Button 
                              variant="ghost" 
                              size="sm"
                              onClick={() => handleViewDetail(quote)}
                            >
                              <Eye className="w-4 h-4" />
                            </Button>
                            <Button 
                              variant="ghost" 
                              size="sm"
                              onClick={() => onEdit(quote)}
                              title={quote.isFinal ? "확정 견적도 수정 가능합니다" : "견적 수정"}
                            >
                              <Edit className="w-4 h-4" />
                            </Button>
                            {!quote.isFinal && onFinalize && (
                              <Button 
                                variant="ghost" 
                                size="sm"
                                onClick={() => onFinalize(quote.id)}
                                title="최종 확정"
                              >
                                <CheckCircle className="w-4 h-4 text-green-600" />
                              </Button>
                            )}
                            <Button 
                              variant="ghost" 
                              size="sm"
                              onClick={() => {
                                if (confirm('정말 삭제하시겠습니까?')) {
                                  onDelete(quote.id);
                                }
                              }}
                              disabled={quote.isFinal}
                            >
                              <Trash2 className={`w-4 h-4 ${quote.isFinal ? 'text-muted' : 'text-destructive'}`} />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              {/* 모바일/태블릿: 카드 뷰 (MobileCard 컴포넌트 사용) */}
              <div className="block md:hidden p-4 space-y-3">
                {[...filteredQuotes].reverse().map((quote, index) => {
                  // 액션 버튼 구성
                  const actions = [
                    {
                      label: "이력",
                      onClick: () => handleViewRevisionHistory(quote),
                      icon: History,
                      variant: "outline" as const
                    },
                    {
                      label: "산출",
                      onClick: () => handleViewCalculationReport(quote),
                      icon: Calculator,
                      variant: "outline" as const
                    },
                    {
                      label: "보기",
                      onClick: () => handleViewDetail(quote),
                      icon: Eye,
                      variant: "outline" as const
                    },
                    {
                      label: "수정",
                      onClick: () => onEdit(quote),
                      icon: Edit,
                      variant: "outline" as const
                    },
                    ...(!quote.isFinal && onFinalize ? [{
                      label: "확정",
                      onClick: () => onFinalize(quote.id),
                      icon: CheckCircle,
                      variant: "outline" as const
                    }] : []),
                    ...(!quote.isFinal ? [{
                      label: "삭제",
                      onClick: () => {
                        if (confirm('정말 삭제하시겠습니까?')) {
                          onDelete(quote.id);
                        }
                      },
                      icon: Trash2,
                      variant: "outline" as const
                    }] : [])
                  ];

                  // 필드 데이터 구성
                  const fields = [
                    { label: "접수일", value: quote.registrationDate || '-' },
                    ...(quote.currentRevision || 0) > 0 ? [{
                      label: "수정이력",
                      value: `${quote.currentRevision}회 (이력 ${quote.revisions?.length || 0}건)`
                    }] : [],
                    ...(quote.isFinal ? [{
                      label: "확정일",
                      value: quote.finalizedDate || '-'
                    }] : []),
                    { label: "발주처", value: quote.client || '-' },
                    { label: "현장명", value: quote.site || '-' },
                    { label: "제품코드", value: quote.productCode || '-' },
                    { label: "수량", value: String(quote.quantity || 0) },
                    { label: "금액", value: formatAmount(quote.amount || 0) },
                    { label: "담당자", value: quote.manager || '-' },
                    ...(quote.remarks ? [{ label: "비고", value: quote.remarks }] : [])
                  ];

                  return (
                    <div key={quote.id}>
                      <MobileCard
                        title={quote.quoteNumber || '-'}
                        subtitle={`#${filteredQuotes.length - index}`}
                        icon={<FileText className="w-5 h-5 text-blue-600" />}
                        badge={{
                          label: quote.isFinal ? '확정' : '작성중',
                          variant: quote.isFinal ? 'default' : 'outline'
                        }}
                        fields={fields}
                        actions={actions}
                        onCardClick={() => handleViewDetail(quote)}
                      />
                    </div>
                  );
                })}
              </div>
            </CardContent>
          </Card>

          {/* 상세 보기 다이얼로그 */}
          <Dialog open={isDetailDialogOpen} onOpenChange={setIsDetailDialogOpen}>
            <DialogContent className="max-w-3xl max-h-[80vh] overflow-y-auto">
              <DialogHeader>
                <DialogTitle className="flex items-center gap-2">
                  견적 상세 정보
                  {selectedQuote && getRevisionBadge(selectedQuote)}
                </DialogTitle>
                <DialogDescription>
                  {selectedQuote?.quoteNumber}
                </DialogDescription>
              </DialogHeader>
              {selectedQuote && (() => {
                // 선택된 이력 번호에 따라 데이터 가져오기
                let displayData = selectedQuote;
                
                if (selectedRevisionNumber !== null && selectedQuote.revisions) {
                  const revision = selectedQuote.revisions.find(r => r.revisionNumber === selectedRevisionNumber);
                  if (revision && revision.previousData) {
                    displayData = revision.previousData as QuoteData;
                  }
                }
                
                return (
                  <div className="space-y-4">
                    {/* 이력 선택 드롭다운 */}
                    {selectedQuote.revisions && selectedQuote.revisions.length > 0 && (
                      <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                        <div className="flex items-center gap-3">
                          <History className="w-5 h-5 text-blue-600" />
                          <div className="flex-1">
                            <label className="text-sm font-medium text-blue-900 block mb-2">
                              수정 이력 선택
                            </label>
                            <Select
                              value={selectedRevisionNumber === null ? "current" : String(selectedRevisionNumber)}
                              onValueChange={(value) => {
                                setSelectedRevisionNumber(value === "current" ? null : Number(value));
                              }}
                            >
                              <SelectTrigger className="w-full bg-white">
                                <SelectValue placeholder="버전 선택" />
                              </SelectTrigger>
                              <SelectContent>
                                <SelectItem value="current">
                                  <div className="flex items-center gap-2">
                                    <CheckCircle className="w-4 h-4 text-blue-600" />
                                    <span className="font-medium">현재 버전 (V{selectedQuote.currentRevision || 0})</span>
                                    {selectedQuote.isFinal && (
                                      <Badge variant="default" className="bg-green-600 ml-2">최종확정</Badge>
                                    )}
                                  </div>
                                </SelectItem>
                                {selectedQuote.revisions
                                  .sort((a, b) => b.revisionNumber - a.revisionNumber)
                                  .map((revision) => (
                                    <SelectItem key={revision.id} value={String(revision.revisionNumber)}>
                                      <div className="flex items-center gap-2">
                                        <History className="w-4 h-4 text-orange-600" />
                                        <span>V{revision.revisionNumber} - {revision.revisionDate}</span>
                                        <span className="text-xs text-muted-foreground ml-2">
                                          ({revision.revisionReason})
                                        </span>
                                      </div>
                                    </SelectItem>
                                  ))}
                              </SelectContent>
                            </Select>
                          </div>
                        </div>
                        {selectedRevisionNumber !== null && (
                          <div className="mt-2 text-xs text-blue-700 flex items-center gap-1">
                            <span>💡</span>
                            <span>이전 버전의 데이터를 조회하고 있습니다</span>
                          </div>
                        )}
                      </div>
                    )}
                    
                    {/* 상세 정보 */}
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <div className="text-muted-foreground">발주처</div>
                      <div>{displayData.client}</div>
                    </div>
                    <div>
                      <div className="text-muted-foreground">담당자</div>
                      <div>{displayData.manager}</div>
                    </div>
                    <div>
                      <div className="text-muted-foreground">접수일</div>
                      <div>{displayData.registrationDate}</div>
                    </div>
                    <div>
                      <div className="text-muted-foreground">제품코드</div>
                      <div>{displayData.productCode}</div>
                    </div>
                    <div>
                      <div className="text-muted-foreground">수량</div>
                      <div>{displayData.quantity}</div>
                    </div>
                    <div>
                      <div className="text-muted-foreground">현장명</div>
                      <div>{displayData.site || '-'}</div>
                    </div>
                    <div>
                      <div className="text-muted-foreground">오픈사이즈</div>
                      <div>
                        {displayData.openSizeWidth && displayData.openSizeHeight 
                          ? `${displayData.openSizeWidth} × ${displayData.openSizeHeight}` 
                          : '-'}
                      </div>
                    </div>
                    <div className="col-span-2">
                      <div className="text-muted-foreground">금액</div>
                      <div className="text-blue-600">
                        {formatAmount(displayData.amount || 0)}원
                      </div>
                    </div>
                    {selectedQuote.isFinal && selectedRevisionNumber === null && (
                      <>
                        <div>
                          <div className="text-muted-foreground">최종 확정일</div>
                          <div>{selectedQuote.finalizedDate}</div>
                        </div>
                        <div>
                          <div className="text-muted-foreground">확정자</div>
                          <div>{selectedQuote.finalizedBy}</div>
                        </div>
                      </>
                    )}
                  </div>
                  
                  {displayData.remarks && (
                    <>
                      <Separator />
                      <div>
                        <div className="text-muted-foreground mb-1">비고</div>
                        <div>{displayData.remarks}</div>
                      </div>
                    </>
                  )}
                  
                  {displayData.commitment && (
                    <div>
                      <div className="text-muted-foreground mb-1">확약사항</div>
                      <div>{displayData.commitment}</div>
                    </div>
                  )}
                  
                  {selectedRevisionNumber !== null && selectedQuote.revisions && (
                    <>
                      <Separator />
                      <div className="bg-orange-50 border border-orange-200 rounded-lg p-3">
                        <div className="text-orange-900 mb-1">수정 정보</div>
                        {(() => {
                          const revision = selectedQuote.revisions.find(r => r.revisionNumber === selectedRevisionNumber);
                          if (revision) {
                            return (
                              <div className="text-xs text-orange-700 space-y-1">
                                <div>수정일: {revision.revisionDate}</div>
                                <div>수정자: {revision.revisedBy}</div>
                                <div>수정 사유: {revision.revisionReason}</div>
                              </div>
                            );
                          }
                          return null;
                        })()}
                      </div>
                    </>
                  )}
                </div>
                );
              })()}
            </DialogContent>
          </Dialog>

          {/* 수정 이력 다이얼로그 */}
          <Dialog open={isRevisionHistoryOpen} onOpenChange={setIsRevisionHistoryOpen}>
            <DialogContent className="max-w-5xl max-h-[85vh] overflow-y-auto">
              <DialogHeader>
                <DialogTitle className="flex items-center gap-2">
                  <History className="w-5 h-5 text-orange-600" />
                  견적 수정 이력
                </DialogTitle>
                <DialogDescription>
                  {selectedQuote?.quoteNumber} - 총 <span className="font-semibold text-orange-600">{selectedQuote?.currentRevision || 0}회</span> 수정되었습니다
                </DialogDescription>
              </DialogHeader>
              {selectedQuote && (
                <div className="space-y-4">
                  {/* 현재 버전 */}
                  <Card className="border-2 border-blue-500 bg-blue-50/50">
                    <CardContent className="pt-6">
                      <div className="flex items-start justify-between mb-4">
                        <div>
                          <Badge variant="default" className="bg-blue-600 mb-2">
                            <CheckCircle className="w-3 h-3 mr-1" />
                            현재 버전 (V{selectedQuote.currentRevision || 0})
                          </Badge>
                          <div className="text-muted-foreground">
                            📅 {selectedQuote.registrationDate}
                          </div>
                        </div>
                        <div className="text-right">
                          <div className="text-blue-600">
                            {formatAmount(selectedQuote.amount || 0)}원
                          </div>
                          <div className="text-muted-foreground">수량: {selectedQuote.quantity}개</div>
                        </div>
                      </div>
                      <div className="grid grid-cols-2 gap-4 text-xs">
                        <div><strong className="text-muted-foreground">발주처:</strong> {selectedQuote.client}</div>
                        <div><strong className="text-muted-foreground">제품:</strong> {selectedQuote.productCode}</div>
                      </div>
                    </CardContent>
                  </Card>

                  {/* 수정 이력 */}
                  {selectedQuote.revisions && selectedQuote.revisions.length > 0 ? (
                    <>
                      <Separator className="my-6" />
                      <div className="space-y-4">
                        <h4 className="font-semibold text-sm text-muted-foreground flex items-center gap-2">
                          <History className="w-4 h-4" />
                          이전 버전 기록 ({selectedQuote.revisions.length}건)
                        </h4>
                        {[...selectedQuote.revisions].reverse().map((revision: QuoteRevision) => (
                          <Card key={revision.revisionNumber} className="bg-gray-50/50">
                            <CardContent className="pt-6">
                              <div className="flex items-start justify-between mb-4">
                                <div className="flex-1">
                                  <div className="flex items-center gap-2 mb-2">
                                    <Badge variant="outline" className="bg-white">
                                      V{revision.revisionNumber - 1} → V{revision.revisionNumber}
                                    </Badge>
                                    <Badge variant="secondary" className="bg-orange-100 text-orange-700">
                                      {revision.revisionNumber}차 수정
                                    </Badge>
                                  </div>
                                  <div className="text-sm text-muted-foreground mb-2">
                                    📅 {revision.revisionDate} | 👤 {revision.revisionBy}
                                  </div>
                                  {revision.revisionReason && (
                                    <div className="bg-white p-3 rounded-md border text-sm mt-2">
                                      <div className="flex items-start gap-2">
                                        <span className="font-semibold text-orange-600">💬 수정 사유:</span>
                                        <span className="flex-1">{revision.revisionReason}</span>
                                      </div>
                                    </div>
                                  )}
                                </div>
                                <div className="text-right ml-4">
                                  <div className="text-xl font-semibold">
                                    {formatAmount(revision.previousData.amount || revision.previousData.totalAmount || 0)}원
                                  </div>
                                  <div className="text-sm text-muted-foreground">
                                    수량: {revision.previousData.quantity}개
                                  </div>
                                </div>
                              </div>
                              <div className="grid grid-cols-2 gap-4 text-sm pt-3 border-t">
                                <div><strong className="text-muted-foreground">발주처:</strong> {revision.previousData.client || revision.previousData.customerName}</div>
                                <div><strong className="text-muted-foreground">제품:</strong> {revision.previousData.productCode}</div>
                              </div>
                            </CardContent>
                          </Card>
                        ))}
                      </div>
                    </>
                  ) : (
                    <div className="text-center py-8 text-muted-foreground">
                      <History className="w-12 h-12 mx-auto mb-3 opacity-20" />
                      <p>정 이력이 없습니다</p>
                      <p className="text-sm mt-1">최초 작성된 견적서입니다</p>
                    </div>
                  )}
                </div>
              )}
            </DialogContent>
          </Dialog>

          {/* 산출내역서 */}
          {isCalculationReportOpen && selectedQuote && (
            <QuoteCalculationReport 
              quote={selectedQuote as any}
              onClose={() => setIsCalculationReportOpen(false)}
            />
          )}
        </>
      )}

    </PageLayout>
  );
}