/**
 * 표준 페이지 템플릿 사용 예제
 * 
 * 이 파일은 List/Detail/Form 페이지를 표준 템플릿으로 구현하는 방법을 보여줍니다.
 * 품목관리를 기준으로 작성되었으며, 다른 모든 메뉴에서 동일하게 사용할 수 있습니다.
 * 
 * 사용법:
 * 1. List 페이지: ListPageTemplate 사용
 * 2. Detail 페이지: DetailViewTemplate 사용
 * 3. Form 페이지: FormPageTemplate 사용
 */

import { useState } from "react";
import {
  ListPageTemplate,
  DetailViewTemplate,
  FormPageTemplate,
} from "../templates";
import type { Column } from "../organisms/DataTable";
import {
  Package,
  Edit,
  Trash2,
  Copy,
  Plus,
  FileText,
  Settings,
  Archive,
  Layers,
  Clock,
} from "lucide-react";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Label } from "../ui/label";
import { Badge } from "../ui/badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "../ui/select";

// 예제 데이터 타입
interface ExampleItem {
  id: string;
  code: string;
  name: string;
  type: string;
  category: string;
  status: "active" | "inactive";
  price: number;
  stock: number;
  createdAt: string;
}

// 샘플 데이터
const sampleData: ExampleItem[] = [
  {
    id: "1",
    code: "ITEM-001",
    name: "알루미늄 프로파일",
    type: "원자재",
    category: "금속",
    status: "active",
    price: 15000,
    stock: 150,
    createdAt: "2025-01-15",
  },
  {
    id: "2",
    code: "ITEM-002",
    name: "스테인리스 파이프",
    type: "구매품",
    category: "금속",
    status: "active",
    price: 25000,
    stock: 80,
    createdAt: "2025-01-16",
  },
];

