'use client';

/**
 * 팝업관리 상세 클라이언트 컴포넌트 V2
 * IntegratedDetailTemplate 기반 마이그레이션
 */

import { useState, useEffect, useCallback } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { format } from 'date-fns';
import { IntegratedDetailTemplate } from '@/components/templates/IntegratedDetailTemplate';
import type { DetailMode } from '@/components/templates/IntegratedDetailTemplate/types';
import type { Popup, PopupFormData } from './types';
import { getPopupById, createPopup, updatePopup, deletePopup } from './actions';
import { popupDetailConfig, decodeTargetValue } from './popupDetailConfig';
import { toast } from 'sonner';

interface PopupDetailClientV2Props {
  popupId?: string;
  initialMode?: DetailMode;
}

// 로그인 사용자 이름을 가져오는 헬퍼
function getLoggedInUserName(): string {
  if (typeof window === 'undefined') return '';
  try {
    const userDataStr = localStorage.getItem('user');
    return userDataStr ? JSON.parse(userDataStr).name || '' : '';
  } catch { return ''; }
}

export function PopupDetailClientV2({ popupId, initialMode }: PopupDetailClientV2Props) {
  const router = useRouter();
  const searchParams = useSearchParams();

  // URL 쿼리에서 모드 결정
  const modeFromQuery = searchParams.get('mode') as DetailMode | null;
  const isNewMode = !popupId || popupId === 'new';

  const [mode, setMode] = useState<DetailMode>(() => {
    if (isNewMode) return 'create';
    if (initialMode) return initialMode;
    if (modeFromQuery === 'edit') return 'edit';
    return 'view';
  });

  const [popupData, setPopupData] = useState<Popup | null>(null);
  const [isLoading, setIsLoading] = useState(!isNewMode);

  // 데이터 로드
  useEffect(() => {
    const loadData = async () => {
      if (isNewMode) {
        setIsLoading(false);
        return;
      }

      setIsLoading(true);
      try {
        const data = await getPopupById(popupId!);
        if (data) {
          setPopupData(data);
        } else {
          toast.error('팝업을 불러오는데 실패했습니다.');
          router.push(popupDetailConfig.basePath);
        }
      } catch (error) {
        console.error('팝업 조회 실패:', error);
        toast.error('팝업을 불러오는데 실패했습니다.');
        router.push(popupDetailConfig.basePath);
      } finally {
        setIsLoading(false);
      }
    };

    loadData();
  }, [popupId, isNewMode, router]);

  // URL 쿼리 변경 감지
  useEffect(() => {
    if (!isNewMode && modeFromQuery === 'edit') {
      setMode('edit');
    } else if (!isNewMode && !modeFromQuery) {
      setMode('view');
    }
  }, [modeFromQuery, isNewMode]);

  // 모드 변경 핸들러
  const handleModeChange = useCallback(
    (newMode: DetailMode) => {
      setMode(newMode);
      if (newMode === 'edit' && popupId) {
        router.push(`${popupDetailConfig.basePath}/${popupId}?mode=edit`);
      } else if (newMode === 'view' && popupId) {
        router.push(`${popupDetailConfig.basePath}/${popupId}?mode=view`);
      }
    },
    [router, popupId]
  );

  // 저장 핸들러
  const handleSubmit = useCallback(
    async (formData: Record<string, unknown>) => {
      try {
        const { targetType, departmentId } = decodeTargetValue((formData.target as string) || 'all');
        const popupFormData: PopupFormData = {
          target: targetType,
          targetDepartmentId: departmentId ? String(departmentId) : undefined,
          title: formData.title as string,
          content: formData.content as string,
          status: (formData.status as PopupFormData['status']) || 'inactive',
          startDate: formData.startDate as string,
          endDate: formData.endDate as string,
        };

        if (isNewMode) {
          const result = await createPopup(popupFormData);
          if (result.success) {
            toast.success('팝업이 등록되었습니다.');
            router.push(popupDetailConfig.basePath);
            return { success: true };
          }
          return { success: false, error: result.error || '팝업 등록에 실패했습니다.' };
        } else {
          const result = await updatePopup(popupId!, popupFormData);
          if (result.success) {
            toast.success('팝업이 수정되었습니다.');
            router.push(`${popupDetailConfig.basePath}/${popupId}?mode=view`);
            return { success: true };
          }
          return { success: false, error: result.error || '팝업 수정에 실패했습니다.' };
        }
      } catch (error) {
        console.error('저장 실패:', error);
        return { success: false, error: error instanceof Error ? error.message : '저장 중 오류가 발생했습니다.' };
      }
    },
    [isNewMode, popupId, router]
  );

  // 삭제 핸들러
  const handleDelete = useCallback(
    async (id: string | number) => {
      try {
        const result = await deletePopup(String(id));
        if (result.success) {
          toast.success('팝업이 삭제되었습니다.');
          router.push(popupDetailConfig.basePath);
          return { success: true };
        }
        return { success: false, error: result.error || '팝업 삭제에 실패했습니다.' };
      } catch (error) {
        console.error('삭제 실패:', error);
        return { success: false, error: error instanceof Error ? error.message : '삭제 중 오류가 발생했습니다.' };
      }
    },
    [router]
  );

  // 취소 핸들러
  const handleCancel = useCallback(() => {
    if (isNewMode) {
      router.push(popupDetailConfig.basePath);
    } else {
      setMode('view');
      router.push(`${popupDetailConfig.basePath}/${popupId}?mode=view`);
    }
  }, [router, popupId, isNewMode]);

  // 초기 데이터 (신규 등록 시 기본값 포함)
  const initialData = isNewMode
    ? ({
        target: 'all',
        status: 'inactive',
        author: getLoggedInUserName(),
        createdAt: format(new Date(), 'yyyy-MM-dd HH:mm'),
        startDate: format(new Date(), 'yyyy-MM-dd'),
        endDate: format(new Date(), 'yyyy-MM-dd'),
      } as unknown as Popup)
    : popupData || undefined;

  // 타이틀 동적 설정
  // IntegratedDetailTemplate: create → "{title} 등록", view → "{title}", edit → "{title} 수정"
  // view 모드에서 "팝업 상세"로 표시하려면 직접 설정 필요
  const dynamicConfig = {
    ...popupDetailConfig,
    title: mode === 'view' ? '팝업 상세' : '팝업',
  };

  return (
    <IntegratedDetailTemplate
      config={dynamicConfig}
      mode={mode}
      initialData={initialData as Record<string, unknown> | undefined}
      itemId={popupId}
      isLoading={isLoading}
      onSubmit={handleSubmit}
      onDelete={handleDelete}
      onCancel={handleCancel}
      onModeChange={handleModeChange}
    />
  );
}
