/**
 * 통합 폼 템플릿 V3 (Integrated Form Template V3)
 * 
 * 품목관리 상세 페이지 기반 - 모든 요소를 재사용 가능한 템플릿으로 구조화
 * - 아토믹 디자인 시스템 기반
 * - 완전한 반응형 레이아웃
 * - 버전 관리 시스템 통합
 * - 조건부 섹션 렌더링
 * - 이미지 갤러리, BOM 테이블 등 포함
 * 
 * 사용 예시:
 * <IntegratedFormTemplateV3
 *   config={{
 *     header: { title, description, icon, actions },
 *     sections: [...],
 *     versionControl: { ... }
 *   }}
 * />
 */

import { ReactNode } from "react";
import { LucideIcon } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Label } from "../ui/label";
import { Separator } from "../ui/separator";
import { PageLayout } from "../organisms/PageLayout";
import { PageHeader } from "../organisms/PageHeader";

// ============================================
// 타입 정의
// ============================================

/**
 * 필드 아이템 (개별 정보 필드)
 */
export interface FieldItem {
  label: string;
  value?: ReactNode;
  type?: "text" | "badge" | "code" | "custom";
  badgeVariant?: "default" | "secondary" | "outline" | "destructive";
  badgeColor?: string;
  span?: 1 | 2 | 3 | 4; // 컬럼 스팬
  hidden?: boolean; // 조건부 표시
  className?: string;
}

/**
 * 섹션 설정
 */
export interface SectionConfig {
  id: string;
  title: string;
  icon?: LucideIcon;
  hidden?: boolean; // 조건부 표시
  gridCols?: {
    default: 1 | 2 | 3 | 4;
    md?: 1 | 2 | 3 | 4;
    lg?: 1 | 2 | 3 | 4;
  };
  fields?: FieldItem[];
  customContent?: ReactNode; // 커스텀 컨텐츠
  headerBadge?: ReactNode;
  className?: string;
  cardClassName?: string;
}

/**
 * 버전 관리 설정
 */
export interface VersionControlConfig {
  currentRevision: number;
  revisions?: any[];
  selectedRevision?: string;
  onRevisionChange?: (revision: string) => void;
  itemType?: string;
  versionHistory?: Array<{
    id: string;
    version: number;
    changeDescription: string;
    changedBy: string;
    changedAt: string;
  }>;
  hidden?: boolean;
}

/**
 * 헤더 액션 버튼
 */
export interface HeaderAction {
  label: string;
  icon?: LucideIcon;
  onClick: () => void;
  variant?: "default" | "outline" | "ghost" | "destructive";
  hidden?: boolean;
}

/**
 * 헤더 설정
 */
export interface HeaderConfig {
  title: string;
  description?: string;
  icon?: LucideIcon;
  actions?: ReactNode; // 커스텀 액션 버튼 영역
  badge?: ReactNode;
}

/**
 * 이미지 아이템
 */
export interface ImageItem {
  id: string;
  url: string;
  alt: string;
  caption?: string;
}

/**
 * 이미지 갤러리 설정
 */
export interface ImageGalleryConfig {
  title: string;
  icon?: LucideIcon;
  images: ImageItem[];
  hidden?: boolean;
  columns?: {
    default: 1 | 2 | 3 | 4;
    md?: 1 | 2 | 3 | 4;
    lg?: 1 | 2 | 3 | 4;
  };
}

/**
 * 테이블 컬럼 설정
 */
export interface TableColumn {
  key: string;
  label: string;
  width?: string;
  render?: (value: any, row: any) => ReactNode;
  className?: string;
}

/**
 * 테이블 섹션 설정
 */
export interface TableSectionConfig {
  id: string;
  title: string;
  icon?: LucideIcon;
  columns: TableColumn[];
  data: any[];
  hidden?: boolean;
  emptyMessage?: string;
  responsive?: boolean; // 모바일에서 카드형으로 전환
  actions?: ReactNode;
  headerBadge?: ReactNode;
}

/**
 * 통합 템플릿 설정
 */
export interface IntegratedFormTemplateV3Config {
  header: HeaderConfig;
  versionControl?: VersionControlConfig;
  sections: SectionConfig[];
  tableSections?: TableSectionConfig[];
  imageGallery?: ImageGalleryConfig;
  maxWidth?: "default" | "full" | "lg" | "xl" | "2xl";
}

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

/**
 * 필드 라벨 (Atom)
 */
