/**
 * 견적 관리 목록 - 기본 목록 템플릿 적용
 * BasicListTemplate을 사용한 표준화된 견적 목록 화면
 */

import { useState } from "react";
import { FileText, Plus, Edit, Eye, Trash2, CheckCircle, History, Calculator, FileCheck } from "lucide-react";
import { BasicListTemplate } from "./templates/BasicListTemplate";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import { QuoteData } from "./QuoteManagement3Write";
import { toast } from "sonner@2.0.3";

export function QuoteManagement3List_BasicTemplate({
  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 [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 10;

  // 내림차순 정렬 (최신 견적이 먼저)
  const sortedQuotes = [...quotes].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 totalPages = Math.ceil(sortedQuotes.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const paginatedQuotes = sortedQuotes.slice(startIndex, startIndex + itemsPerPage);

  // 탭 정의
  const tabs = [
    {
      value: "all",
      label: "전체",
      count: quotes.length,
    },
    {
      value: "draft",
      label: "작성중",
      count: quotes.filter((q) => !q.isFinal && q.status !== "converted").length,
      color: "text-orange-600",
    },
    {
      value: "final",
      label: "최종 확정",
      count: quotes.filter((q) => q.isFinal).length,
      color: "text-green-600",
    },
    {
      value: "converted",
      label: "수주 전환",
      count: quotes.filter((q) => q.status === "converted").length,
      color: "text-blue-600",
    },
  ];

  // 테이블 컬럼 정의
  const columns = [
    { key: "quoteNumber", label: "견적번호", width: "150px" },
    { key: "client", label: "거래처", width: "150px" },
    { key: "site", label: "현장명" },
    { key: "productCategory", label: "제품 카테고리", width: "120px", align: "center" as const },
    { key: "totalPrice", label: "견적 금액", width: "120px", align: "right" as const },
    { key: "registrationDate", label: "등록일", width: "100px", align: "center" as const },
    { key: "status", label: "상태", width: "100px", align: "center" as const },
  ];

  // 상태 뱃지 렌더링
  const renderStatusBadge = (quote: QuoteData) => {
    if (quote.status === "converted") {
      return <Badge className="bg-blue-500">수주전환</Badge>;
    }
    if (quote.isFinal) {
      return (
        <Badge className="bg-green-500">
          <CheckCircle className="h-3 w-3 mr-1" />
          최종확정
        </Badge>
      );
    }
    if ((quote.currentRevision || 0) > 0) {
      return (
        <Badge variant="secondary">
          <History className="h-3 w-3 mr-1" />
          Rev.{quote.currentRevision}
        </Badge>
      );
    }
    return <Badge variant="outline">작성중</Badge>;
  };

  // 제품 카테고리 뱃지
  const renderCategoryBadge = (category?: string) => {
    if (category === "SCREEN") {
      return <Badge variant="outline" className="bg-blue-50 text-blue-700">스크린</Badge>;
    }
    if (category === "STEEL") {
      return <Badge variant="outline" className="bg-gray-50 text-gray-700">철재</Badge>;
    }
    return <Badge variant="outline">-</Badge>;
  };

  // 셀 커스텀 렌더러
  const renderCell = (quote: QuoteData, column: { key: string; label: string }) => {
    switch (column.key) {
      case "quoteNumber":
        return (
          <code className="text-sm bg-blue-50 text-blue-700 px-2 py-1 rounded font-mono">
            {quote.quoteNumber}
          </code>
        );
      
      case "client":
        return <span className="font-medium">{quote.client || "-"}</span>;
      
      case "site":
        return quote.site || "-";
      
      case "productCategory":
        return renderCategoryBadge(quote.productCategory);
      
      case "totalPrice":
        return (
          <span className="font-medium">
            {quote.totalPrice ? `${quote.totalPrice.toLocaleString()}원` : "-"}
          </span>
        );
      
      case "registrationDate":
        return quote.registrationDate || "-";
      
      case "status":
        return renderStatusBadge(quote);
      
      default:
        return (quote as any)[column.key] || "-";
    }
  };

  // 모바일 카드 렌더러
  const renderMobileCard = (quote: QuoteData, index: number) => (
    <div className="border rounded-lg p-4 space-y-3 bg-white hover:bg-muted/50 transition-colors shadow-sm">
      <div className="flex items-start gap-3">
        <div className="flex-1 min-w-0 space-y-3">
          {/* 번호 + 견적번호 */}
          <div className="flex items-center gap-2 flex-wrap">
            <Badge variant="outline" className="bg-gray-100 text-gray-700 font-mono text-xs">
              #{startIndex + index + 1}
            </Badge>
            <code className="text-xs bg-blue-50 text-blue-700 px-2 py-1 rounded font-mono">
              {quote.quoteNumber}
            </code>
            {renderStatusBadge(quote)}
          </div>

          {/* 거래처/현장 */}
          <div>
            <div className="font-semibold text-base">{quote.client}</div>
            <div className="text-sm text-muted-foreground">{quote.site}</div>
          </div>

          {/* 제품 카테고리 */}
          <div>
            <span className="text-muted-foreground text-xs">제품 카테고리</span>
            <div className="mt-1">
              {renderCategoryBadge(quote.productCategory)}
            </div>
          </div>

          {/* 견적 금액 */}
          <div>
            <span className="text-muted-foreground text-xs">견적 금액</span>
            <div className="font-semibold mt-1">
              {quote.totalPrice ? `${quote.totalPrice.toLocaleString()}원` : "-"}
            </div>
          </div>

          {/* 등록일 */}
          <div>
            <span className="text-muted-foreground text-xs">등록일</span>
            <div className="mt-1">{quote.registrationDate || "-"}</div>
          </div>

          {/* 액션 버튼 */}
          <div className="flex gap-2 pt-2 border-t">
            {onView && (
              <Button
                variant="outline"
                size="sm"
                onClick={() => onView(quote.id)}
                className="flex-1"
              >
                <Eye className="h-4 w-4 mr-1" />
                보기
              </Button>
            )}
            <Button
              variant="outline"
              size="sm"
              onClick={() => onEdit(quote)}
              className="flex-1"
            >
              <Edit className="h-4 w-4 mr-1" />
              수정
            </Button>
            {!quote.isFinal && onFinalize && (
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  if (confirm("최종 확정하시겠습니까?")) {
                    onFinalize(quote.id);
                  }
                }}
                className="flex-1"
              >
                <FileCheck className="h-4 w-4 mr-1" />
                확정
              </Button>
            )}
            <Button
              variant="outline"
              size="sm"
              onClick={() => {
                if (confirm("삭제하시겠습니까?")) {
                  onDelete(quote.id);
                }
              }}
              className="flex-1"
            >
              <Trash2 className="h-4 w-4 mr-1 text-red-500" />
              삭제
            </Button>
          </div>
        </div>
      </div>
    </div>
  );

  // 행 클릭 핸들러
  const handleRowClick = (quote: QuoteData) => {
    if (onView) {
      onView(quote.id);
    }
  };

  return (
    <BasicListTemplate
      title="견적관리"
      subtitle="견적서를 작성하고 관리합니다"
      tabs={tabs}
      columns={columns}
      data={paginatedQuotes}
      selectable={false}
      selectedIds={selectedIds}
      onSelectionChange={setSelectedIds}
      onAdd={onNew}
      onEdit={onEdit}
      onDelete={(quote) => {
        if (confirm("삭제하시겠습니까?")) {
          onDelete(quote.id);
        }
      }}
      onRowClick={handleRowClick}
      searchable={false}
      filterable={false}
      pagination={{
        currentPage,
        totalPages,
        onPageChange: setCurrentPage,
      }}
      renderCell={renderCell}
      renderMobileCard={renderMobileCard}
    />
  );
}
