/**
 * 기본 등록 페이지 템플릿
 * 
 * 품목 등록 페이지를 기반으로 한 재사용 가능한 등록/수정 페이지 템플릿입니다.
 * - PageLayout
 * - PageHeader with FormActions
 * - Version History Card (선택사항)
 * - Validation Error Summary (선택사항)
 * - Form Sections (Card 기반)
 * - Bottom Actions (선택사항)
 */

import { ReactNode } from "react";
import { LucideIcon, History, X } from "lucide-react";
import { PageLayout } from "../organisms/PageLayout";
import { PageHeader } from "../organisms/PageHeader";
import { FormActions } from "../molecules/FormActions";
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import { Alert, AlertDescription } from "../ui/alert";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";

/**
 * 버전 히스토리 항목
 */
export interface VersionHistoryItem {
  id: string;
  version: number;
  changeDescription: string;
  changedBy: string;
  changedAt: string;
}

/**
 * 유효성 검증 에러 타입
 */
export type ValidationErrors = Record<string, string>;

/**
 * 섹션 정의
 */
export interface FormSection {
  id: string;
  title: string;
  icon?: LucideIcon;
  content: ReactNode;
  className?: string;
  headerClassName?: string;
  error?: boolean; // 에러가 있는 섹션인 경우 테두리 표시
}

/**
 * 필드명 맵핑 타입
 */
export type FieldNameMap = Record<string, string>;

export interface BasicRegistrationTemplateProps {
  // 페이지 헤더
  title: string;
  description?: string;
  icon?: LucideIcon;
  
  // 헤더 액션 (FormActions)
  onSave?: () => void;
  onCancel?: () => void;
  saveDisabled?: boolean;
  saveText?: string;
  cancelText?: string;
  showHeaderActions?: boolean;
  
  // 버전 히스토리 (수정 모드일 때)
  versionHistory?: VersionHistoryItem[];
  showVersionHistory?: boolean;
  
  // 유효성 검증 에러
  validationErrors?: ValidationErrors;
  fieldNameMap?: FieldNameMap; // 필드명을 한글로 매핑
  onErrorFieldClick?: (field: string) => void; // 에러 필드 클릭 핸들러
  
  // 폼 섹션
  sections?: FormSection[];
  
  // 또는 children으로 커스텀 컨텐츠
  children?: ReactNode;
  
  // 하단 액션
  bottomActions?: ReactNode;
  
  // 레이아웃
  maxWidth?: "sm" | "md" | "lg" | "xl" | "full";
}

/**
 * 기본 등록 페이지 템플릿
 */
export function BasicRegistrationTemplate({
  title,
  description,
  icon,
  onSave,
  onCancel,
  saveDisabled = false,
  saveText = "저장",
  cancelText = "취소",
  showHeaderActions = true,
  versionHistory,
  showVersionHistory = true,
  validationErrors,
  fieldNameMap,
  onErrorFieldClick,
  sections,
  children,
  bottomActions,
  maxWidth = "xl",
}: BasicRegistrationTemplateProps) {
  
  // 에러 필드 클릭 핸들러 (기본)
  const handleErrorFieldClick = (field: string) => {
    if (onErrorFieldClick) {
      onErrorFieldClick(field);
    } else {
      // 기본 동작: 해당 필드로 스크롤
      const errorField = document.querySelector(`[name="${field}"]`) as HTMLElement;
      if (errorField) {
        errorField.scrollIntoView({ behavior: 'smooth', block: 'center' });
        errorField.focus();
      }
    }
  };

  return (
    <PageLayout maxWidth={maxWidth}>
      {/* 페이지 헤더 */}
      <PageHeader
        title={title}
        description={description}
        icon={icon}
        actions={
          showHeaderActions && (onSave || onCancel) ? (
            <FormActions
              onSave={onSave}
              onCancel={onCancel}
              saveDisabled={saveDisabled}
              saveText={saveText}
              cancelText={cancelText}
            />
          ) : undefined
        }
      />
      
      {/* 수정 모드일 때 버전 히스토리 표시 */}
      {showVersionHistory && versionHistory && versionHistory.length > 0 && (
        <Card className="border-purple-200 bg-purple-50">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-purple-700">
              <History className="h-5 w-5" />
              수정 이력
            </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">총 {versionHistory.length}건</Badge>
                </div>
                <div className="max-h-32 overflow-y-auto space-y-2">
                  {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>
      )}
      
      {/* Validation 에러 요약 */}
      {validationErrors && Object.keys(validationErrors).length > 0 && (
        <Alert className="bg-red-50 border-red-200">
          <AlertDescription className="text-red-900">
            <div className="flex items-start gap-2">
              <span className="text-lg">⚠️</span>
              <div className="flex-1">
                <strong className="block mb-2">
                  입력 내용을 확인해주세요 ({Object.keys(validationErrors).length}개 오류)
                </strong>
                <ul className="space-y-1 text-sm">
                  {Object.entries(validationErrors).map(([field, message]) => {
                    const fieldLabel = fieldNameMap?.[field] || field;
                    
                    return (
                      <li key={field} className="flex items-start gap-2">
                        <span className="text-red-600 mt-0.5">•</span>
                        <button
                          type="button"
                          onClick={() => handleErrorFieldClick(field)}
                          className="text-left hover:underline focus:outline-none focus:underline"
                        >
                          <span className="font-medium">{fieldLabel}:</span> {message}
                        </button>
                      </li>
                    );
                  })}
                </ul>
              </div>
            </div>
          </AlertDescription>
        </Alert>
      )}

      {/* 폼 섹션들 */}
      {sections && sections.map((section) => (
        <Card 
          key={section.id} 
          className={`${section.error || (validationErrors && Object.keys(validationErrors).length > 0) ? "border-red-300" : ""} ${section.className || ""}`}
        >
          <CardHeader className={section.headerClassName}>
            <CardTitle className="flex items-center gap-2">
              {section.icon && <section.icon className="h-5 w-5" />}
              {section.title}
            </CardTitle>
          </CardHeader>
          <CardContent>
            {section.content}
          </CardContent>
        </Card>
      ))}

      {/* 커스텀 컨텐츠 */}
      {children}

      {/* 하단 액션 버튼 */}
      {bottomActions}
    </PageLayout>
  );
}
