/**
 * 통합 폼 템플릿 V2 (Integrated Form Template V2)
 * 
 * 아토믹 디자인 시스템 기반 통합 폼 레이아웃
 * - Atoms: Badge, Button, Input, Label 등 기본 UI 요소
 * - Molecules: InfoField, SectionHeader, TabButton 등 조합 요소
 * - Organisms: DetailSection, TabPanel, BOMTable 등 복잡한 UI 블록
 * - Template: 전체 상세 정보 페이지 레이아웃
 * 
 * 품목관리 상세 정보 페이지 구조 기반
 */

import { ReactNode, useState } from "react";
import { LucideIcon, ArrowLeft, Edit, Trash2, FileText, History, Copy, X } from "lucide-react";
import { Button } from "../ui/button";
import { Badge } from "../ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../ui/table";
import { Label } from "../ui/label";
import { Separator } from "../ui/separator";

// ============================================
// ATOMS (기본 UI 요소)
// ============================================

/**
 * 정보 라벨 (Atom)
 * 필드의 레이블을 표시
 */
interface InfoLabelProps {
  children: ReactNode;
  required?: boolean;
  className?: string;
}

export function InfoLabel({ children, required, className = "" }: InfoLabelProps) {
  return (
    <span className={`text-xs text-muted-foreground ${className}`}>
      {children}
      {required && <span className="text-red-500 ml-1">*</span>}
    </span>
  );
}

/**
 * 정보 값 (Atom)
 * 필드의 값을 표시
 */
interface InfoValueProps {
  children: ReactNode;
  className?: string;
  mono?: boolean;
}

export function InfoValue({ children, className = "", mono = false }: InfoValueProps) {
  return (
    <div className={`font-medium mt-1 ${mono ? 'font-mono' : ''} ${className}`}>
      {children || <span className="text-muted-foreground">-</span>}
    </div>
  );
}

/**
 * 상태 배지 (Atom)
 * 상태를 표시하는 배지
 */
interface StatusBadgeProps {
  status: string;
  variant?: 'default' | 'secondary' | 'outline' | 'destructive';
  colorScheme?: 'blue' | 'green' | 'red' | 'yellow' | 'purple' | 'gray';
  className?: string;
}

export function StatusBadge({ status, variant = 'outline', colorScheme = 'blue', className = "" }: StatusBadgeProps) {
  const colorClasses = {
    blue: 'bg-blue-50 text-blue-700 border-blue-200',
    green: 'bg-green-50 text-green-700 border-green-200',
    red: 'bg-red-50 text-red-700 border-red-200',
    yellow: 'bg-yellow-50 text-yellow-700 border-yellow-200',
    purple: 'bg-purple-50 text-purple-700 border-purple-200',
    gray: 'bg-gray-50 text-gray-700 border-gray-200',
  };

  return (
    <Badge variant={variant} className={`${colorClasses[colorScheme]} ${className}`}>
      {status}
    </Badge>
  );
}

/**
 * 액션 버튼 (Atom)
 * 단일 액션을 수행하는 버튼
 */
interface ActionButtonProps {
  icon?: LucideIcon;
  children: ReactNode;
  onClick?: () => void;
  variant?: 'default' | 'outline' | 'ghost' | 'destructive';
  size?: 'default' | 'sm' | 'lg' | 'icon';
  disabled?: boolean;
  className?: string;
}

export function ActionButton({ 
  icon: Icon, 
  children, 
  onClick, 
  variant = 'outline', 
  size = 'sm',
  disabled = false,
  className = ""
}: ActionButtonProps) {
  return (
    <Button 
      variant={variant} 
      size={size} 
      onClick={onClick} 
      disabled={disabled}
      className={className}
    >
      {Icon && <Icon className="h-4 w-4 mr-2" />}
      {children}
    </Button>
  );
}

// ============================================
// MOLECULES (조합 UI 요소)
// ============================================

/**
 * 정보 필드 (Molecule)
 * 라벨과 값을 함께 표시하는 필드
 */
interface InfoFieldProps {
  label: string;
  value?: ReactNode;
  required?: boolean;
  mono?: boolean;
  badge?: ReactNode;
  className?: string;
}