interface FieldLabelProps {
  children: ReactNode;
  required?: boolean;
  className?: string;
}

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

/**
 * 필드 값 (Atom)
 */
interface FieldValueProps {
  children: ReactNode;
  type?: "text" | "code" | "badge";
  className?: string;
}

export function FieldValue({ children, type = "text", className = "" }: FieldValueProps) {
  if (type === "code") {
    return (
      <code className={`text-sm bg-gray-100 px-2 py-1 rounded ${className}`}>
        {children}
      </code>
    );
  }

  if (type === "badge") {
    return <>{children}</>;
  }

  return (
    <p className={`mt-1 font-medium ${className}`}>
      {children || <span className="text-muted-foreground">-</span>}
    </p>
  );
}

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

/**
 * 정보 필드 (Molecule)
 * 라벨 + 값 조합
 */
interface InfoFieldProps {
  field: FieldItem;
}

export function InfoField({ field }: InfoFieldProps) {
  if (field.hidden) return null;

  const spanClass = field.span 
    ? `md:col-span-${field.span === 2 ? '2' : field.span === 3 ? '3' : field.span === 4 ? '4' : '1'}`
    : '';

  return (
    <div className={`${spanClass} ${field.className || ''}`}>
      <FieldLabel>{field.label}</FieldLabel>
      {field.type === "custom" ? (
        field.value
      ) : field.type === "code" ? (
        <FieldValue type="code">{field.value}</FieldValue>
      ) : field.type === "badge" ? (
        <div className="mt-1">{field.value}</div>
      ) : (
        <FieldValue>{field.value}</FieldValue>
      )}
    </div>
  );
}

/**
 * 버전 선택기 (Molecule)
 */
interface RevisionSelectorProps {
  config: VersionControlConfig;
}

export function RevisionSelector({ config }: RevisionSelectorProps) {
  if (config.hidden || !config.revisions || config.revisions.length === 0) {
    return null;
  }

  return (
    <Card>
      <CardContent className="pt-6">
        <div className="flex items-center gap-4">
          <Label className="text-sm font-medium">버전 선택:</Label>
          <select
            value={config.selectedRevision || "current"}
            onChange={(e) => config.onRevisionChange?.(e.target.value)}
            className="border rounded px-3 py-1.5 text-sm"
          >
            <option value="current">현재 버전 (V{config.currentRevision})</option>
            {config.revisions.map((rev, idx) => (
              <option key={idx} value={`v${idx}`}>
                V{idx} - {new Date(rev.updatedAt || Date.now()).toLocaleDateString('ko-KR')}
              </option>
            ))}
          </select>
        </div>
      </CardContent>
    </Card>
  );
}

/**
 * 버전 히스토리 (Molecule)
 */
interface VersionHistoryProps {
  config: VersionControlConfig;
}

