/**
 * 견적 관리 목록 - 아토믹 디자인 시스템 적용
 * 
 * QuoteManagement3List.tsx를 디자인 시스템의 유기체/템플릿으로 재구성한 버전입니다.
 * - 검색 필터: SearchFilter 유기체
 * - 통계 카드: StatCards 유기체
 * - 데스크톱 테이블: DataTable 유기체
 * - 모바일 목록: QuoteListTemplate 템플릿
 */

import { useState } from "react";
import { FileText, Plus, Edit, Eye, Trash2, CheckCircle, History, Calculator, X } from "lucide-react";
import { PageLayout } from "./organisms/PageLayout";
import { PageHeader } from "./organisms/PageHeader";
import { StatCards } from "./organisms/StatCards";
import { DataTable, Column } from "./organisms/DataTable";
import { QuoteListTemplate, QuoteListItem } from "./templates/QuoteListTemplate";
import { Card, CardContent } from "./ui/card";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "./ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Separator } from "./ui/separator";
import { QuoteData } from "./QuoteManagement3Write";
import { QuoteCalculationReport } from "./QuoteCalculationReport";
import { toast } from "sonner@2.0.3";

export function QuoteManagement3List_Redesigned({
  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 [filterStatus, setFilterStatus] = useState("all");
  const [currentPage, setCurrentPage] = useState(1);
  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);

  // 필터링된 견적 (내림차순 정렬: 최신 견적이 맨 위)
  const filteredQuotes = quotes
    .filter((quote) => {
      const searchLower = searchTerm.toLowerCase();
      const matchesSearch =
        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);

      let matchesStatus = true;
      if (filterStatus === "final") {
        matchesStatus = quote.isFinal === true;
      } else if (filterStatus === "draft") {
        matchesStatus = !quote.isFinal && quote.status !== "converted";
      } else if (filterStatus === "converted") {
        matchesStatus = quote.status === "converted";
      }

      return matchesSearch && matchesStatus;
    })
    .sort((a, b) => {
      // 등록일 기준 내림차순 정렬 (최신 견적이 먼저)
      const dateA = new Date(a.registrationDate || a.createdAt || 0).getTime();
      const dateB = new Date(b.registrationDate || b.createdAt || 0).getTime();
      return dateB - dateA;
    });

  // 통계 데이터
  const stats = [
    {
      label: "총 견적서",
      value: quotes.length,
      icon: FileText,
      iconColor: "text-blue-600",
    },
    {
      label: "최종 확정",
      value: quotes.filter((q) => q.isFinal).length,
      icon: CheckCircle,
      iconColor: "text-green-600",
    },
    {
      label: "수정중",
      value: quotes.filter((q) => !q.isFinal && q.status !== "converted" && (q.currentRevision || 0) > 0).length,
      icon: Edit,
      iconColor: "text-orange-600",
    },
    {
      label: "수주 전환",
      value: quotes.filter((q) => q.status === "converted").length,
      icon: CheckCircle,
      iconColor: "text-purple-600",
    },
  ];

  // 핸들러
  const handleViewDetail = (quote: QuoteData) => {
    if (onView) {
      onView(quote.id);
    } else {
      setSelectedQuote(quote);
      setSelectedRevisionNumber(null);
      setIsDetailDialogOpen(true);
    }
  };

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

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

  const handleDelete = (quoteId: string) => {
    const quote = quotes.find((q) => q.id === quoteId);
    if (quote && confirm(`견적번호 ${quote.quoteNumber}을(를) 삭제하시겠습니까?`)) {
      onDelete(quoteId);
      toast.success("견적이 삭제되었습니다");
    }
  };

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

  // 상태 뱃지
  const getRevisionBadge = (quote: QuoteData) => {
    if (quote.status === "converted") {
      return (
        <Badge variant="default" className="bg-purple-600">
          <CheckCircle className="w-3 h-3 mr-1" />
          수주전환
        </Badge>
      );
    }
    if (quote.isFinal) {
      return (
        <Badge variant="default" className="bg-green-600">
          <CheckCircle className="w-3 h-3 mr-1" />
          최종확정
        </Badge>
      );
    }
    if ((quote.currentRevision || 0) > 0) {
      return (
        <Badge variant="secondary" className="bg-orange-100 text-orange-700 border-orange-300">
          <History className="w-3 h-3 mr-1" />
          {quote.currentRevision}차 수정
        </Badge>
      );
    }
    return <Badge variant="outline" className="bg-gray-50">최초 작성</Badge>;
  };

  // QuoteListItem 형식으로 변환
  const quoteListItems: QuoteListItem[] = filteredQuotes.map((quote) => ({
    id: quote.id,
    quoteNumber: quote.quoteNumber || "",
    registrationDate: quote.registrationDate || "",
    client: quote.client || "",
    site: quote.site,
    manager: quote.manager,
    contact: quote.contact,
    productCode: quote.productCode,
    quantity: quote.quantity,
    amount: quote.amount || 0,
    status: quote.status,
    currentRevision: quote.currentRevision,
    isFinal: quote.isFinal,
    type: quote.type,
    remarks: quote.remarks,
  }));

  // DataTable용 컬럼 정의
  const tableColumns: Column<QuoteData>[] = [
    {
      key: "quoteNumber",
      label: "견적번호",
      type: "text",
      width: "150px",
      render: (value) => (
        <code className="text-xs bg-blue-50 text-blue-700 px-2 py-1 rounded font-mono">
          {value || "-"}
        </code>
      ),
    },
    {
      key: "registrationDate",
      label: "접수일",
      type: "text",
      width: "120px",
    },
    {
      key: "status",
      label: "상태",
      type: "custom",
      width: "110px",
      render: (_, row) => getRevisionBadge(row),
    },
    {
      key: "type",
      label: "구분",
      type: "badge",
      width: "80px",
      render: (value) => value || "일반",
      badgeConfig: {
        variant: "outline",
      },
    },
    {
      key: "productCode",
      label: "제품코드",
      type: "text",
      width: "100px",
    },
    {
      key: "quantity",
      label: "수량",
      type: "text",
      width: "70px",
      align: "center",
      render: (value) => String(value || 0),
    },
    {
      key: "amount",
      label: "금액",
      type: "text",
      width: "120px",
      align: "right",
      render: (value) => formatAmount(Number(value) || 0),
    },
    {
      key: "client",
      label: "발주처",
      type: "text",
      width: "150px",
    },
    {
      key: "site",
      label: "현장명",
      type: "text",
      width: "150px",
    },
    {
      key: "manager",
      label: "담당자",
      type: "text",
      width: "100px",
    },
    {
      key: "contact",
      label: "연락처",
      type: "text",
      width: "120px",
      render: (value) => <span className="text-muted-foreground">{value || "-"}</span>,
    },
    {
      key: "remarks",
      label: "비고",
      type: "text",
      minWidth: "200px",
    },
  ];

  // 테이블 액션
  const tableActions = (quote: QuoteData) => [
    ...(quote.currentRevision || 0) > 0
      ? [
          {
            label: "이력",
            icon: History,
            onClick: () => handleViewRevisionHistory(quote),
            variant: "ghost" as const,
          },
        ]
      : [],
    {
      label: "산출",
      icon: Calculator,
      onClick: () => handleViewCalculationReport(quote),
      variant: "ghost" as const,
    },
    {
      label: "상세",
      icon: Eye,
      onClick: () => handleViewDetail(quote),
      variant: "ghost" as const,
    },
    {
      label: "수정",
      icon: Edit,
      onClick: () => onEdit(quote),
      variant: "ghost" as const,
    },
    ...(!quote.isFinal && onFinalize
      ? [
          {
            label: "확정",
            icon: CheckCircle,
            onClick: () => onFinalize(quote.id),
            variant: "ghost" as const,
          },
        ]
      : []),
    ...(!quote.isFinal
      ? [
          {
            label: "삭제",
            icon: Trash2,
            onClick: () => handleDelete(quote.id),
            variant: "ghost" as const,
            disabled: quote.isFinal,
          },
        ]
      : []),
  ];

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

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

      {/* 검색 필터 */}
      <Card className="hidden lg:block">
        <CardContent className="p-4">
          <div className="flex gap-4">
            <div className="flex-1">
              <input
                type="text"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                placeholder="견적번호, 발주처, 담당자, 제품코드, 현장명으로 검색..."
                className="w-full px-4 py-2 border rounded-lg"
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 데스크톱: DataTable */}
      <div className="hidden lg:block">
        <DataTable
          data={filteredQuotes}
          columns={tableColumns}
          keyField="id"
          onRowClick={handleViewDetail}
          striped
          hoverable
          emptyMessage={searchTerm ? "검색 결과가 없습니다" : "작성된 견적서가 없습니다"}
        />
      </div>

      {/* 모바일: QuoteListTemplate */}
      <div className="block lg:hidden">
        <QuoteListTemplate
          quotes={quoteListItems}
          searchValue={searchTerm}
          onSearchChange={setSearchTerm}
          filterStatus={filterStatus}
          onFilterChange={setFilterStatus}
          currentPage={currentPage}
          onPageChange={setCurrentPage}
          itemsPerPage={20}
          onQuoteClick={(quote) => handleViewDetail(quotes.find((q) => q.id === quote.id)!)}
          onEdit={(quote) => onEdit(quotes.find((q) => q.id === quote.id)!)}
          onView={(quote) => handleViewDetail(quotes.find((q) => q.id === quote.id)!)}
          onDelete={handleDelete}
          onViewHistory={(quote) => handleViewRevisionHistory(quotes.find((q) => q.id === quote.id)!)}
          onViewCalculation={(quote) => handleViewCalculationReport(quotes.find((q) => q.id === quote.id)!)}
          onFinalize={onFinalize}
          showActions={true}
        />
      </div>

      {/* 상세 보기 다이얼로그 */}
      <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.contact}</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 &&
                [...selectedQuote.revisions].reverse().map((revision, index) => (
                  <Card key={revision.id}>
                    <CardContent className="pt-6">
                      <div className="flex items-start justify-between mb-4">
                        <div>
                          <Badge variant="secondary" className="bg-orange-100 text-orange-700 border-orange-300 mb-2">
                            <History className="w-3 h-3 mr-1" />
                            V{revision.revisionNumber - 1} → V{revision.revisionNumber}
                          </Badge>
                          <div className="text-xs text-muted-foreground space-y-1">
                            <div>📅 {revision.revisionDate}</div>
                            <div>👤 {revision.revisedBy}</div>
                            <div className="text-orange-700">📝 {revision.revisionReason}</div>
                          </div>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))}

              {/* 수정 이력이 없을 때 */}
              {(!selectedQuote.revisions || selectedQuote.revisions.length === 0) && (
                <div className="text-center py-8 text-muted-foreground">수정 이력이 없습니다</div>
              )}
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 산출내역서 다이얼로그 */}
      <Dialog open={isCalculationReportOpen} onOpenChange={setIsCalculationReportOpen}>
        <DialogContent className="max-w-[95vw] md:max-w-[800px] lg:max-w-[900px] h-[95vh] flex flex-col p-0 overflow-hidden">
          <DialogHeader className="flex-shrink-0 px-6 py-4 border-b">
            <DialogTitle>산출내역서</DialogTitle>
          </DialogHeader>

          {/* 닫기 버튼 */}
          <div className="flex-shrink-0 px-6 py-3 border-b bg-muted/30 flex justify-end">
            <Button size="sm" variant="outline" onClick={() => setIsCalculationReportOpen(false)}>
              <X className="w-4 h-4 mr-2" />
              닫기
            </Button>
          </div>

          {/* 스크롤 가능한 문서 영역 */}
          <div className="flex-1 overflow-hidden bg-gray-100">
            <div
              className="h-full overflow-y-auto p-4"
              style={{
                scrollbarWidth: "thin",
                scrollbarColor: "rgb(203 213 225) transparent",
              }}
            >
              <div className="max-w-[210mm] mx-auto bg-white shadow-lg rounded-lg p-8">
                {selectedQuote && <QuoteCalculationReport quote={selectedQuote as any} documentType="견적산출내역서" />}
              </div>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </PageLayout>
  );
}