/**
 * 반응형 목록 템플릿 사용 예제
 * 
 * ResponsiveListTemplate을 사용한 품목관리 스타일의 목록 페이지 예제입니다.
 */

import { useState } from "react";
import { Package, Edit, Eye, Trash2 } from "lucide-react";
import { ResponsiveListTemplate, TabConfig, createMobileCardRenderer } from "./ResponsiveListTemplate";
import { Column } from "../organisms/DataTable";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { toast } from "sonner@2.0.3";

// 예제 데이터 타입
interface ExampleItem {
  id: string;
  itemCode: string;
  itemName: string;
  itemType: "FG" | "PT" | "SM" | "RM" | "CS";
  specification?: string;
  material?: string;
  status: "active" | "inactive";
}

// 샘플 데이터
const SAMPLE_ITEMS: ExampleItem[] = [
  {
    id: "1",
    itemCode: "FG-001",
    itemName: "방화셔터 3000x3000",
    itemType: "FG",
    specification: "3000x3000",
    material: "강판",
    status: "active",
  },
  {
    id: "2",
    itemCode: "PT-001",
    itemName: "가이드레일",
    itemType: "PT",
    specification: "L=3000",
    material: "알루미늄",
    status: "active",
  },
  {
    id: "3",
    itemCode: "SM-001",
    itemName: "볼트 M8x20",
    itemType: "SM",
    specification: "M8x20",
    material: "스테인레스",
    status: "active",
  },
  {
    id: "4",
    itemCode: "RM-001",
    itemName: "알루미늄 판재",
    itemType: "RM",
    specification: "1000x2000x2.0T",
    material: "알루미늄",
    status: "active",
  },
  {
    id: "5",
    itemCode: "CS-001",
    itemName: "윤활유",
    itemType: "CS",
    specification: "1L",
    material: "-",
    status: "active",
  },
];

