/**
 * 견적관리 - IntegratedListTemplateV2 적용
 * 
 * 기준정보 -> 디자인시스템관리 -> 템플릿의 IntegratedListTemplateV2를 적용한 견적 관리 페이지입니다.
 * - PageHeader, StatCards, SearchFilter, 체크박스
 * - 데스크톱: TabsList + DataTable
 * - 모바일: 커스텀 버튼 탭 + 카드 리스트
 * - 완전한 반응형 지원
 */

import { useState, useRef, useEffect } from "react";
import { FileText, Edit, Eye, Trash2, CheckCircle, History, Calculator, ArrowLeft } from "lucide-react";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { BadgeSm, getQuoteStatusBadge } from "./atoms/BadgeSm";
import { useData } from "./contexts/DataContext";
import { IntegratedListTemplateV2, TabOption, TableColumn } from "./templates/IntegratedListTemplateV2";
import { toast } from "sonner@2.0.3";
import { QuoteManagement3Write } from "./QuoteManagement3Write";
import { QuoteManagement3Detail } from "./QuoteManagement3Detail";
import { QuoteDetailView } from "./QuoteDetailView";
import { StandardDialog } from "./molecules/StandardDialog";
import { Table, TableHeader, TableRow, TableHead, TableBody, TableCell } from "./ui/table";
import { Separator } from "./ui/separator";
import { Checkbox } from "./ui/checkbox";
import { Card } from "./ui/card";
import { MobileCard } from "./organisms/MobileCard"; // MobileCard 추가
import { formatAmount, formatAmountManwon } from "../utils/formatAmount";
import { StatusBadge } from "./molecules/StatusBadge";
import { ActionButtonGroup } from "./molecules/ActionButtonGroup";
import { ListMobileCard, InfoField } from "./organisms/ListMobileCard";
import { ListTableRow, CodeCell, ActionCell } from "./organisms/ListTableRow";

// 견적 타입
interface Quote {
  id: string;
  quoteNumber: string;
  registrationDate: string;
  client: string;
  site?: string;
  siteCode?: string;
  manager?: string;
  contact?: string;
  productCode?: string;
  quantity: number;
  amount: number;
  status: "draft" | "converted";
  currentRevision: number;
  isFinal: boolean;
  type?: string;
  remarks?: string;
}

// 샘플 견적 데이터
const SAMPLE_QUOTES: Quote[] = [
  {
    id: "SAMPLE-Q-001",
    quoteNumber: "Q2024-001",
    registrationDate: "2024-01-15",
    client: "ABC건설",
    site: "강남 오피스텔 현장",
    siteCode: "PJ-20240115-01",
    manager: "김철수",
    contact: "010-1234-5678",
    productCode: "SCR-001",
    quantity: 10,
    amount: 15000000,
    status: "draft",
    currentRevision: 0,
    isFinal: false,
    type: "스크린",
    remarks: "급하게 진행 필요",
  },
  {
    id: "SAMPLE-Q-002",
    quoteNumber: "Q2024-002",
    registrationDate: "2024-01-16",
    client: "XYZ산업",
    site: "판교 공장",
    siteCode: "PJ-20240116-01",
    manager: "이영희",
    contact: "010-2345-6789",
    productCode: "STL-002",
    quantity: 5,
    amount: 8500000,
    status: "draft",
    currentRevision: 2,
    isFinal: false,
    type: "철재",
    remarks: "",
  },
  {
    id: "SAMPLE-Q-003",
    quoteNumber: "Q2024-003",
    registrationDate: "2024-01-17",
    client: "DEF개발",
    site: "송도 아파트 현장",
    siteCode: "PJ-20240117-01",
    manager: "박민수",
    contact: "010-3456-7890",
    productCode: "SCR-003",
    quantity: 20,
    amount: 25000000,
    status: "draft",
    currentRevision: 0,
    isFinal: true,
    type: "스크린",
    remarks: "확정 완료",
  },
  {
    id: "SAMPLE-Q-004",
    quoteNumber: "Q2024-004",
    registrationDate: "2024-01-18",
    client: "GHI건축",
    site: "분당 상가 현장",
    siteCode: "PJ-20240118-01",
    manager: "최지원",
    contact: "010-4567-8901",
    productCode: "STL-004",
    quantity: 8,
    amount: 12000000,
    status: "converted",
    currentRevision: 1,
    isFinal: true,
    type: "철재",
    remarks: "수주 전환 완료",
  },
  {
    id: "SAMPLE-Q-005",
    quoteNumber: "Q2024-005",
    registrationDate: "2024-01-19",
    client: "JKL개발",
    site: "용산 오피스빌딩",
    siteCode: "PJ-20240119-01",
    manager: "정수민",
    contact: "010-5678-9012",
    productCode: "SCR-005",
    quantity: 15,
    amount: 22000000,
    status: "draft",
    currentRevision: 3,
    isFinal: false,
    type: "스크린",
    remarks: "3차 수정 중",
  },
];

