import { createContext, useContext, useState, ReactNode } from 'react';

export interface ComponentMetadata {
  componentName: string;
  pagePath: string;
  description: string;
  
  // API 정보
  apis?: {
    endpoint: string;
    method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
    description: string;
    requestBody?: any;
    responseBody?: any;
    queryParams?: { name: string; type: string; required: boolean; description: string }[];
    pathParams?: { name: string; type: string; description: string }[];
  }[];
  
  // 데이터 구조
  dataStructures?: {
    name: string;
    type: string;
    fields: { name: string; type: string; required: boolean; description: string }[];
    example?: any;
  }[];
  
  // 컴포넌트 정보
  components?: {
    name: string;
    path: string;
    props?: { name: string; type: string; required: boolean; description: string }[];
    children?: string[];
  }[];
  
  // 상태 관리
  stateManagement?: {
    type: 'Context' | 'Local' | 'Props';
    name: string;
    description: string;
    methods?: string[];
  }[];
  
  // 의존성
  dependencies?: {
    package: string;
    version?: string;
    usage: string;
  }[];
  
  // DB 스키마 (백엔드)
  dbSchema?: {
    tableName: string;
    columns: { name: string; type: string; nullable: boolean; key?: 'PK' | 'FK'; description: string }[];
    indexes?: string[];
    relations?: { table: string; type: '1:1' | '1:N' | 'N:M'; description: string }[];
  }[];
  
  // 비즈니스 로직
  businessLogic?: {
    name: string;
    description: string;
    steps: string[];
  }[];
  
  // 유효성 검사
  validations?: {
    field: string;
    rules: string[];
    errorMessages: string[];
  }[];
}

interface DeveloperModeContextType {
  isDeveloperMode: boolean;
  setIsDeveloperMode: (value: boolean) => void;
  currentMetadata: ComponentMetadata | null;
  setCurrentMetadata: (metadata: ComponentMetadata | null) => void;
  isConsoleExpanded: boolean;
  setIsConsoleExpanded: (value: boolean) => void;
}

const DeveloperModeContext = createContext<DeveloperModeContextType | undefined>(undefined);

export function DeveloperModeProvider({ children }: { children: ReactNode }) {
  const [isDeveloperMode, setIsDeveloperMode] = useState(false);
  const [currentMetadata, setCurrentMetadata] = useState<ComponentMetadata | null>(null);
  const [isConsoleExpanded, setIsConsoleExpanded] = useState(true);

  return (
    <DeveloperModeContext.Provider
      value={{
        isDeveloperMode,
        setIsDeveloperMode,
        currentMetadata,
        setCurrentMetadata,
        isConsoleExpanded,
        setIsConsoleExpanded,
      }}
    >
      {children}
    </DeveloperModeContext.Provider>
  );
}

export function useDeveloperMode() {
  const context = useContext(DeveloperModeContext);
  if (!context) {
    throw new Error('useDeveloperMode must be used within DeveloperModeProvider');
  }
  return context;
}
