/**
 * 기본 목록_데스크톱/태블릿/모바일 통합 템플릿 예제
 * 
 * ResponsiveListTemplate을 활용한 완전한 반응형 목록 페이지 예제입니다.
 * 품목관리를 기반으로 한 실제 사용 시나리오를 보여줍니다.
 */

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

// 샘플 데이터 타입
interface SampleItem {
  id: string;
  no: number;
  itemCode: string;
  itemName: string;
  itemType: "FG" | "PT" | "RM";
  category: string;
  unit: string;
  spec: string;
  status: "active" | "inactive";
  price: number;
}

// 샘플 데이터
const sampleData: SampleItem[] = [
  { id: "1", no: 1, itemCode: "FG-001", itemName: "스크린 셔터 (표준형)", itemType: "FG", category: "스크린", unit: "SET", spec: "2000x2000", status: "active", price: 450000 },
  { id: "2", no: 2, itemCode: "PT-001", itemName: "가이드레일 (벽면형)", itemType: "PT", category: "부품", unit: "EA", spec: "SUS 1.2T", status: "active", price: 35000 },
  { id: "3", no: 3, itemCode: "RM-001", itemName: "알루미늄 압출재", itemType: "RM", category: "원자재", unit: "M", spec: "6063-T5", status: "active", price: 8000 },
  { id: "4", no: 4, itemCode: "FG-002", itemName: "방화셔터 (중형)", itemType: "FG", category: "철재", unit: "SET", spec: "3000x3000", status: "active", price: 850000 },
  { id: "5", no: 5, itemCode: "PT-002", itemName: "케이스 전면부", itemType: "PT", category: "부품", unit: "EA", spec: "SUS 1.5T", status: "inactive", price: 45000 },
  { id: "6", no: 6, itemCode: "RM-002", itemName: "SUS 철판", itemType: "RM", category: "원자재", unit: "SHEET", spec: "1.2T", status: "active", price: 120000 },
  { id: "7", no: 7, itemCode: "FG-003", itemName: "스크린 셔터 (고급형)", itemType: "FG", category: "스크린", unit: "SET", spec: "2500x2500", status: "active", price: 620000 },
  { id: "8", no: 8, itemCode: "PT-003", itemName: "가이드레일 (측면형)", itemType: "PT", category: "부품", unit: "EA", spec: "SUS 1.2T", status: "active", price: 38000 },
];