export function QuoteManagement() {
  const [searchTerm, setSearchTerm] = useState("");
  const [filterType, setFilterType] = useState("all");
  const [currentView, setCurrentView] = useState<"list" | "create" | "detail" | "edit">("list");
  const [selectedQuote, setSelectedQuote] = useState<Quote | null>(null);
  const [isCalculationDialogOpen, setIsCalculationDialogOpen] = useState(false);
  const [calculationQuote, setCalculationQuote] = useState<Quote | null>(null);
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;
  
  // 삭제 확인 다이얼로그 state
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
  
  // 모바일 인피니티 스크롤 state
  const [mobileDisplayCount, setMobileDisplayCount] = useState(20);
  const sentinelRef = useRef<HTMLDivElement>(null);
  
  // 실제 데이터와 샘플 데이터 병합
  const { quotes: realQuotes, addQuote, currentUser, reviseQuote, updateQuote } = useData();
  
  // 디버깅: realQuotes 확인
  useEffect(() => {
    console.log("🔍 QuoteManagement - realQuotes 변경됨:", realQuotes.length, "개");
    console.log("🔍 realQuotes 내용:", realQuotes);
  }, [realQuotes]);
  
  // ID 중복 방지 및 고유 ID 보장
  const processedRealQuotes = realQuotes.map((q, index) => {
    const uniqueId = q.id && q.id.trim() !== '' ? q.id : `real-quote-${Date.now()}-${index}-${Math.random().toString(36).substr(2, 9)}`;
    
    return {
      id: uniqueId,
      quoteNumber: q.quoteNumber || "",
      registrationDate: q.registrationDate || q.quoteDate || "",
      client: q.client || q.customerName || "",
      site: q.site || q.projectName || "",
      manager: q.manager || q.author || "",
      contact: q.contact || q.clientContact || q.contactPhone || "",
      productCode: q.productCode || q.selectedProductId || "",
      quantity: q.quantity || 1,
      amount: q.amount || q.totalAmount || 0,
      status: q.status || "draft",
      currentRevision: q.currentRevision || 0,
      isFinal: q.isFinal || false,
      type: q.type || (q.productCategory === 'SCREEN' ? '스크린' : q.productCategory === 'STEEL' ? '철재' : '일반'),
      remarks: q.remarks || q.notes || q.memo || "",
    };
  });
  
  // ID 중복 제거
  const uniqueRealQuotes = processedRealQuotes.filter((quote, index, self) =>
    index === self.findIndex((q) => q.id === quote.id)
  );
  
  const allQuotes: Quote[] = [
    ...SAMPLE_QUOTES,
    ...uniqueRealQuotes,
  ];

  // 필터링 및 정렬
  const filteredQuotes = allQuotes
    .filter((quote) => {
      const searchLower = searchTerm.toLowerCase();
      const matchesSearch =
        !searchTerm ||
        quote.quoteNumber.toLowerCase().includes(searchLower) ||
        quote.client.toLowerCase().includes(searchLower) ||
        (quote.manager && quote.manager.toLowerCase().includes(searchLower)) ||
        (quote.productCode && quote.productCode.toLowerCase().includes(searchLower)) ||
        (quote.site && quote.site.toLowerCase().includes(searchLower));

      let matchesFilter = true;
      if (filterType === "initial") {
        matchesFilter = quote.currentRevision === 0 && !quote.isFinal && quote.status !== "converted";
      } else if (filterType === "revising") {
        matchesFilter = quote.currentRevision > 0 && !quote.isFinal && quote.status !== "converted";
      } else if (filterType === "final") {
        matchesFilter = quote.isFinal && quote.status !== "converted";
      } else if (filterType === "converted") {
        matchesFilter = quote.status === "converted";
      }

      return matchesSearch && matchesFilter;
    })
    .sort((a, b) => {
      return new Date(b.registrationDate).getTime() - new Date(a.registrationDate).getTime();
    });

  // 페이지네이션
  const totalPages = Math.ceil(filteredQuotes.length / itemsPerPage);
  const paginatedQuotes = filteredQuotes.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );
  
  // 모바일용 인피니티 스크롤 데이터
  const mobileQuotes = filteredQuotes.slice(0, mobileDisplayCount);
  
  // Intersection Observer를 이용한 인피니티 스크롤
  useEffect(() => {
    // 모바일/태블릿 환경(xl 미만)에서만 작동
    if (window.innerWidth >= 1280) return;
    
    const observer = new IntersectionObserver(
      (entries) => {
        // sentinel 요소가 화면에 보이고, 더 불러올 데이터가 있으면
        if (entries[0].isIntersecting && mobileDisplayCount < filteredQuotes.length) {
          setMobileDisplayCount(prev => Math.min(prev + 20, filteredQuotes.length));
        }
      },
      {
        threshold: 0.1, // 10%만 보여도 트리거
        rootMargin: '100px', // 하단 100px 전에 미리 로드
      }
    );
    
    if (sentinelRef.current) {
      observer.observe(sentinelRef.current);
    }
    
    return () => {
      observer.disconnect();
    };
  }, [mobileDisplayCount, filteredQuotes.length]);
  
  // 탭이나 검색어 변경 시 모바일 표시 개수 초기화
  useEffect(() => {
    setMobileDisplayCount(20);
  }, [searchTerm, filterType]);
  
  // 통계 계산
  const now = new Date();
  const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
  const startOfWeek = new Date(now);
  startOfWeek.setDate(now.getDate() - now.getDay()); // 이번 주 일요일

  // 이번 달 견적 금액
  const thisMonthQuotes = allQuotes.filter(q => 
    new Date(q.registrationDate) >= startOfMonth
  );
  const thisMonthAmount = thisMonthQuotes.reduce((sum, q) => sum + q.amount, 0);

  // 진행중 견적 금액 (status === "draft")
  const ongoingQuotes = allQuotes.filter(q => q.status === "draft");
  const ongoingAmount = ongoingQuotes.reduce((sum, q) => sum + q.amount, 0);

  // 이번 주 신규 견적
  const thisWeekQuotes = allQuotes.filter(q => 
    new Date(q.registrationDate) >= startOfWeek
  );

  // 이번 달 수주 전환율 (이번 달 등록된 견적 중 수주로 전환된 비율)
  const thisMonthConvertedCount = thisMonthQuotes.filter(q => q.status === "converted").length;
  const thisMonthConversionRate = thisMonthQuotes.length > 0 
    ? ((thisMonthConvertedCount / thisMonthQuotes.length) * 100).toFixed(1) 
    : "0.0";

  const stats = [
    {
      label: "이번 달 견적 금액",
      value: formatAmountManwon(thisMonthAmount),
      icon: Calculator,
      iconColor: "text-blue-600",
    },
    {
      label: "진행중 견적 금액",
      value: formatAmountManwon(ongoingAmount),
      icon: FileText,
      iconColor: "text-orange-600",
    },
    {
      label: "이번 주 신규 견적",
      value: `${thisWeekQuotes.length}건`,
      icon: Edit,
      iconColor: "text-green-600",
    },
    {
      label: "이번 달 수주 전환율",
      value: `${thisMonthConversionRate}%`,
      icon: CheckCircle,
      iconColor: "text-purple-600",
    },
  ];

  // 핸들러
  const handleView = (quote: Quote) => {
    const fullQuote = realQuotes.find((q) => q.id === quote.id);
    if (fullQuote) {
      setSelectedQuote(quote);
      setCurrentView("detail");
    } else {
      toast.info(`샘플 데이터는 상세보기를 지원하지 않습니다: ${quote.quoteNumber}`);
    }
  };

  const handleEdit = (quote: Quote) => {
    const fullQuote = realQuotes.find((q) => q.id === quote.id);
    if (fullQuote) {
      setSelectedQuote(quote);
      setCurrentView("edit");
    } else {
      toast.info(`샘플 데이터는 수정할 수 없습니다: ${quote.quoteNumber}`);
    }
  };

  const handleDelete = (quoteId: string) => {
    setDeleteTargetId(quoteId);
    setIsDeleteDialogOpen(true);
  };
  
  // 삭제 확인 후 실행
  const handleConfirmDelete = () => {
    if (deleteTargetId) {
      const quote = allQuotes.find((q) => q.id === deleteTargetId);
      // 여기서 실제 삭제 로직 구현
      toast.success(`견적이 삭제되었습니다${quote ? `: ${quote.quoteNumber}` : ""}`);
      setIsDeleteDialogOpen(false);
      setDeleteTargetId(null);
    }
  };

  const handleViewHistory = (quote: Quote) => {
    toast.info(`수정 이력: ${quote.quoteNumber} (${quote.currentRevision}차 수정)`);
  };

  const handleViewCalculation = (quote: Quote) => {
    setCalculationQuote(quote);
    setIsCalculationDialogOpen(true);
  };

  const handleFinalize = (quoteId: string) => {
    const quote = allQuotes.find((q) => q.id === quoteId);
    if (quote && confirm(`견적번호 ${quote.quoteNumber}을(를) 최종 확정하시겠습니까?`)) {
      toast.success("견적이 최종 확정되었습니다");
    }
  };

  // 체크박스 선택
  const toggleSelection = (id: string) => {
    const newSelection = new Set(selectedItems);
    if (newSelection.has(id)) {
      newSelection.delete(id);
    } else {
      newSelection.add(id);
    }
    setSelectedItems(newSelection);
  };

  const toggleSelectAll = () => {
    if (selectedItems.size === paginatedQuotes.length && paginatedQuotes.length > 0) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(paginatedQuotes.map((q) => q.id)));
    }
  };

  // 일괄 삭제
  const handleBulkDelete = () => {
    if (selectedItems.size === 0) {
      toast.error("삭제할 항목을 선택해주세요");
      return;
    }
    
    if (confirm(`선택한 ${selectedItems.size}개의 견적을 삭제하시겠습니까?`)) {
      // 여기서 실제 삭제 로직 구현
      toast.success(`${selectedItems.size}개의 견적이 삭제되었습니다`);
      setSelectedItems(new Set());
    }
  };

  // 상태 뱃지
  const getRevisionBadge = (quote: Quote) => {
    return getQuoteStatusBadge(quote);
  };

  // 탭 구성
  const tabs: TabOption[] = [
    {
      value: "all",
      label: "전체",
      count: allQuotes.length,
      color: "blue",
    },
    {
      value: "initial",
      label: "최초작성",
      count: allQuotes.filter((q) => q.currentRevision === 0 && !q.isFinal && q.status !== "converted").length,
      color: "gray",
    },
    {
      value: "revising",
      label: "수정중",
      count: allQuotes.filter((q) => q.currentRevision > 0 && !q.isFinal && q.status !== "converted").length,
      color: "orange",
    },
    {
      value: "final",
      label: "최종확정",
      count: allQuotes.filter((q) => q.isFinal && q.status !== "converted").length,
      color: "green",
    },
    {
      value: "converted",
      label: "수주전환",
      count: allQuotes.filter((q) => q.status === "converted").length,
      color: "purple",
    },
  ];

  // 테이블 컬럼 정의
  const tableColumns: TableColumn[] = [
    { key: "rowNumber", label: "번호", className: "px-4" },
    { key: "quoteNumber", label: "견적번호", className: "px-4" },
    { key: "registrationDate", label: "접수일", className: "px-4" },
    { key: "status", label: "상태", className: "px-4" },
    { key: "productName", label: "제품명", className: "px-4" },
    { key: "quantity", label: "수량", className: "px-4" },
    { key: "amount", label: "금액", className: "px-4" },
    { key: "client", label: "발주처", className: "px-4" },
    { key: "site", label: "현장명", className: "px-4" },
    { key: "manager", label: "담당자", className: "px-4" },
    { key: "remarks", label: "비고", className: "px-4" },
    { key: "actions", label: "작업", className: "px-4" },
  ];

  // 테이블 행 렌더링
  const renderTableRow = (quote: Quote, index: number, globalIndex: number) => {
    const itemId = quote.id;
    const isSelected = selectedItems.has(itemId);

    return (
      <TableRow 
        key={quote.id} 
        className={`cursor-pointer hover:bg-muted/50 ${isSelected ? "bg-blue-50" : ""}`}
        onClick={() => handleView(quote)}
      >
        <TableCell onClick={(e) => e.stopPropagation()} className="text-center">
          <Checkbox
            checked={isSelected}
            onCheckedChange={() => toggleSelection(itemId)}
          />
        </TableCell>
        <TableCell>{globalIndex}</TableCell>
        <TableCell>
          <code className="text-xs bg-gray-100 text-gray-700 px-2 py-1 rounded font-mono">
            {quote.quoteNumber || "-"}
          </code>
        </TableCell>
        <TableCell>{quote.registrationDate}</TableCell>
        <TableCell>{getRevisionBadge(quote)}</TableCell>
        <TableCell>{quote.productCode || "-"}</TableCell>
        <TableCell className="text-center">{quote.quantity}</TableCell>
        <TableCell className="text-right">{formatAmount(quote.amount)}</TableCell>
        <TableCell>{quote.client}</TableCell>
        <TableCell>
          <div className="flex flex-col gap-1">
            <span>{quote.site || "-"}</span>
            {quote.siteCode && (
              <code className="inline-block w-fit text-xs bg-gray-100 text-gray-700 px-1.5 py-0.5 rounded font-mono whitespace-nowrap">
                {quote.siteCode}
              </code>
            )}
          </div>
        </TableCell>
        <TableCell>{quote.manager || "-"}</TableCell>
        <TableCell>
          <div className="max-w-[200px] line-clamp-2 text-sm">
            {quote.remarks || "-"}
          </div>
        </TableCell>
        <TableCell onClick={(e) => e.stopPropagation()}>
          {isSelected && (
            <div className="flex gap-1">
              {quote.currentRevision > 0 && (
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => handleViewHistory(quote)}
                >
                  <History className="h-4 w-4" />
                </Button>
              )}
              <Button
                variant="ghost"
                size="sm"
                onClick={() => handleEdit(quote)}
              >
                <Edit className="h-4 w-4" />
              </Button>
              {!quote.isFinal && (
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => handleDelete(quote.id)}
                >
                  <Trash2 className="h-4 w-4 text-red-500" />
                </Button>
              )}
            </div>
          )}
        </TableCell>
      </TableRow>
    );
  };

  // 모바일 카드 렌더링
  const renderMobileCard = (quote: Quote, index: number, globalIndex: number, isSelected: boolean, onToggle: () => void) => {
    return (
      <ListMobileCard
        key={quote.id}
        id={quote.id}
        isSelected={isSelected}
        onToggleSelection={onToggle}
        onCardClick={() => handleView(quote)}
        headerBadges={
          <>
            <Badge variant="outline" className="bg-gray-100 text-gray-700 font-mono text-xs">
              #{globalIndex}
            </Badge>
            <code className="inline-block text-xs bg-gray-100 text-gray-700 px-2.5 py-0.5 rounded-md font-mono whitespace-nowrap">
              {quote.quoteNumber}
            </code>
          </>
        }
        title={quote.client}
        statusBadge={getRevisionBadge(quote)}
        infoGrid={
          <div className="grid grid-cols-2 gap-x-4 gap-y-3">
            <InfoField label="현장명" value={quote.site || "-"} />
            <InfoField label="현장코드" value={quote.siteCode || "-"} />
            <InfoField label="접수일" value={quote.registrationDate} />
            <InfoField label="담당자" value={quote.manager || "-"} />
            <InfoField label="제품명" value={quote.productCode || "-"} />
            <InfoField label="수량" value={`${quote.quantity}개`} />
            <InfoField label="총 금액" value={formatAmount(quote.amount)} valueClassName="text-green-600" />
          </div>
        }
        actions={
          isSelected ? (
            <div className="flex gap-2 flex-wrap">
              {quote.currentRevision > 0 && (
                <Button
                  variant="outline"
                  size="default"
                  className="flex-1 min-w-[100px] h-11"
                  onClick={(e) => {
                    e.stopPropagation();
                    handleViewHistory(quote);
                  }}
                >
                  <History className="h-4 w-4 mr-2" />
                  이력
                </Button>
              )}
              <Button
                variant="default"
                size="default"
                className="flex-1 min-w-[100px] h-11"
                onClick={(e) => {
                  e.stopPropagation();
                  handleEdit(quote);
                }}
              >
                <Edit className="h-4 w-4 mr-2" />
                수정
              </Button>
              {!quote.isFinal && (
                <Button
                  variant="outline"
                  size="default"
                  className="flex-1 min-w-[100px] h-11 border-red-200 text-red-600 hover:border-red-300 bg-[rgba(255,255,255,0)]"
                  onClick={(e) => {
                    e.stopPropagation();
                    handleDelete(quote.id);
                  }}
                >
                  <Trash2 className="h-4 w-4 mr-2" />
                  삭제
                </Button>
              )}
            </div>
          ) : undefined
        }
      />
    );
  };

  // 견적 등록 화면
  if (currentView === "create") {
    return (
      <div className="space-y-4">
        <QuoteManagement3Write 
          onSave={(data) => {
            const quoteToSave = {
              id: data.id || String(Date.now()),
              quoteNumber: data.quoteNumber,
              registrationDate: data.registrationDate,
              receiptDate: data.receiptDate,
              author: data.author,
              client: data.client,
              site: data.site,
              siteId: data.siteId,
              siteCode: data.siteCode,
              manager: data.manager,
              contact: data.contact,
              remarks: data.remarks,
              memo: data.memo,
              clientContact: data.clientContact,
              contactPhone: data.contactPhone,
              completionDate: data.completionDate,
              modelSelection: data.modelSelection,
              floors: data.floors,
              code: data.code,
              powderType: data.powderType,
              installType: data.installType,
              installLocation: data.installLocation,
              openSizeWidth: data.openSizeWidth,
              openSizeHeight: data.openSizeHeight,
              selectedProducts: data.selectedProducts,
              calculationRows: data.calculationRows,
              createdAt: data.createdAt,
              type: data.type,
              productCode: data.productCode,
              quantity: data.quantity,
              amount: data.amount,
              responseMethod: data.responseMethod,
              commitment: data.commitment,
              notes: data.notes,
              productCategory: data.productCategory,
              selectedProductId: data.selectedProductId,
              bomCalculations: data.bomCalculations,
              autoCalculationSettings: data.autoCalculationSettings,
              status: data.status || 'draft',
              currentRevision: data.currentRevision || 0,
              isFinal: data.isFinal || false,
              revisions: data.revisions || [],
            };
            
            console.log("💾 QuoteManagement - 저장할 견적 데이터:", quoteToSave);
            console.log("💾 BOM 계산 항목 수:", quoteToSave.bomCalculations?.length || 0);
            console.log("💾 자동 산출 설정:", quoteToSave.autoCalculationSettings);
            
            addQuote(quoteToSave);
            console.log("견적 저장:", quoteToSave);
            toast.success("견적이 저장되었습니다");
            setCurrentView("list");
          }}
          onCancel={() => setCurrentView("list")}
        />
      </div>
    );
  }

  // 견적 상세 보기 화면
  if (currentView === "detail" && selectedQuote) {
    const fullQuote = realQuotes.find((q) => q.id === selectedQuote.id);
    
    if (!fullQuote) {
      return (
        <QuoteDetailView
          quoteId={selectedQuote.id}
          onBack={() => {
            setCurrentView("list");
            setSelectedQuote(null);
          }}
          onEdit={() => {
            setCurrentView("edit");
          }}
          onCreateOrder={(quoteId) => {
            toast.success(`수주로 전환되었습니다: ${quoteId}`);
            setCurrentView("list");
            setSelectedQuote(null);
          }}
        />
      );
    }
    
    return (
      <QuoteManagement3Detail
        quote={fullQuote}
        onBack={() => {
          setCurrentView("list");
          setSelectedQuote(null);
        }}
        onEdit={() => {
          setCurrentView("edit");
        }}
        onConvertToOrder={(quote) => {
          toast.success(`견적이 수주로 전환되었습니다: ${quote.quoteNumber}`);
          // 수주 등록 화면으로 이동하는 로직 추가 가능
          setCurrentView("list");
          setSelectedQuote(null);
        }}
      />
    );
  }

  // 견적 수정 화면 표시
  if (currentView === "edit" && selectedQuote) {
    const fullQuote = realQuotes.find((q) => q.id === selectedQuote.id);
    
    return (
      <div className="space-y-4">
        <QuoteManagement3Write
          initialData={fullQuote}
          isEditMode={true}
          onSave={(data, isRevision, revisionReason) => {
            const quoteToSave = {
              id: data.id || String(Date.now()),
              quoteNumber: data.quoteNumber,
              registrationDate: data.registrationDate,
              receiptDate: data.receiptDate,
              author: data.author,
              client: data.client,
              site: data.site,
              siteId: data.siteId,
              siteCode: data.siteCode,
              manager: data.manager,
              contact: data.contact,
              remarks: data.remarks,
              memo: data.memo,
              clientContact: data.clientContact,
              contactPhone: data.contactPhone,
              completionDate: data.completionDate,
              modelSelection: data.modelSelection,
              floors: data.floors,
              code: data.code,
              powderType: data.powderType,
              installType: data.installType,
              installLocation: data.installLocation,
              openSizeWidth: data.openSizeWidth,
              openSizeHeight: data.openSizeHeight,
              selectedProducts: data.selectedProducts,
              calculationRows: data.calculationRows,
              createdAt: data.createdAt,
              type: data.type,
              productCode: data.productCode,
              quantity: data.quantity,
              amount: data.amount,
              responseMethod: data.responseMethod,
              commitment: data.commitment,
              notes: data.notes,
              productCategory: data.productCategory,
              selectedProductId: data.selectedProductId,
              bomCalculations: data.bomCalculations,
              autoCalculationSettings: data.autoCalculationSettings,
              status: data.status || 'draft',
              currentRevision: data.currentRevision || 0,
              isFinal: data.isFinal || false,
              revisions: data.revisions || [],
            };
            
            if (isRevision && revisionReason) {
              console.log("🔄 reviseQuote 호출 - 수정 이력 저장");
              reviseQuote(data.id, quoteToSave, revisionReason, currentUser?.name || '관리자');
              toast.success(`견적이 수정되었습니다 (수정 이력 저장됨)`, {
                description: revisionReason
              });
            } else {
              console.log("💾 updateQuote 호출 - 일반 업데이트");
              updateQuote(data.id, quoteToSave);
              toast.success("견적이 저장되었습니다");
            }
            
            setCurrentView("list");
            setSelectedQuote(null);
          }}
          onCancel={() => {
            setCurrentView("list");
            setSelectedQuote(null);
          }}
        />
      </div>
    );
  }

  // 목록 화면 - IntegratedListTemplateV2 사용
  return (
    <>
      <IntegratedListTemplateV2
        title="견적 목록"
        description="견적서 작성 및 관리"
        icon={FileText}
        headerActions={
          <Button onClick={() => setCurrentView("create")}>
            <FileText className="w-4 h-4 mr-2" />
            견적 등록
          </Button>
        }
        stats={stats}
        searchValue={searchTerm}
        onSearchChange={setSearchTerm}
        searchPlaceholder="견적번호, 발주처, 담당자, 제품명, 현장코드, 현장명 검색..."
        tabs={tabs}
        activeTab={filterType}
        onTabChange={(value) => {
          setFilterType(value);
          setCurrentPage(1);
        }}
        tableColumns={tableColumns}
        tableTitle={`${tabs.find(t => t.value === filterType)?.label || "전체"} (${filteredQuotes.length}개)`}
        data={paginatedQuotes}
        totalCount={filteredQuotes.length}
        allData={mobileQuotes}
        mobileDisplayCount={mobileDisplayCount}
        infinityScrollSentinelRef={sentinelRef}
        selectedItems={selectedItems}
        onToggleSelection={toggleSelection}
        onToggleSelectAll={toggleSelectAll}
        onBulkDelete={handleBulkDelete}
        getItemId={(quote) => quote.id}
        renderTableRow={renderTableRow}
        renderMobileCard={renderMobileCard}
        pagination={{
          currentPage,
          totalPages,
          totalItems: filteredQuotes.length,
          itemsPerPage,
          onPageChange: setCurrentPage,
        }}
      />

      {/* 산출내역서 다이얼로그 */}
      <StandardDialog
        open={isCalculationDialogOpen}
        onOpenChange={setIsCalculationDialogOpen}
        title="산출내역서"
        description={calculationQuote ? `견적번호: ${calculationQuote.quoteNumber} | 발주처: ${calculationQuote.client}` : ""}
        size="xl"
        footer={
          <Button onClick={() => setIsCalculationDialogOpen(false)}>
            닫기
          </Button>
        }
      >
        {calculationQuote && (
          <div className="space-y-6">
            {/* 기본 정보 */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 p-4 bg-muted/50 rounded-lg">
              <div>
                <p className="text-sm text-muted-foreground">견적번호</p>
                <p className="font-medium">{calculationQuote.quoteNumber}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">발주처</p>
                <p className="font-medium">{calculationQuote.client}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">현장명</p>
                <p className="font-medium">{calculationQuote.site || "-"}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">접수일</p>
                <p className="font-medium">{calculationQuote.registrationDate}</p>
              </div>
            </div>

            <Separator />

            {/* 산출 내역 테이블 */}
            <div>
              <h4 className="font-semibold mb-3 flex items-center gap-2">
                <Calculator className="w-5 h-5" />
                산출 내역
              </h4>
              <div className="border rounded-lg overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-[60px]">번호</TableHead>
                      <TableHead>품목명</TableHead>
                      <TableHead>규격</TableHead>
                      <TableHead className="text-center">수량</TableHead>
                      <TableHead className="text-right">단가</TableHead>
                      <TableHead className="text-right">공급가</TableHead>
                      <TableHead className="text-right">부가세</TableHead>
                      <TableHead className="text-right">합계</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    <TableRow>
                      <TableCell>1</TableCell>
                      <TableCell>{calculationQuote.type || "스크린"}</TableCell>
                      <TableCell>{calculationQuote.productCode || "-"}</TableCell>
                      <TableCell className="text-center">{calculationQuote.quantity}</TableCell>
                      <TableCell className="text-right">
                        {formatAmount(Math.floor(calculationQuote.amount / calculationQuote.quantity))}원
                      </TableCell>
                      <TableCell className="text-right">
                        {formatAmount(Math.floor(calculationQuote.amount / 1.1))}원
                      </TableCell>
                      <TableCell className="text-right">
                        {formatAmount(Math.floor(calculationQuote.amount - calculationQuote.amount / 1.1))}원
                      </TableCell>
                      <TableCell className="text-right font-medium">
                        {formatAmount(calculationQuote.amount)}원
                      </TableCell>
                    </TableRow>
                  </TableBody>
                </Table>
              </div>
            </div>

            {/* 합계 */}
            <div className="bg-muted/50 p-4 rounded-lg">
              <div className="flex justify-between items-center">
                <span className="font-semibold">총 금액</span>
                <span className="text-xl font-bold text-primary">
                  {formatAmount(calculationQuote.amount)}원
                </span>
              </div>
            </div>
          </div>
        )}
      </StandardDialog>

      {/* 삭제 확인 다이얼로그 */}
      <StandardDialog
        open={isDeleteDialogOpen}
        onOpenChange={setIsDeleteDialogOpen}
        title="견적 삭제 확인"
        description={
          deleteTargetId
            ? `견적번호: ${allQuotes.find((q) => q.id === deleteTargetId)?.quoteNumber || deleteTargetId}`
            : ""
        }
        size="sm"
        footer={
          <>
            <Button
              variant="outline"
              size="default"
              onClick={() => setIsDeleteDialogOpen(false)}
            >
              취소
            </Button>
            <Button
              variant="destructive"
              size="default"
              onClick={handleConfirmDelete}
            >
              삭제
            </Button>
          </>
        }
      >
        <p className="text-sm text-muted-foreground">
          이 견적을 삭제하시겠습니까? 삭제된 데이터는 복구할 수 없습니다.
        </p>
      </StandardDialog>
    </>
  );
}