export function VersionHistory({ config }: VersionHistoryProps) {
  if (!config.versionHistory || config.versionHistory.length === 0) {
    return null;
  }

  return (
    <Card className="border-purple-200 bg-purple-50">
      <CardHeader>
        <CardTitle className="flex items-center gap-2 text-purple-700">
          수정 이력
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="bg-white border border-purple-200 rounded-lg p-4">
          <div className="text-sm space-y-2">
            <div className="flex items-center justify-between mb-2">
              <span className="font-semibold text-purple-700">최근 수정 이력</span>
              <Badge variant="secondary">총 {config.versionHistory.length}건</Badge>
            </div>
            <div className="max-h-32 overflow-y-auto space-y-2">
              {config.versionHistory.slice().reverse().slice(0, 3).map((history) => (
                <div key={history.id} className="flex items-center gap-2 text-xs">
                  <Badge variant="outline">v{history.version}</Badge>
                  <span className="text-muted-foreground">•</span>
                  <span>{history.changeDescription}</span>
                  <span className="text-muted-foreground">•</span>
                  <span className="text-muted-foreground">{history.changedBy}</span>
                  <span className="text-muted-foreground ml-auto">
                    {new Date(history.changedAt).toLocaleDateString('ko-KR')}
                  </span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}

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

/**
 * 정보 섹션 (Organism)
 * 여러 필드를 그리드로 배치하는 카드
 */
interface InfoSectionProps {
  section: SectionConfig;
}

export function InfoSection({ section }: InfoSectionProps) {
  if (section.hidden) return null;

  const gridClass = section.gridCols
    ? `grid-cols-${section.gridCols.default} ${
        section.gridCols.md ? `md:grid-cols-${section.gridCols.md}` : ''
      } ${section.gridCols.lg ? `lg:grid-cols-${section.gridCols.lg}` : ''}`
    : 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3';

  return (
    <Card className={section.cardClassName}>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          {section.icon && <section.icon className="h-5 w-5" />}
          {section.title}
          {section.headerBadge}
        </CardTitle>
      </CardHeader>
      <CardContent>
        {section.customContent ? (
          section.customContent
        ) : (
          <div className={`grid ${gridClass} gap-6 ${section.className || ''}`}>
            {section.fields?.map((field, idx) => (
              <InfoField key={idx} field={field} />
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  );
}

/**
 * 테이블 섹션 (Organism)
 */
interface TableSectionProps {
  section: TableSectionConfig;
}

export function TableSection({ section }: TableSectionProps) {
  if (section.hidden) return null;

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <CardTitle className="flex items-center gap-2">
            {section.icon && <section.icon className="h-5 w-5" />}
            {section.title}
            {section.headerBadge}
          </CardTitle>
          {section.actions}
        </div>
      </CardHeader>
      <CardContent>
        {section.data.length === 0 ? (
          <div className="text-center py-8 text-muted-foreground">
            {section.emptyMessage || "데이터가 없습니다"}
          </div>
        ) : (
          <div className={`overflow-x-auto ${section.responsive ? '-mx-2 md:mx-0' : ''}`}>
            <table className="w-full text-sm min-w-[500px]">
              <thead className="bg-gray-100">
                <tr>
                  {section.columns.map((col) => (
                    <th
                      key={col.key}
                      className={`border px-2 py-2 ${col.className || ''}`}
                      style={col.width ? { width: col.width } : undefined}
                    >
                      {col.label}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {section.data.map((row, rowIdx) => (
                  <tr key={rowIdx}>
                    {section.columns.map((col) => (
                      <td key={col.key} className="border px-2 py-2">
                        {col.render ? col.render(row[col.key], row) : row[col.key]}
                      </td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </CardContent>
    </Card>
  );
}

/**
 * 이미지 갤러리 (Organism)
 */
interface ImageGalleryProps {
  config: ImageGalleryConfig;
}

export function ImageGallery({ config }: ImageGalleryProps) {
  if (config.hidden || config.images.length === 0) return null;

  const gridClass = config.columns
    ? `grid-cols-${config.columns.default} ${
        config.columns.md ? `md:grid-cols-${config.columns.md}` : ''
      } ${config.columns.lg ? `lg:grid-cols-${config.columns.lg}` : ''}`
    : 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3';

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          {config.icon && <config.icon className="h-5 w-5" />}
          {config.title}
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className={`grid ${gridClass} gap-4`}>
          {config.images.map((image) => (
            <div key={image.id} className="space-y-2">
              <div className="border rounded-lg overflow-hidden bg-gray-50">
                <img
                  src={image.url}
                  alt={image.alt}
                  className="w-full h-48 object-cover"
                />
              </div>
              {image.caption && (
                <p className="text-sm text-muted-foreground text-center">
                  {image.caption}
                </p>
              )}
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  );
}

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

/**
 * 통합 폼 템플릿 V3
 */
interface IntegratedFormTemplateV3Props {
  config: IntegratedFormTemplateV3Config;
}

export function IntegratedFormTemplateV3({ config }: IntegratedFormTemplateV3Props) {
  return (
    <PageLayout maxWidth={config.maxWidth}>
      {/* 페이지 헤더 */}
      <PageHeader
        title={config.header.title}
        description={config.header.description}
        icon={config.header.icon}
        actions={config.header.actions}
      />

      {/* 버전 선택기 */}
      {config.versionControl && (
        <RevisionSelector config={config.versionControl} />
      )}

      {/* 버전 히스토리 */}
      {config.versionControl && (
        <VersionHistory config={config.versionControl} />
      )}

      {/* 정보 섹션들 */}
      {config.sections.map((section) => (
        <InfoSection key={section.id} section={section} />
      ))}

      {/* 테이블 섹션들 */}
      {config.tableSections?.map((section) => (
        <TableSection key={section.id} section={section} />
      ))}

      {/* 이미지 갤러리 */}
      {config.imageGallery && (
        <ImageGallery config={config.imageGallery} />
      )}
    </PageLayout>
  );
}

export default IntegratedFormTemplateV3;