export function InfoField({ label, value, required, mono, badge, className = "" }: InfoFieldProps) {
  return (
    <div className={className}>
      <InfoLabel required={required}>{label}</InfoLabel>
      <div className="flex items-center gap-2 mt-1">
        {typeof value === 'string' || typeof value === 'number' ? (
          <InfoValue mono={mono}>{value}</InfoValue>
        ) : (
          value || <span className="text-muted-foreground">-</span>
        )}
        {badge}
      </div>
    </div>
  );
}

/**
 * 섹션 헤더 (Molecule)
 * 섹션의 제목과 배지를 표시
 */
interface SectionHeaderProps {
  icon?: LucideIcon;
  title: string;
  badge?: ReactNode;
  action?: ReactNode;
}

export function SectionHeader({ icon: Icon, title, badge, action }: SectionHeaderProps) {
  return (
    <div className="flex items-center justify-between">
      <div className="flex items-center gap-2">
        {Icon && <Icon className="h-5 w-5" />}
        <span className="font-semibold">{title}</span>
        {badge}
      </div>
      {action}
    </div>
  );
}

/**
 * 정보 그리드 (Molecule)
 * 정보 필드들을 그리드로 배치
 */
interface InfoGridProps {
  children: ReactNode;
  columns?: 1 | 2 | 3 | 4;
  className?: string;
}

export function InfoGrid({ children, columns = 2, className = "" }: InfoGridProps) {
  const gridClasses = {
    1: 'grid-cols-1',
    2: 'grid-cols-1 md:grid-cols-2',
    3: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
    4: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-4',
  };

  return (
    <div className={`grid ${gridClasses[columns]} gap-4 ${className}`}>
      {children}
    </div>
  );
}

/**
 * 탭 버튼 (Molecule)
 * 탭 메뉴의 버튼
 */
interface TabButtonProps {
  value: string;
  label: string;
  count?: number;
  icon?: LucideIcon;
}

export function TabButton({ value, label, count, icon: Icon }: TabButtonProps) {
  return (
    <TabsTrigger value={value} className="flex items-center gap-2">
      {Icon && <Icon className="h-4 w-4" />}
      {label}
      {count !== undefined && (
        <Badge variant="secondary" className="ml-1">
          {count}
        </Badge>
      )}
    </TabsTrigger>
  );
}

// ============================================
// ORGANISMS (복잡한 UI 블록)
// ============================================

/**
 * 상세 섹션 (Organism)
 * 카드 형태의 상세 정보 섹션
 */
interface DetailSectionProps {
  icon?: LucideIcon;
  title: string;
  badge?: ReactNode;
  action?: ReactNode;
  children: ReactNode;
  collapsible?: boolean;
  defaultCollapsed?: boolean;
  className?: string;
}

export function DetailSection({ 
  icon, 
  title, 
  badge, 
  action, 
  children, 
  collapsible = false,
  defaultCollapsed = false,
  className = ""
}: DetailSectionProps) {
  const [collapsed, setCollapsed] = useState(defaultCollapsed);

  return (
    <Card className={className}>
      <CardHeader className="pb-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2 flex-1">
            {icon && <icon className="h-5 w-5" />}
            <CardTitle className="text-base">{title}</CardTitle>
            {badge}
          </div>
          <div className="flex items-center gap-2">
            {action}
            {collapsible && (
              <Button 
                variant="ghost" 
                size="sm" 
                onClick={() => setCollapsed(!collapsed)}
              >
                {collapsed ? '펼치기' : '접기'}
              </Button>
            )}
          </div>
        </div>
      </CardHeader>
      {!collapsed && (
        <CardContent className="space-y-4">
          {children}
        </CardContent>
      )}
    </Card>
  );
}

/**
 * BOM 테이블 (Organism)
 * BOM 목록을 표시하는 테이블
 */
interface BOMItem {
  id: string;
  no: number;
  itemCode: string;
  itemName: string;
  specification?: string;
  quantity: number;
  unit: string;
  material?: string;
  finishing?: string;
  note?: string;
  badges?: ReactNode[];
  expandedContent?: ReactNode;
}

