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

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

// 견적 타입
interface Quote {
  id: string;
  quoteNumber: string;
  registrationDate: string;
  client: string;
  site?: 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: "강남 오피스텔 현장",
    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: "수주 전환 완료",
  },
  {
    id: "SAMPLE-Q-005",
    quoteNumber: "Q2024-005",
    registrationDate: "2024-01-19",
    client: "JKL개발",
    site: "용산 오피스빌딩",
    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 { quotes: realQuotes } = useData();
  const allQuotes: Quote[] = [
    ...SAMPLE_QUOTES,
    ...realQuotes.map((q) => ({
      id: q.id,
      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 =
      !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;
  });

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

  const handleEdit = (quote: Quote) => {
    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: Quote) => {
    toast.info(`수정 이력: ${quote.quoteNumber} (${quote.currentRevision}차 수정)`);
  };

  const handleViewCalculation = (quote: Quote) => {
    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: Quote) => {
    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) {
      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>
    );
  };

  // 탭 구성
  const tabs: TabConfig[] = [
    {
      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",
    },
  ];

  // DataTable용 컬럼 정의
  const tableColumns: Column<Quote>[] = [
    {
      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
            ? [
                {
                  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;
      },
    },
  ];

  // 모바일 카드 렌더러
  const renderMobileCard = createMobileCardRenderer<Quote>({
    getTitle: (quote) => quote.client,
    getSubtitle: (quote) => quote.quoteNumber,
    getBadge: (quote) => {
      if (quote.status === "converted") {
        return { label: "수주전환", variant: "default" };
      }
      if (quote.isFinal) {
        return { label: "최종확정", variant: "default" };
      }
      if (quote.currentRevision > 0) {
        return { label: `${quote.currentRevision}차 수정`, variant: "secondary" };
      }
      return { label: "최초작성", variant: "outline" };
    },
    getFields: (quote) => [
      { label: "접수일", value: quote.registrationDate },
      { label: "현장명", value: quote.site || "-" },
      { label: "담당자", value: quote.manager || "-" },
      { label: "제품코드", value: quote.productCode || "-" },
      { label: "수량", value: String(quote.quantity) },
      { label: "금액", value: `${formatAmount(quote.amount)}원` },
    ],
    getActions: (quote) => (
      <div className="flex gap-2 flex-wrap">
        {quote.currentRevision > 0 && (
          <Button size="sm" variant="outline" onClick={() => handleViewHistory(quote)}>
            <History className="w-4 h-4 mr-1" />
            이력
          </Button>
        )}
        <Button size="sm" variant="outline" onClick={() => handleViewCalculation(quote)}>
          <Calculator className="w-4 h-4 mr-1" />
          산출
        </Button>
        <Button size="sm" variant="outline" onClick={() => handleView(quote)}>
          <Eye className="w-4 h-4 mr-1" />
          상세
        </Button>
        <Button size="sm" variant="outline" onClick={() => handleEdit(quote)}>
          <Edit className="w-4 h-4 mr-1" />
          수정
        </Button>
        {!quote.isFinal && (
          <>
            <Button size="sm" variant="outline" onClick={() => handleFinalize(quote.id)}>
              <CheckCircle className="w-4 h-4 mr-1" />
              확정
            </Button>
            <Button size="sm" variant="outline" onClick={() => handleDelete(quote.id)}>
              <Trash2 className="w-4 h-4 mr-1" />
              삭제
            </Button>
          </>
        )}
      </div>
    ),
  });

  return (
    <ResponsiveListTemplate
      title="견적 관리"
      description="견적서 작성 및 관리"
      icon={FileText}
      headerActions={
        <Button onClick={() => toast.info("견적 등록")}>
          <FileText className="w-4 h-4 mr-2" />
          견적 등록
        </Button>
      }
      stats={stats}
      searchValue={searchTerm}
      onSearchChange={setSearchTerm}
      searchPlaceholder="견적번호, 발주처, 담당자, 제품코드, 현장명 검색..."
      tabs={tabs}
      currentTab={filterType}
      onTabChange={setFilterType}
      data={filteredQuotes}
      keyField="id"
      columns={tableColumns}
      onRowClick={(quote) => handleView(quote)}
      renderMobileCard={renderMobileCard}
      cardTitle={(currentTab, count) => {
        const tabConfig = tabs.find((t) => t.value === currentTab);
        return `${tabConfig?.label || "목록"} (${count}개)`;
      }}
      emptyMessage="견적이 없습니다"
    />
  );
}
