/**
 * 견적관리 - 디자인 시스템 적용 예제
 * 
 * BasicDesktopListTemplate을 적용한 견적 관리 페이지입니다.
 * - 데스크톱: BasicDesktopListTemplate 템플릿
 * - 모바일: QuoteListTemplate 템플릿
 */

import { useState } from "react";
import { FileText, Plus, Edit, Eye, Trash2, CheckCircle, History, Calculator } from "lucide-react";
import { BasicDesktopListTemplate } from "./templates/BasicDesktopListTemplate";
import { QuoteListTemplate, QuoteListItem } from "./templates/QuoteListTemplate";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { useData } from "./contexts/DataContext";
import { TableAction } from "./molecules/TableActions";
import { Column } from "./organisms/DataTable";
import { toast } from "sonner@2.0.3";

// 샘플 견적 데이터
const SAMPLE_QUOTES: QuoteListItem[] = [
  {
    id: "SAMPLE-Q-001",
    quoteNumber: "Q2024-001",
    registrationDate: "2024-01-15",
    client: "ABC건설",
    site: "강남 오피스텔 현장",
    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: "판교 공장",
    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: "송도 아파트 현장",
    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: "분당 상가 현장",
    manager: "최지원",
    contact: "010-4567-8901",
    productCode: "STL-004",
    quantity: 8,
    amount: 12000000,
    status: "converted",
    currentRevision: 1,
    isFinal: true,
    type: "철재",
    remarks: "수주 전환 완료",
  },
];

export function QuoteManagement_DesignSystemExample() {
  const [searchTerm, setSearchTerm] = useState("");
  const [filterStatus, setFilterStatus] = useState("all");
  const [currentPage, setCurrentPage] = useState(1);

  // 실제 데이터와 샘플 데이터 병합
  const { quotes: realQuotes } = useData();
  const allQuotes: QuoteListItem[] = [
    ...SAMPLE_QUOTES,
    ...realQuotes.map((q, index) => ({
      id: q.id && q.id.trim() !== '' ? q.id : `real-quote-${Date.now()}-${index}-${Math.random().toString(36).substr(2, 9)}`,
      quoteNumber: q.quoteNumber || "",
      registrationDate: q.registrationDate || q.quoteDate || "",
      client: q.client || q.customerName || "",
      site: q.site || q.projectName,
      manager: q.manager,
      contact: q.contact,
      productCode: q.productCode,
      quantity: q.quantity,
      amount: q.amount || q.totalAmount || 0,
      status: q.status,
      currentRevision: q.currentRevision,
      isFinal: q.isFinal,
      type: q.type,
      remarks: q.remarks,
    })),
  ];

  // 필터링된 견적
  const filteredQuotes = allQuotes.filter((quote) => {
    const searchLower = searchTerm.toLowerCase();
    const matchesSearch =
      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 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;
  });

  // 통계 데이터
  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 handleView = (quote: QuoteListItem) => {
    toast.info(`상세: ${quote.quoteNumber}`);
  };

  const handleEdit = (quote: QuoteListItem) => {
    toast.info(`수정: ${quote.quoteNumber}`);
  };

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

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

  const handleViewCalculation = (quote: QuoteListItem) => {
    toast.info(`산출내역서: ${quote.quoteNumber}`);
  };

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

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

  // 상태 뱃지
  const getRevisionBadge = (quote: QuoteListItem) => {
    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>;
  };

  // DataTable용 컬럼 정의
  const tableColumns: Column<QuoteListItem>[] = [
    {
      key: "quoteNumber",
      label: "견적번호",
      type: "text",
      width: "150px",
      render: (value) => <span className="text-blue-600 font-medium">{value || "-"}</span>,
    },
    {
      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",
    },
    {
      key: "id",
      label: "작업",
      type: "actions",
      width: "180px",
      render: (_, row) => {
        const actions: TableAction[] = [
          ...(row.currentRevision || 0) > 0
            ? [
                {
                  label: "이력",
                  icon: History,
                  onClick: () => handleViewHistory(row),
                  variant: "ghost" as const,
                },
              ]
            : [],
          {
            label: "산출",
            icon: Calculator,
            onClick: () => handleViewCalculation(row),
            variant: "ghost" as const,
          },
          {
            label: "상세",
            icon: Eye,
            onClick: () => handleView(row),
            variant: "ghost" as const,
          },
          {
            label: "수정",
            icon: Edit,
            onClick: () => handleEdit(row),
            variant: "ghost" as const,
          },
          ...(!row.isFinal
            ? [
                {
                  label: "확정",
                  icon: CheckCircle,
                  onClick: () => handleFinalize(row.id),
                  variant: "ghost" as const,
                },
              ]
            : []),
          ...(!row.isFinal
            ? [
                {
                  label: "삭제",
                  icon: Trash2,
                  onClick: () => handleDelete(row.id),
                  variant: "ghost" as const,
                },
              ]
            : []),
        ];
        return actions;
      },
    },
  ];

  return (
    <>
      {/* 데스크톱: BasicDesktopListTemplate */}
      <div className="hidden md:block">
        <BasicDesktopListTemplate
          title="견적 관리 (디자인 시스템 예제)"
          description="아토믹 디자인 시스템을 적용한 견적 관리 페이지입니다"
          icon={FileText}
          headerActions={
            <Button onClick={() => toast.info("견적 등록 기능은 예제에서 비활성화되어 있습니다")}>
              <Plus className="w-4 h-4 mr-2" />
              견적 등록
            </Button>
          }
          stats={stats}
          data={filteredQuotes}
          columns={tableColumns}
          keyField="id"
          searchValue={searchTerm}
          onSearchChange={setSearchTerm}
          searchPlaceholder="견적번호, 발주처, 담당자, 제품코드, 현장명으로 검색..."
          onRowClick={handleView}
          emptyMessage={searchTerm ? "검색 결과가 없습니다" : "작성된 견적서가 없습니다"}
        />
      </div>

      {/* 모바일: QuoteListTemplate */}
      <div className="block md:hidden">
        <QuoteListTemplate
          quotes={filteredQuotes}
          searchValue={searchTerm}
          onSearchChange={setSearchTerm}
          filterStatus={filterStatus}
          onFilterChange={setFilterStatus}
          currentPage={currentPage}
          onPageChange={setCurrentPage}
          itemsPerPage={20}
          onQuoteClick={handleView}
          onEdit={handleEdit}
          onView={handleView}
          onDelete={handleDelete}
          onViewHistory={handleViewHistory}
          onViewCalculation={handleViewCalculation}
          onFinalize={handleFinalize}
          showActions={true}
        />
      </div>
    </>
  );
}