interface BOMTableProps {
  items: BOMItem[];
  onEdit?: (item: BOMItem) => void;
  onDelete?: (item: BOMItem) => void;
  showActions?: boolean;
  className?: string;
}

export function BOMTable({ items, onEdit, onDelete, showActions = true, className = "" }: BOMTableProps) {
  const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set());

  const toggleRow = (id: string) => {
    const newExpanded = new Set(expandedRows);
    if (newExpanded.has(id)) {
      newExpanded.delete(id);
    } else {
      newExpanded.add(id);
    }
    setExpandedRows(newExpanded);
  };

  return (
    <div className={`border rounded-lg overflow-hidden ${className}`}>
      <Table>
        <TableHeader>
          <TableRow className="bg-muted/50">
            <TableHead className="w-16 text-center">번호</TableHead>
            <TableHead className="w-32">품목코드</TableHead>
            <TableHead>품목명</TableHead>
            <TableHead className="w-32">재질/마감</TableHead>
            <TableHead className="w-20 text-right">수량</TableHead>
            <TableHead className="w-20">단위</TableHead>
            {showActions && <TableHead className="w-24 text-center">작업</TableHead>}
          </TableRow>
        </TableHeader>
        <TableBody>
          {items.length === 0 ? (
            <TableRow>
              <TableCell colSpan={showActions ? 7 : 6} className="text-center py-8 text-muted-foreground">
                등록된 BOM이 없습니다
              </TableCell>
            </TableRow>
          ) : (
            items.map((item) => (
              <>
                <TableRow 
                  key={item.id}
                  className={`hover:bg-muted/30 ${item.expandedContent ? 'cursor-pointer' : ''}`}
                  onClick={() => item.expandedContent && toggleRow(item.id)}
                >
                  <TableCell className="text-center">{item.no}</TableCell>
                  <TableCell>
                    <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                      {item.itemCode}
                    </code>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      {item.itemName}
                      {item.badges && item.badges.map((badge, idx) => (
                        <span key={idx}>{badge}</span>
                      ))}
                    </div>
                  </TableCell>
                  <TableCell>
                    {item.material ? (
                      <StatusBadge status={item.material} colorScheme="green" />
                    ) : item.finishing ? (
                      <StatusBadge status={item.finishing} colorScheme="blue" />
                    ) : (
                      <span className="text-muted-foreground">-</span>
                    )}
                  </TableCell>
                  <TableCell className="text-right font-semibold">{item.quantity}</TableCell>
                  <TableCell>{item.unit}</TableCell>
                  {showActions && (
                    <TableCell>
                      <div className="flex items-center justify-center gap-1">
                        {onEdit && (
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={(e) => {
                              e.stopPropagation();
                              onEdit(item);
                            }}
                          >
                            <Edit className="h-3 w-3" />
                          </Button>
                        )}
                        {onDelete && (
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={(e) => {
                              e.stopPropagation();
                              onDelete(item);
                            }}
                          >
                            <Trash2 className="h-3 w-3 text-red-600" />
                          </Button>
                        )}
                      </div>
                    </TableCell>
                  )}
                </TableRow>
                {item.expandedContent && expandedRows.has(item.id) && (
                  <TableRow>
                    <TableCell colSpan={showActions ? 7 : 6} className="bg-muted/20 p-4">
                      {item.expandedContent}
                    </TableCell>
                  </TableRow>
                )}
              </>
            ))
          )}
        </TableBody>
      </Table>
    </div>
  );
}

/**
 * 탭 패널 (Organism)
 * 탭으로 구분된 컨텐츠 영역
 */
interface Tab {
  value: string;
  label: string;
  count?: number;
  icon?: LucideIcon;
  content: ReactNode;
}

interface TabPanelProps {
  tabs: Tab[];
  defaultTab?: string;
  className?: string;
}

