/**
 * 통합 폼 템플릿 V2 사용 예시
 * 
 * 품목관리 상세 정보 페이지를 기반으로 한 템플릿 사용 예제
 */

import { useState } from "react";
import { Package, FileText, Layers, Image as ImageIcon, History, Save } from "lucide-react";
import {
  IntegratedFormTemplateV2,
  DetailSection,
  InfoGrid,
  InfoField,
  BOMTable,
  ImageGallery,
  StatusBadge,
  ActionButton,
  type BOMItem,
  type ImageItem,
  type Tab
} from "../templates/IntegratedFormTemplateV2";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { toast } from "sonner@2.0.3";

export function IntegratedFormTemplateV2Example() {
  const [itemData] = useState({
    itemCode: "KQTS01",
    itemName: "방화문 KFD-001",
    itemType: "FG",
    specification: "1500x2000",
    unit: "EA",
    status: "active",
    material: "SUS304 1.2T",
    finishing: "아노다이징",
    safetyStock: 10,
    currentStock: 25,
    version: 3,
    createdBy: "김영희",
    createdAt: "2025-01-15"
  });

  // BOM 데이터
  const bomItems: BOMItem[] = [
    {
      id: "1",
      no: 1,
      itemCode: "GR-R-001",
      itemName: "가이드레일(벽면형)",
      specification: "2438mm",
      quantity: 2,
      unit: "EA",
      material: "SUS304 1.2T",
      badges: [
        <StatusBadge key="bending" status="절곡품" colorScheme="purple" />
      ],
      expandedContent: (
        <div className="space-y-3">
          <div className="flex items-center gap-2">
            <StatusBadge status="절곡 전개도 정보" colorScheme="purple" />
          </div>
          <div className="text-sm text-muted-foreground">
            전개도 이미지 및 연신율 상세 정보가 여기에 표시됩니다.
          </div>
        </div>
      )
    },
    {
      id: "2",
      no: 2,
      itemCode: "CS-F-001",
      itemName: "케이스 전면부",
      specification: "1500x300",
      quantity: 1,
      unit: "EA",
      finishing: "무도장",
      badges: [
        <StatusBadge key="assembly" status="조립품" colorScheme="blue" />,
        <Badge key="bom" variant="outline" className="bg-blue-50 text-blue-700 text-xs">
          BOM 3개
        </Badge>
      ]
    },
    {
      id: "3",
      no: 3,
      itemCode: "SL-001",
      itemName: "슬랫(방화)",
      specification: "1400x100",
      quantity: 15,
      unit: "EA",
      material: "EGI 1.6T"
    }
  ];

  // 이미지 갤러리 데이터
  const images: ImageItem[] = [
    {
      id: "1",
      url: "https://images.unsplash.com/photo-1586023492125-27b2c045efd7?w=400",
      alt: "제품 전면",
      caption: "제품 전면"
    },
    {
      id: "2",
      url: "https://images.unsplash.com/photo-1600607687939-ce8a6c25118c?w=400",
      alt: "제품 측면",
      caption: "제품 측면"
    },
    {
      id: "3",
      url: "https://images.unsplash.com/photo-1600566753190-17f0baa2a6c3?w=400",
      alt: "전개도",
      caption: "절곡 전개도"
    }
  ];

  // 탭 구성
  const tabs: Tab[] = [
    {
      value: "basic",
      label: "기본정보",
      icon: FileText,
      content: (
        <div className="space-y-6">
          {/* 기본 정보 섹션 */}
          <DetailSection
            icon={Package}
            title="기본 정보"
            badge={<StatusBadge status="필수" colorScheme="red" />}
          >
            <InfoGrid columns={3}>
              <InfoField 
                label="품목코드" 
                value={itemData.itemCode} 
                mono 
                required
                badge={<Badge variant="outline" className="bg-blue-50 text-blue-700">자동생성</Badge>}
              />
              <InfoField 
                label="품목명" 
                value={itemData.itemName} 
                required
              />
              <InfoField 
                label="품목유형" 
                value="제품 (FG)"
                badge={<StatusBadge status="제품" colorScheme="purple" />}
              />
              <InfoField 
                label="규격" 
                value={itemData.specification}
              />
              <InfoField 
                label="단위" 
                value={itemData.unit}
              />
              <InfoField 
                label="품목상태" 
                value="사용중"
                badge={<StatusBadge status="사용중" colorScheme="green" />}
              />
            </InfoGrid>
          </DetailSection>

          {/* 재질 및 마감 정보 */}
          <DetailSection
            icon={Layers}
            title="재질 및 마감 정보"
          >
            <InfoGrid columns={2}>
              <InfoField 
                label="재질" 
                value={itemData.material}
                badge={<StatusBadge status="SUS304" colorScheme="green" />}
              />
              <InfoField 
                label="마감" 
                value={itemData.finishing}
                badge={<StatusBadge status="아노다이징" colorScheme="blue" />}
              />
            </InfoGrid>
          </DetailSection>

          {/* 재고 정보 */}
          <DetailSection
            icon={Package}
            title="재고 정보"
          >
            <InfoGrid columns={2}>
              <InfoField 
                label="안전재고" 
                value={`${itemData.safetyStock} ${itemData.unit}`}
              />
              <InfoField 
                label="현재고" 
                value={`${itemData.currentStock} ${itemData.unit}`}
                badge={
                  itemData.currentStock > itemData.safetyStock ? (
                    <StatusBadge status="충분" colorScheme="green" />
                  ) : (
                    <StatusBadge status="부족" colorScheme="red" />
                  )
                }
              />
            </InfoGrid>
          </DetailSection>
        </div>
      )
    },
    {
      value: "bom",
      label: "BOM",
      icon: Layers,
      count: bomItems.length,
      content: (
        <DetailSection
          icon={Package}
          title="부품 구성 (BOM)"
          badge={<Badge variant="outline" className="bg-blue-50 text-blue-700">
            총 {bomItems.length}개 품목
          </Badge>}
          action={
            <ActionButton 
              icon={Save}
              onClick={() => toast.success("BOM이 저장되었습니다")}
            >
              저장
            </ActionButton>
          }
        >
          <BOMTable 
            items={bomItems}
            onEdit={(item) => toast.info(`${item.itemName} 편집`)}
            onDelete={(item) => {
              if (confirm(`${item.itemName}을(를) 삭제하시겠습니까?`)) {
                toast.success("삭제되었습니다");
              }
            }}
          />
        </DetailSection>
      )
    },
    {
      value: "images",
      label: "이미지",
      icon: ImageIcon,
      count: images.length,
      content: (
        <DetailSection
          icon={ImageIcon}
          title="제품 이미지"
          badge={<Badge variant="outline">{images.length}개</Badge>}
          action={
            <ActionButton onClick={() => toast.info("이미지 업로드")}>
              이미지 추가
            </ActionButton>
          }
        >
          <ImageGallery 
            images={images}
            onDelete={(image) => {
              if (confirm("이미지를 삭제하시겠습니까?")) {
                toast.success("이미지가 삭제되었습니다");
              }
            }}
            maxHeight="250px"
          />
        </DetailSection>
      )
    },
    {
      value: "history",
      label: "변경이력",
      icon: History,
      content: (
        <DetailSection
          icon={History}
          title="변경 이력"
          badge={<StatusBadge status={`V${itemData.version}`} colorScheme="purple" />}
        >
          <div className="space-y-4">
            <div className="border-l-4 border-blue-500 pl-4 py-2">
              <div className="flex items-center justify-between">
                <div>
                  <div className="font-semibold">V3 - 현재 버전</div>
                  <div className="text-sm text-muted-foreground">
                    2025-01-15 • {itemData.createdBy}
                  </div>
                </div>
                <StatusBadge status="최신" colorScheme="green" />
              </div>
              <div className="mt-2 text-sm">
                재질 변경: SUS304 1.0T → SUS304 1.2T
              </div>
            </div>

            <div className="border-l-4 border-gray-300 pl-4 py-2">
              <div className="flex items-center justify-between">
                <div>
                  <div className="font-semibold">V2</div>
                  <div className="text-sm text-muted-foreground">
                    2024-12-20 • 이철수
                  </div>
                </div>
              </div>
              <div className="mt-2 text-sm">
                BOM 구성 변경: 가이드레일 수량 2개 → 4개
              </div>
            </div>

            <div className="border-l-4 border-gray-300 pl-4 py-2">
              <div className="flex items-center justify-between">
                <div>
                  <div className="font-semibold">V1</div>
                  <div className="text-sm text-muted-foreground">
                    2024-11-10 • {itemData.createdBy}
                  </div>
                </div>
              </div>
              <div className="mt-2 text-sm">
                최초 등록
              </div>
            </div>
          </div>
        </DetailSection>
      )
    }
  ];

  return (
    <IntegratedFormTemplateV2
      title={itemData.itemName}
      subtitle={itemData.itemCode}
      icon={Package}
      badge={<StatusBadge status="사용중" colorScheme="green" />}
      onBack={() => toast.info("목록으로 이동")}
      onEdit={() => toast.info("수정 모드로 전환")}
      onCopy={() => toast.info("품목 복사")}
      onDelete={() => {
        if (confirm("정말 삭제하시겠습니까?")) {
          toast.success("삭제되었습니다");
        }
      }}
      customActions={[
        {
          icon: FileText,
          label: "견적서 생성",
          onClick: () => toast.info("견적서 생성"),
          variant: "outline"
        }
      ]}
      tabs={tabs}
      defaultTab="basic"
      maxWidth="4xl"
      versionInfo={
        <div className="flex items-center gap-2">
          <StatusBadge status={`버전 ${itemData.version}`} colorScheme="purple" />
          <span className="text-xs text-muted-foreground">
            최종 수정: {itemData.createdAt}
          </span>
        </div>
      }
    />
  );
}