export function BasicListUnifiedExample() {
  const [currentTab, setCurrentTab] = useState("all");
  const [searchValue, setSearchValue] = useState("");

  // 탭별 데이터 필터링
  const filteredData = sampleData.filter((item) => {
    // 탭 필터
    if (currentTab === "fg" && item.itemType !== "FG") return false;
    if (currentTab === "pt" && item.itemType !== "PT") return false;
    if (currentTab === "rm" && item.itemType !== "RM") return false;
    if (currentTab === "active" && item.status !== "active") return false;
    if (currentTab === "inactive" && item.status !== "inactive") return false;

    // 검색 필터
    if (searchValue) {
      const search = searchValue.toLowerCase();
      return (
        item.itemCode.toLowerCase().includes(search) ||
        item.itemName.toLowerCase().includes(search) ||
        item.category.toLowerCase().includes(search)
      );
    }

    return true;
  });

  // 통계 카드
  const stats: StatCardProps[] = [
    {
      label: "전체 품목",
      value: String(sampleData.length),
      icon: Package,
      trend: { value: 12, isPositive: true },
    },
    {
      label: "제품",
      value: String(sampleData.filter((i) => i.itemType === "FG").length),
      icon: Package,
    },
    {
      label: "부품",
      value: String(sampleData.filter((i) => i.itemType === "PT").length),
      icon: Package,
    },
    {
      label: "원자재",
      value: String(sampleData.filter((i) => i.itemType === "RM").length),
      icon: Package,
    },
  ];

  // 탭 구성
  const tabs: TabConfig[] = [
    { value: "all", label: "전체", count: sampleData.length, color: "blue" },
    { value: "fg", label: "제품", count: sampleData.filter((i) => i.itemType === "FG").length, color: "purple" },
    { value: "pt", label: "부품", count: sampleData.filter((i) => i.itemType === "PT").length, color: "orange" },
    { value: "rm", label: "원자재", count: sampleData.filter((i) => i.itemType === "RM").length, color: "cyan" },
    { value: "active", label: "활성", count: sampleData.filter((i) => i.status === "active").length, color: "green" },
    { value: "inactive", label: "비활성", count: sampleData.filter((i) => i.status === "inactive").length, color: "gray" },
  ];

  // 데스크톱 테이블 컬럼
  const columns: Column<SampleItem>[] = [
    {
      key: "no",
      label: "No",
      type: "text",
      width: "60px",
      render: (value, row, index) => (
        <Badge variant="outline" className="bg-gray-100 text-gray-700 font-mono">
          {filteredData.length - index}
        </Badge>
      ),
    },
    {
      key: "itemCode",
      label: "품목코드",
      type: "text",
      width: "150px",
      render: (value) => <span className="font-mono text-sm">{value}</span>,
    },
    {
      key: "itemName",
      label: "품목명",
      type: "text",
      render: (value) => <span className="font-semibold">{value}</span>,
    },
    {
      key: "itemType",
      label: "품목유형",
      type: "badge",
      width: "100px",
      render: (value) => {
        const typeMap = { FG: "제품", PT: "부품", RM: "원자재" };
        const colorMap = { FG: "default", PT: "secondary", RM: "outline" };
        return <Badge variant={colorMap[value] as any}>{typeMap[value]}</Badge>;
      },
    },
    {
      key: "category",
      label: "분류",
      type: "text",
      width: "120px",
    },
    {
      key: "unit",
      label: "단위",
      type: "badge",
      width: "80px",
      render: (value) => <Badge variant="secondary">{value}</Badge>,
    },
    {
      key: "spec",
      label: "규격",
      type: "text",
      width: "150px",
    },
    {
      key: "status",
      label: "상태",
      type: "badge",
      width: "80px",
      render: (value) => (
        <Badge variant={value === "active" ? "default" : "secondary"}>
          {value === "active" ? "활성" : "비활성"}
        </Badge>
      ),
    },
    {
      key: "price",
      label: "단가",
      type: "text",
      width: "120px",
      render: (value) => `₩${(value || 0).toLocaleString()}`,
    },
    {
      key: "id",
      label: "작업",
      type: "actions",
      width: "120px",
      render: (value) => (
        <div className="flex gap-1">
          <Button size="sm" variant="ghost">
            <Eye className="w-4 h-4" />
          </Button>
          <Button size="sm" variant="ghost">
            <Edit className="w-4 h-4" />
          </Button>
          <Button size="sm" variant="ghost">
            <Trash2 className="w-4 h-4" />
          </Button>
        </div>
      ),
    },
  ];

  // 모바일 카드 렌더러
  const renderMobileCard = createMobileCardRenderer<SampleItem>({
    getTitle: (item) => item.itemName,
    getSubtitle: (item) => item.itemCode,
    getBadge: (item) => {
      const typeMap = { FG: "제품", PT: "부품", RM: "원자재" };
      return { label: typeMap[item.itemType], variant: "default" };
    },
    getFields: (item) => [
      { label: "분류", value: item.category },
      { label: "단위", value: item.unit, badge: true, badgeVariant: "secondary" },
      { label: "규격", value: item.spec },
      { 
        label: "상태", 
        value: item.status === "active" ? "활성" : "비활성", 
        badge: true, 
        badgeVariant: item.status === "active" ? "default" : "secondary" 
      },
      { label: "단가", value: `₩${item.price.toLocaleString()}` },
    ],
    getActions: (item) => (
      <div className="flex gap-2">
        <Button size="sm" variant="outline" className="flex-1">
          <Eye className="w-4 h-4 mr-1" />
          상세
        </Button>
        <Button size="sm" variant="outline" className="flex-1">
          <Edit className="w-4 h-4 mr-1" />
          수정
        </Button>
        <Button size="sm" variant="outline" className="flex-1">
          <Trash2 className="w-4 h-4 mr-1" />
          삭제
        </Button>
      </div>
    ),
    getNumber: (item, index, total) => total - index,
  });

  return (
    <ResponsiveListTemplate
      title="품목관리 (통합 템플릿)"
      description="데스크톱/태블릿/모바일을 모두 지원하는 완전한 반응형 목록 템플릿 예제입니다"
      icon={Package}
      headerActions={
        <Button>
          <Plus className="w-4 h-4 mr-2" />
          품목 등록
        </Button>
      }
      stats={stats}
      searchValue={searchValue}
      onSearchChange={setSearchValue}
      searchPlaceholder="품목코드, 품목명, 분류로 검색..."
      tabs={tabs}
      currentTab={currentTab}
      onTabChange={setCurrentTab}
      data={filteredData}
      keyField="id"
      columns={columns}
      onRowClick={(row) => console.log("클릭:", row)}
      renderMobileCard={renderMobileCard}
      emptyMessage="검색 결과가 없습니다"
      maxWidth="full"
    />
  );
}