export function TabPanel({ tabs, defaultTab, className = "" }: TabPanelProps) {
  return (
    <Tabs defaultValue={defaultTab || tabs[0]?.value} className={className}>
      <TabsList className="w-full justify-start overflow-x-auto flex-wrap h-auto">
        {tabs.map((tab) => (
          <TabButton
            key={tab.value}
            value={tab.value}
            label={tab.label}
            count={tab.count}
            icon={tab.icon}
          />
        ))}
      </TabsList>
      {tabs.map((tab) => (
        <TabsContent key={tab.value} value={tab.value} className="mt-4">
          {tab.content}
        </TabsContent>
      ))}
    </Tabs>
  );
}

/**
 * 헤더 액션 바 (Organism)
 * 상세 페이지 상단의 액션 버튼 영역
 */
interface HeaderAction {
  icon?: LucideIcon;
  label: string;
  onClick: () => void;
  variant?: 'default' | 'outline' | 'ghost' | 'destructive';
  show?: boolean;
}

interface HeaderActionBarProps {
  actions: HeaderAction[];
  className?: string;
}

export function HeaderActionBar({ actions, className = "" }: HeaderActionBarProps) {
  const visibleActions = actions.filter(action => action.show !== false);

  return (
    <div className={`flex items-center gap-2 flex-wrap ${className}`}>
      {visibleActions.map((action, index) => (
        <ActionButton
          key={index}
          icon={action.icon}
          onClick={action.onClick}
          variant={action.variant || 'outline'}
        >
          {action.label}
        </ActionButton>
      ))}
    </div>
  );
}

/**
 * 이미지 갤러리 (Organism)
 * 이미지들을 갤러리 형태로 표시
 */
interface ImageItem {
  id: string;
  url: string;
  alt?: string;
  caption?: string;
}

interface ImageGalleryProps {
  images: ImageItem[];
  onDelete?: (image: ImageItem) => void;
  maxHeight?: string;
  className?: string;
}

export function ImageGallery({ images, onDelete, maxHeight = '200px', className = "" }: ImageGalleryProps) {
  if (images.length === 0) {
    return (
      <div className="text-center py-8 text-muted-foreground border-2 border-dashed rounded-lg">
        등록된 이미지가 없습니다
      </div>
    );
  }

  return (
    <div className={`grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 ${className}`}>
      {images.map((image) => (
        <div key={image.id} className="relative group">
          <img
            src={image.url}
            alt={image.alt || '이미지'}
            className="w-full border rounded-lg object-cover hover:scale-105 transition-transform cursor-pointer"
            style={{ maxHeight }}
            onClick={() => window.open(image.url, '_blank')}
          />
          {image.caption && (
            <p className="text-xs text-center text-muted-foreground mt-1">
              {image.caption}
            </p>
          )}
          {onDelete && (
            <Button
              variant="destructive"
              size="icon"
              className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity h-6 w-6"
              onClick={() => onDelete(image)}
            >
              <X className="h-3 w-3" />
            </Button>
          )}
        </div>
      ))}
    </div>
  );
}

// ============================================
// TEMPLATE (전체 레이아웃)
// ============================================

/**
 * 통합 폼 템플릿 V2 Props
 */
interface IntegratedFormTemplateV2Props {
  // 헤더 정보
  title: string;
  subtitle?: string;
  icon?: LucideIcon;
  badge?: ReactNode;
  
  // 액션 버튼
  onBack?: () => void;
  onEdit?: () => void;
  onDelete?: () => void;
  onCopy?: () => void;
  customActions?: HeaderAction[];
  
  // 탭 구성
  tabs?: Tab[];
  defaultTab?: string;
  
  // 메인 컨텐츠
  children: ReactNode;
  
  // 레이아웃 설정
  maxWidth?: 'md' | 'lg' | 'xl' | '2xl' | '3xl' | '4xl' | 'full';
  showBackButton?: boolean;
  
  // 버전 정보
  versionInfo?: ReactNode;
}

/**
 * 통합 폼 템플릿 V2 (Template)
 * 품목관리 상세 정보 페이지 레이아웃 기반
 */