/**
 * 사용법 가이드:
 * 
 * 1. 기본 사용:
 * ```tsx
 * <IntegratedFormTemplateV2
 *   title="품목 상세정보"
 *   subtitle="KQTS01"
 *   icon={Package}
 *   onBack={() => navigate('/items')}
 * >
 *   <DetailSection title="기본 정보">
 *     <InfoGrid columns={2}>
 *       <InfoField label="품목코드" value="KQTS01" />
 *       <InfoField label="품목명" value="방화문" />
 *     </InfoGrid>
 *   </DetailSection>
 * </IntegratedFormTemplateV2>
 * ```
 * 
 * 2. 탭 사용:
 * ```tsx
 * <IntegratedFormTemplateV2
 *   title="품목 상세정보"
 *   tabs={[
 *     { value: 'basic', label: '기본정보', content: <BasicInfo /> },
 *     { value: 'bom', label: 'BOM', count: 5, content: <BOMInfo /> }
 *   ]}
 * />
 * ```
 * 
 * 3. Atoms 사용:
 * - InfoLabel: 정보 레이블 표시
 * - InfoValue: 정보 값 표시
 * - StatusBadge: 상태 배지
 * - ActionButton: 액션 버튼
 * 
 * 4. Molecules 사용:
 * - InfoField: 레이블 + 값 조합
 * - SectionHeader: 섹션 헤더
 * - InfoGrid: 정보 그리드
 * - TabButton: 탭 버튼
 * 
 * 5. Organisms 사용:
 * - DetailSection: 상세 정보 섹션
 * - BOMTable: BOM 테이블
 * - TabPanel: 탭 패널
 * - ImageGallery: 이미지 갤러리
 */