export function ResponsiveListTemplateExample() {
  const [searchTerm, setSearchTerm] = useState("");
  const [filterType, setFilterType] = useState("all");
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());

  // 품목 유형 라벨
  const getItemTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      FG: "제품",
      PT: "부품",
      SM: "부자재",
      RM: "원자재",
      CS: "소모품",
    };
    return labels[type] || type;
  };

  // 필터링된 데이터
  const filteredItems = SAMPLE_ITEMS.filter((item) => {
    const matchesSearch =
      !searchTerm ||
      item.itemCode.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.itemName.toLowerCase().includes(searchTerm.toLowerCase());

    const matchesType = filterType === "all" || item.itemType === filterType;

    return matchesSearch && matchesType;
  });

  // 통계
  const stats = [
    {
      label: "전체 품목",
      value: SAMPLE_ITEMS.length,
      icon: Package,
      iconColor: "text-blue-600",
    },
    {
      label: "제품",
      value: SAMPLE_ITEMS.filter((i) => i.itemType === "FG").length,
      icon: Package,
      iconColor: "text-purple-600",
    },
    {
      label: "부품",
      value: SAMPLE_ITEMS.filter((i) => i.itemType === "PT").length,
      icon: Package,
      iconColor: "text-orange-600",
    },
    {
      label: "활성",
      value: SAMPLE_ITEMS.filter((i) => i.status === "active").length,
      icon: Package,
      iconColor: "text-green-600",
    },
  ];

  // 탭 구성
  const tabs: TabConfig[] = [
    { value: "all", label: "전체", count: SAMPLE_ITEMS.length, color: "blue" },
    { value: "FG", label: "제품", count: SAMPLE_ITEMS.filter((i) => i.itemType === "FG").length, color: "purple" },
    { value: "PT", label: "부품", count: SAMPLE_ITEMS.filter((i) => i.itemType === "PT").length, color: "orange" },
    { value: "SM", label: "부자재", count: SAMPLE_ITEMS.filter((i) => i.itemType === "SM").length, color: "cyan" },
    { value: "RM", label: "원자재", count: SAMPLE_ITEMS.filter((i) => i.itemType === "RM").length, color: "green" },
    { value: "CS", label: "소모품", count: SAMPLE_ITEMS.filter((i) => i.itemType === "CS").length, color: "gray" },
  ];

  // 데스크톱 테이블 컬럼
  const columns: Column<ExampleItem>[] = [
    {
      key: "itemCode",
      label: "품목코드",
      type: "text",
      width: "150px",
      render: (value) => <code className="text-blue-600 font-mono text-sm">{value}</code>,
    },
    {
      key: "itemName",
      label: "품목명",
      type: "text",
      minWidth: "200px",
    },
    {
      key: "itemType",
      label: "유형",
      type: "custom",
      width: "100px",
      render: (value) => {
        const colorMap: Record<string, string> = {
          FG: "bg-purple-100 text-purple-800 border-purple-300",
          PT: "bg-orange-100 text-orange-800 border-orange-300",
          SM: "bg-cyan-100 text-cyan-800 border-cyan-300",
          RM: "bg-green-100 text-green-800 border-green-300",
          CS: "bg-gray-100 text-gray-800 border-gray-300",
        };
        return (
          <Badge className={colorMap[value as string] || ""}>
            {getItemTypeLabel(value as string)}
          </Badge>
        );
      },
    },
    {
      key: "specification",
      label: "규격",
      type: "text",
      width: "150px",
      render: (value) => value || "-",
    },
    {
      key: "material",
      label: "재질",
      type: "text",
      width: "120px",
      render: (value) => value || "-",
    },
    {
      key: "status",
      label: "상태",
      type: "custom",
      width: "100px",
      render: (value) => (
        <Badge variant={value === "active" ? "default" : "secondary"}>
          {value === "active" ? "활성" : "비활성"}
        </Badge>
      ),
    },
    {
      key: "id",
      label: "작업",
      type: "actions",
      width: "150px",
      render: (_, row) => [
        {
          label: "상세",
          icon: Eye,
          onClick: () => toast.info(`${row.itemName} 상세`),
          variant: "ghost" as const,
        },
        {
          label: "수정",
          icon: Edit,
          onClick: () => toast.info(`${row.itemName} 수정`),
          variant: "ghost" as const,
        },
        {
          label: "삭제",
          icon: Trash2,
          onClick: () => toast.info(`${row.itemName} 삭제`),
          variant: "ghost" as const,
        },
      ],
    },
  ];

  // 모바일 카드 렌더러
  const renderMobileCard = createMobileCardRenderer<ExampleItem>({
    getNumber: (item, index, total) => total - index,
    getTitle: (item) => item.itemName,
    getSubtitle: (item) => item.itemCode,
    getBadge: (item) => ({
      label: getItemTypeLabel(item.itemType),
      variant: "outline",
    }),
    getFields: (item) => [
      { label: "규격", value: item.specification || "-" },
      { label: "재질", value: item.material || "-" },
      {
        label: "상태",
        value: item.status === "active" ? "활성" : "비활성",
        badge: true,
        badgeVariant: item.status === "active" ? "default" : "secondary",
      },
    ],
    getActions: (item) => (
      <div className="flex gap-2">
        <Button size="sm" variant="outline" onClick={() => toast.info(`${item.itemName} 상세`)}>
          <Eye className="w-4 h-4 mr-1" />
          상세
        </Button>
        <Button size="sm" variant="outline" onClick={() => toast.info(`${item.itemName} 수정`)}>
          <Edit className="w-4 h-4 mr-1" />
          수정
        </Button>
      </div>
    ),
    selectable: true,
    selectedIds,
    onToggleSelection: (id) => {
      const newSelected = new Set(selectedIds);
      if (newSelected.has(id)) {
        newSelected.delete(id);
      } else {
        newSelected.add(id);
      }
      setSelectedIds(newSelected);
    },
  });

  return (
    <ResponsiveListTemplate
      title="품목 관리 (반응형 템플릿 예제)"
      description="데스크톱/태블릿/모바일 모두 지원하는 목록 템플릿"
      icon={Package}
      headerActions={
        <Button onClick={() => toast.info("품목 등록")}>
          <Package className="w-4 h-4 mr-2" />
          품목 등록
        </Button>
      }
      stats={stats}
      searchValue={searchTerm}
      onSearchChange={setSearchTerm}
      searchPlaceholder="품목코드, 품목명 검색..."
      tabs={tabs}
      currentTab={filterType}
      onTabChange={setFilterType}
      data={filteredItems}
      keyField="id"
      columns={columns}
      onRowClick={(item) => toast.info(`${item.itemName} 클릭`)}
      renderMobileCard={renderMobileCard}
      selectable={true}
      selectedIds={selectedIds}
      onToggleSelection={(id) => {
        const newSelected = new Set(selectedIds);
        if (newSelected.has(id)) {
          newSelected.delete(id);
        } else {
          newSelected.add(id);
        }
        setSelectedIds(newSelected);
      }}
      cardTitle={(currentTab, count) => {
        const tabConfig = tabs.find((t) => t.value === currentTab);
        return `${tabConfig?.label || "목록"} (${count}개)`;
      }}
      emptyMessage="품목이 없습니다"
    />
  );
}
