import React, { createContext, useContext, ReactNode } from 'react';
import { useQuery } from '@tanstack/react-query';
import { areaClient, areaClientManager } from '../../api/areaClient';
import type { InferResponseType } from 'hono/client';

// 类型定义 - 使用areaClient进行类型推断
type AreaResponse = InferResponseType<typeof areaClient.index.$get, 200>['data'][0];

interface AreaContextValue {
  // 数据获取函数
  getProvinces: () => Promise<AreaResponse[]>;
  getCities: (provinceId: number) => Promise<AreaResponse[]>;
  getDistricts: (cityId: number) => Promise<AreaResponse[]>;
  getTowns: (districtId: number) => Promise<AreaResponse[]>;

  // 缓存数据
  provinces?: AreaResponse[];
  cities?: AreaResponse[];
  districts?: AreaResponse[];
  towns?: AreaResponse[];

  // 加载状态
  isLoadingProvinces: boolean;
  isLoadingCities: boolean;
  isLoadingDistricts: boolean;
  isLoadingTowns: boolean;
}

const AreaContext = createContext<AreaContextValue | undefined>(undefined);

interface AreaProviderProps {
  children: ReactNode;
}

export const AreaProvider: React.FC<AreaProviderProps> = ({ children }) => {
  // 查询省份列表
  const { data: provinces, isLoading: isLoadingProvinces } = useQuery({
    queryKey: ['areas', 'provinces'],
    queryFn: async () => {
      const res = await areaClientManager.get().index.$get({
        query: {
          page: 1,
          pageSize: 100,
          filters: JSON.stringify({
            level: 1,
            isDisabled: 0
          }),
          sortBy: 'id',
          sortOrder: 'ASC'
        }
      });
      if (res.status !== 200) throw new Error('获取省份列表失败');
      const json = await res.json();
      return json.data;
    },
    staleTime: 10 * 60 * 1000,
    gcTime: 30 * 60 * 1000,
  });

  // 获取城市列表的函数
  const getCities = async (provinceId: number): Promise<AreaResponse[]> => {
    if (!provinceId) return [];

    const res = await areaClientManager.get().index.$get({
      query: {
        page: 1,
        pageSize: 100,
        filters: JSON.stringify({
          level: 2,
          parentId: provinceId,
          isDisabled: 0
        }),
        sortBy: 'id',
        sortOrder: 'ASC'
      }
    });

    if (res.status !== 200) throw new Error('获取城市列表失败');
    const json = await res.json();
    return json.data;
  };

  // 获取区县列表的函数
  const getDistricts = async (cityId: number): Promise<AreaResponse[]> => {
    if (!cityId) return [];

    const res = await areaClientManager.get().index.$get({
      query: {
        page: 1,
        pageSize: 100,
        filters: JSON.stringify({
          level: 3,
          parentId: cityId,
          isDisabled: 0
        }),
        sortBy: 'id',
        sortOrder: 'ASC'
      }
    });

    if (res.status !== 200) throw new Error('获取区县列表失败');
    const json = await res.json();
    return json.data;
  };

  // 获取街道列表的函数
  const getTowns = async (districtId: number): Promise<AreaResponse[]> => {
    if (!districtId) return [];

    const res = await areaClientManager.get().index.$get({
      query: {
        page: 1,
        pageSize: 100,
        filters: JSON.stringify({
          level: 4,
          parentId: districtId,
          isDisabled: 0
        }),
        sortBy: 'id',
        sortOrder: 'ASC'
      }
    });

    if (res.status !== 200) throw new Error('获取街道列表失败');
    const json = await res.json();
    return json.data;
  };

  const value: AreaContextValue = {
    getProvinces: async () => provinces || [],
    getCities,
    getDistricts,
    getTowns,
    provinces,
    isLoadingProvinces,
    isLoadingCities: false, // 这些状态由具体组件管理
    isLoadingDistricts: false,
    isLoadingTowns: false,
  };

  return (
    <AreaContext.Provider value={value}>
      {children}
    </AreaContext.Provider>
  );
};

export const useAreaContext = () => {
  const context = useContext(AreaContext);
  if (!context) {
    throw new Error('useAreaContext必须在AreaProvider内部使用');
  }
  return context;
};