export function IntegratedFormTemplateV2({
  title,
  subtitle,
  icon: Icon,
  badge,
  onBack,
  onEdit,
  onDelete,
  onCopy,
  customActions = [],
  tabs,
  defaultTab,
  children,
  maxWidth = '4xl',
  showBackButton = true,
  versionInfo
}: IntegratedFormTemplateV2Props) {
  const maxWidthClasses = {
    md: 'max-w-md',
    lg: 'max-w-lg',
    xl: 'max-w-xl',
    '2xl': 'max-w-2xl',
    '3xl': 'max-w-3xl',
    '4xl': 'max-w-4xl',
    full: 'max-w-full'
  };

  // 기본 액션 버튼 구성
  const defaultActions: HeaderAction[] = [
    { icon: Edit, label: '수정', onClick: onEdit!, variant: 'default', show: !!onEdit },
    { icon: Copy, label: '복사', onClick: onCopy!, show: !!onCopy },
    { icon: Trash2, label: '삭제', onClick: onDelete!, variant: 'destructive', show: !!onDelete },
  ];

  const allActions = [...customActions, ...defaultActions];

  return (
    <div className={`p-4 md:p-6 space-y-6 ${maxWidthClasses[maxWidth]} mx-auto w-full`}>
      {/* 버전 정보 */}
      {versionInfo && (
        <div className="flex justify-end">
          {versionInfo}
        </div>
      )}

      {/* 헤더 */}
      <div className="space-y-4">
        {/* 뒤로가기 버튼 */}
        {showBackButton && onBack && (
          <Button variant="ghost" onClick={onBack} className="mb-2">
            <ArrowLeft className="h-4 w-4 mr-2" />
            목록으로
          </Button>
        )}

        {/* 제목 영역 */}
        <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
          <div className="flex items-center gap-3">
            {Icon && <Icon className="h-8 w-8 text-primary" />}
            <div>
              <div className="flex items-center gap-2">
                <h1 className="text-2xl md:text-3xl font-bold">{title}</h1>
                {badge}
              </div>
              {subtitle && (
                <p className="text-muted-foreground mt-1">{subtitle}</p>
              )}
            </div>
          </div>

          {/* 액션 버튼 */}
          <HeaderActionBar actions={allActions} />
        </div>

        <Separator />
      </div>

      {/* 탭 또는 메인 컨텐츠 */}
      {tabs ? (
        <TabPanel tabs={tabs} defaultTab={defaultTab} />
      ) : (
        <div className="space-y-6">
          {children}
        </div>
      )}
    </div>
  );
}

// ============================================
// 사용 예시 (Example Usage)
// ============================================

/**
 * 사용 예시:
 * 
 * import { 
 *   IntegratedFormTemplateV2, 
 *   DetailSection, 
 *   InfoGrid, 
 *   InfoField,
 *   BOMTable,
 *   ImageGallery,
 *   StatusBadge
 * } from './templates/IntegratedFormTemplateV2';
 * 
 * function ItemDetailPage() {
 *   return (
 *     <IntegratedFormTemplateV2
 *       title="품목 상세정보"
 *       subtitle="KQTS01"
 *       icon={Package}
 *       badge={<StatusBadge status="사용중" colorScheme="green" />}
 *       onBack={() => navigate('/items')}
 *       onEdit={() => setEditMode(true)}
 *       onDelete={() => handleDelete()}
 *       tabs={[
 *         {
 *           value: 'basic',
 *           label: '기본정보',
 *           content: (
 *             <DetailSection title="기본 정보" icon={FileText}>
 *               <InfoGrid columns={3}>
 *                 <InfoField label="품목코드" value="KQTS01" mono />
 *                 <InfoField label="품목명" value="방화문" />
 *                 <InfoField label="규격" value="1500x2000" />
 *               </InfoGrid>
 *             </DetailSection>
 *           )
 *         },
 *         {
 *           value: 'bom',
 *           label: 'BOM',
 *           count: 5,
 *           content: (
 *             <DetailSection title="부품 구성" icon={Package}>
 *               <BOMTable 
 *                 items={bomItems}
 *                 onEdit={handleBOMEdit}
 *                 onDelete={handleBOMDelete}
 *               />
 *             </DetailSection>
 *           )
 *         }
 *       ]}
 *     />
 *   );
 * }
 */

export default IntegratedFormTemplateV2;
