"use client";

import { useState, useEffect, useCallback } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { apiClient } from "@/lib/api/client";

// 웹타입 데이터 인터페이스
export interface WebTypeStandard {
  web_type: string;
  type_name: string;
  type_name_eng?: string;
  description?: string;
  category: string;
  component_name?: string;
  config_panel?: string;
  default_config?: any;
  validation_rules?: any;
  default_style?: any;
  input_properties?: any;
  sort_order?: number;
  is_active: string;
  created_date?: string;
  created_by?: string;
  updated_date?: string;
  updated_by?: string;
}

// 웹타입 생성/수정 데이터
export interface WebTypeFormData {
  web_type: string;
  type_name: string;
  type_name_eng?: string;
  description?: string;
  category: string;
  component_name?: string;
  config_panel?: string;
  default_config?: any;
  validation_rules?: any;
  default_style?: any;
  input_properties?: any;
  sort_order?: number;
  is_active?: string;
}

// API 응답 인터페이스
interface ApiResponse<T> {
  success: boolean;
  data?: T;
  message?: string;
  error?: string;
}

// 쿼리 파라미터 인터페이스
interface WebTypeQueryParams {
  active?: string;
  category?: string;
  search?: string;
}

/**
 * 웹타입 관리 훅
 */
export const useWebTypes = (params?: WebTypeQueryParams) => {
  const queryClient = useQueryClient();

  // 웹타입 목록 조회
  const {
    data: webTypes,
    isLoading,
    error,
    refetch,
  } = useQuery({
    queryKey: ["webTypes", params],
    queryFn: async (): Promise<WebTypeStandard[]> => {
      const searchParams = new URLSearchParams();

      if (params?.active) searchParams.append("active", params.active);
      if (params?.category) searchParams.append("category", params.category);
      if (params?.search) searchParams.append("search", params.search);

      const response = await apiClient.get(`/admin/web-types?${searchParams.toString()}`);

      const result: ApiResponse<WebTypeStandard[]> = response.data;

      if (!result.success) {
        throw new Error(result.error || "Failed to fetch web types");
      }

      return result.data || [];
    },
    staleTime: 5 * 60 * 1000,
    gcTime: 10 * 60 * 1000,
  });

  // 웹타입 생성
  const createWebTypeMutation = useMutation({
    mutationFn: async (data: WebTypeFormData): Promise<WebTypeStandard> => {
      const response = await apiClient.post("/admin/web-types", data);

      const result: ApiResponse<WebTypeStandard> = response.data;

      if (!result.success) {
        throw new Error(result.error || "Failed to create web type");
      }

      return result.data!;
    },
    onSuccess: () => {
      // 목록 새로고침
      queryClient.invalidateQueries({ queryKey: ["webTypes"] });
    },
  });

  // 웹타입 수정
  const updateWebTypeMutation = useMutation({
    mutationFn: async ({
      webType,
      data,
    }: {
      webType: string;
      data: Partial<WebTypeFormData>;
    }): Promise<WebTypeStandard> => {
      const response = await apiClient.put(`/admin/web-types/${webType}`, data);

      const result: ApiResponse<WebTypeStandard> = response.data;

      if (!result.success) {
        throw new Error(result.error || "Failed to update web type");
      }

      return result.data!;
    },
    onSuccess: () => {
      // 목록 새로고침
      queryClient.invalidateQueries({ queryKey: ["webTypes"] });
    },
  });

  // 웹타입 삭제
  const deleteWebTypeMutation = useMutation({
    mutationFn: async (webType: string): Promise<void> => {
      const response = await apiClient.delete(`/admin/web-types/${webType}`);

      const result: ApiResponse<void> = response.data;

      if (!result.success) {
        throw new Error(result.error || "Failed to delete web type");
      }
    },
    onSuccess: () => {
      // 목록 새로고침
      queryClient.invalidateQueries({ queryKey: ["webTypes"] });
    },
  });

  // 정렬 순서 업데이트
  const updateSortOrderMutation = useMutation({
    mutationFn: async (webTypes: { web_type: string; sort_order: number }[]): Promise<void> => {
      const response = await apiClient.put("/admin/web-types/sort-order/bulk", { webTypes });

      const result: ApiResponse<void> = response.data;

      if (!result.success) {
        throw new Error(result.error || "Failed to update sort order");
      }
    },
    onSuccess: () => {
      // 목록 새로고침
      queryClient.invalidateQueries({ queryKey: ["webTypes"] });
    },
  });

  // 편의 메서드들
  const createWebType = useCallback(
    (data: WebTypeFormData) => {
      return createWebTypeMutation.mutateAsync(data);
    },
    [createWebTypeMutation],
  );

  const updateWebType = useCallback(
    (webType: string, data: Partial<WebTypeFormData>) => {
      return updateWebTypeMutation.mutateAsync({ webType, data });
    },
    [updateWebTypeMutation],
  );

  const deleteWebType = useCallback(
    (webType: string) => {
      return deleteWebTypeMutation.mutateAsync(webType);
    },
    [deleteWebTypeMutation],
  );

  const updateSortOrder = useCallback(
    (webTypes: { web_type: string; sort_order: number }[]) => {
      return updateSortOrderMutation.mutateAsync(webTypes);
    },
    [updateSortOrderMutation],
  );

  return {
    // 데이터
    webTypes: webTypes || [],

    // 로딩 상태
    isLoading,
    isCreating: createWebTypeMutation.isPending,
    isUpdating: updateWebTypeMutation.isPending,
    isDeleting: deleteWebTypeMutation.isPending,
    isSortingUpdating: updateSortOrderMutation.isPending,

    // 에러
    error,
    createError: createWebTypeMutation.error,
    updateError: updateWebTypeMutation.error,
    deleteError: deleteWebTypeMutation.error,
    sortError: updateSortOrderMutation.error,

    // 액션
    createWebType,
    updateWebType,
    deleteWebType,
    updateSortOrder,
    refetch,

    // 상태 초기화
    resetCreateError: createWebTypeMutation.reset,
    resetUpdateError: updateWebTypeMutation.reset,
    resetDeleteError: deleteWebTypeMutation.reset,
    resetSortError: updateSortOrderMutation.reset,
  };
};