export function StandardPageExample() {
  const [pageMode, setPageMode] = useState<"list" | "detail" | "form">("list");
  const [selectedItem, setSelectedItem] = useState<ExampleItem | null>(null);
  const [searchValue, setSearchValue] = useState("");

  // ==================== 1. LIST PAGE ====================
  const ListPageExample = () => {
    const columns: Column<ExampleItem>[] = [
      {
        key: "code",
        label: "품목코드",
        sortable: true,
      },
      {
        key: "name",
        label: "품목명",
        sortable: true,
      },
      {
        key: "type",
        label: "품목유형",
        render: (row) => <Badge variant="outline">{row.type}</Badge>,
      },
      {
        key: "status",
        label: "상태",
        render: (row) => (
          <Badge variant={row.status === "active" ? "default" : "secondary"}>
            {row.status === "active" ? "활성" : "비활성"}
          </Badge>
        ),
      },
      {
        key: "price",
        label: "단가",
        align: "right",
        render: (row) => `₩${row.price.toLocaleString()}`,
      },
      {
        key: "stock",
        label: "재고",
        align: "right",
      },
      {
        key: "actions",
        label: "작업",
        align: "center",
        render: (row) => (
          <div className="flex items-center justify-center gap-1">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => {
                setSelectedItem(row);
                setPageMode("detail");
              }}
            >
              <FileText className="h-4 w-4" />
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => {
                setSelectedItem(row);
                setPageMode("form");
              }}
            >
              <Edit className="h-4 w-4" />
            </Button>
            <Button variant="ghost" size="sm">
              <Trash2 className="h-4 w-4 text-red-600" />
            </Button>
          </div>
        ),
      },
    ];

    return (
      <ListPageTemplate
        title="품목관리"
        description="품목 정보를 조회하고 관리합니다"
        icon={Package}
        actions={
          <Button onClick={() => setPageMode("form")}>
            <Plus className="h-4 w-4 mr-2" />
            품목 등록
          </Button>
        }
        stats={[
          {
            label: "전체 품목",
            value: sampleData.length,
            icon: Package,
            iconColor: "text-blue-600",
          },
          {
            label: "활성 품목",
            value: sampleData.filter((i) => i.status === "active").length,
            icon: Archive,
            iconColor: "text-green-600",
          },
          {
            label: "총 재고량",
            value: sampleData.reduce((sum, i) => sum + i.stock, 0),
            icon: Layers,
            iconColor: "text-purple-600",
          },
          {
            label: "평균 단가",
            value: `₩${Math.round(
              sampleData.reduce((sum, i) => sum + i.price, 0) /
                sampleData.length
            ).toLocaleString()}`,
            icon: Clock,
            iconColor: "text-orange-600",
          },
        ]}
        searchValue={searchValue}
        onSearchChange={setSearchValue}
        searchPlaceholder="품목코드, 품목명 검색"
        filterButton
        onFilterClick={() => console.log("필터 클릭")}
        data={sampleData}
        keyField="id"
        columns={columns}
        onRowClick={(row) => {
          setSelectedItem(row);
          setPageMode("detail");
        }}
        renderMobileCard={(item) => ({
          title: item.name,
          subtitle: item.code,
          badge: {
            label: item.status === "active" ? "활성" : "비활성",
            variant: item.status === "active" ? "default" : "secondary",
          },
          fields: [
            { label: "품목유형", value: item.type },
            { label: "카테고리", value: item.category },
            { label: "단가", value: `₩${item.price.toLocaleString()}` },
            { label: "재고", value: String(item.stock) },
          ],
          actions: [
            {
              label: "보기",
              onClick: () => {
                setSelectedItem(item);
                setPageMode("detail");
              },
            },
            {
              label: "수정",
              onClick: () => {
                setSelectedItem(item);
                setPageMode("form");
              },
            },
          ],
        })}
        emptyIcon={Package}
        emptyTitle="등록된 품목이 없습니다"
        emptyDescription="새로운 품목을 등록해주세요"
        emptyAction={{
          label: "품목 등록",
          onClick: () => setPageMode("form"),
        }}
      />
    );
  };

  // ==================== 2. DETAIL PAGE ====================
  const DetailPageExample = () => {
    if (!selectedItem) return null;

    return (
      <DetailViewTemplate
        title={selectedItem.name}
        description={`품목코드: ${selectedItem.code}`}
        icon={Package}
        badge={{
          label: selectedItem.status === "active" ? "활성" : "비활성",
          variant: selectedItem.status === "active" ? "default" : "secondary",
        }}
        onBack={() => setPageMode("list")}
        primaryActions={[
          {
            label: "수정",
            icon: Edit,
            onClick: () => setPageMode("form"),
            variant: "default",
          },
          {
            label: "복사",
            icon: Copy,
            onClick: () => console.log("복사"),
            variant: "outline",
          },
        ]}
        moreActions={[
          {
            label: "비활성화",
            icon: Archive,
            onClick: () => console.log("비활성화"),
          },
          {
            label: "삭제",
            icon: Trash2,
            onClick: () => console.log("삭제"),
            variant: "destructive",
            separator: true,
          },
        ]}
        sections={[
          {
            title: "기본 정보",
            icon: Package,
            columns: 2,
            fields: [
              { label: "품목코드", value: selectedItem.code },
              { label: "품목명", value: selectedItem.name },
              { label: "품목유형", value: selectedItem.type },
              { label: "카테고리", value: selectedItem.category },
              {
                label: "상태",
                value: selectedItem.status === "active" ? "활성" : "비활성",
                badge: {
                  label:
                    selectedItem.status === "active" ? "활성" : "비활성",
                  variant:
                    selectedItem.status === "active" ? "default" : "secondary",
                },
              },
              { label: "등록일", value: selectedItem.createdAt },
            ],
          },
          {
            title: "가격 및 재고 정보",
            icon: Settings,
            columns: 2,
            fields: [
              {
                label: "단가",
                value: `₩${selectedItem.price.toLocaleString()}`,
              },
              { label: "재고", value: `${selectedItem.stock} EA` },
            ],
          },
        ]}
        tabs={[
          {
            id: "bom",
            label: "BOM",
            icon: Layers,
            badge: 5,
            content: (
              <div className="p-4 bg-gray-50 rounded-lg">
                <p className="text-sm text-gray-600">BOM 정보가 표시됩니다</p>
              </div>
            ),
          },
          {
            id: "history",
            label: "변경이력",
            icon: Clock,
            badge: 3,
            content: (
              <div className="p-4 bg-gray-50 rounded-lg">
                <p className="text-sm text-gray-600">
                  변경 이력이 표시됩니다
                </p>
              </div>
            ),
          },
        ]}
      />
    );
  };

  // ==================== 3. FORM PAGE ====================
  const FormPageExample = () => {
    return (
      <FormPageTemplate
        title={selectedItem ? "품목 수정" : "품목 등록"}
        description={
          selectedItem
            ? `${selectedItem.code} 품목 정보를 수정합니다`
            : "새로운 품목을 등록합니다"
        }
        icon={Package}
        sections={[
          {
            title: "기본 정보",
            content: (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <Label>품목코드 *</Label>
                  <Input
                    placeholder="자동 생성"
                    defaultValue={selectedItem?.code}
                  />
                </div>
                <div>
                  <Label>품목명 *</Label>
                  <Input
                    placeholder="품목명 입력"
                    defaultValue={selectedItem?.name}
                  />
                </div>
                <div>
                  <Label>품목유형 *</Label>
                  <Select defaultValue={selectedItem?.type}>
                    <SelectTrigger>
                      <SelectValue placeholder="선택" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="원자재">원자재</SelectItem>
                      <SelectItem value="구매품">구매품</SelectItem>
                      <SelectItem value="반제품">반제품</SelectItem>
                      <SelectItem value="완제품">완제품</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>카테고리</Label>
                  <Input
                    placeholder="카테고리 입력"
                    defaultValue={selectedItem?.category}
                  />
                </div>
              </div>
            ),
          },
          {
            title: "가격 및 재고",
            content: (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <Label>단가</Label>
                  <Input
                    type="number"
                    placeholder="0"
                    defaultValue={selectedItem?.price}
                  />
                </div>
                <div>
                  <Label>재고</Label>
                  <Input
                    type="number"
                    placeholder="0"
                    defaultValue={selectedItem?.stock}
                  />
                </div>
              </div>
            ),
          },
        ]}
        onSave={() => {
          console.log("저장");
          setPageMode("list");
        }}
        onCancel={() => setPageMode("list")}
      />
    );
  };

  // 페이지 모드에 따라 렌더링
  return (
    <>
      {pageMode === "list" && <ListPageExample />}
      {pageMode === "detail" && <DetailPageExample />}
      {pageMode === "form" && <FormPageExample />}
    </>
  );
}
