import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiClient } from '@/lib/api-client';
import type { SeatClass, CoachType, Route, RouteFareRule, SegmentFareRule, BaggageAllowance } from './types';

function toArray<T>(data: unknown): T[] {
  if (Array.isArray(data)) return data as T[];
  const d = data as any;
  return d?.items ?? d?.data ?? [];
}

export function useSeatClasses() {
  const { data, isLoading } = useQuery({
    queryKey: ['seat-classes'],
    queryFn: () => apiClient.get<unknown>('/seat-classes'),
  });
  return { allClasses: toArray<SeatClass>(data), isLoading };
}

export function useCoachTypes() {
  const { data } = useQuery({
    queryKey: ['coach-types'],
    queryFn: () => apiClient.get<unknown>('/fleet/coach-types'),
  });
  return { coachTypes: toArray<CoachType>(data) };
}

export function useRoutes() {
  const { data } = useQuery({
    queryKey: ['routes-active'],
    queryFn: () => apiClient.get<unknown>('/routes?activeOnly=true'),
  });
  return { routes: toArray<Route>(data) };
}

export function useSegmentFareRules(routeId: string | null) {
  const { data, isLoading, refetch } = useQuery({
    queryKey: ['segment-fare-rules', routeId],
    queryFn: () => apiClient.get<unknown>(`/schedules/routes/${routeId}/segment-fares`),
    enabled: !!routeId,
  });
  return { segmentFares: toArray<SegmentFareRule>(data), isLoading, refetch };
}

export function useSegmentFareMutations(routeId: string | null) {
  const queryClient = useQueryClient();
  const invalidate = () => queryClient.invalidateQueries({ queryKey: ['segment-fare-rules', routeId] });

  const create = useMutation({
    mutationFn: (data: any) => apiClient.post('/schedules/segment-fares', data),
    onSuccess: invalidate,
  });
  const update = useMutation({
    mutationFn: ({ id, ...data }: any) => apiClient.patch(`/schedules/segment-fares/${id}`, data),
    onSuccess: invalidate,
  });
  const remove = useMutation({
    mutationFn: (id: string) => apiClient.delete(`/schedules/segment-fares/${id}`),
    onSuccess: invalidate,
  });

  return { create, update, remove };
}

export function useRouteFareRules(routeId: string | null) {
  const { data, isLoading, refetch } = useQuery({
    queryKey: ['route-fare-rules', routeId],
    queryFn: () => apiClient.get<unknown>(`/schedules/routes/${routeId}/fare-rules`),
    enabled: !!routeId,
  });
  return { overrides: toArray<RouteFareRule>(data), isLoading, refetch };
}

export function useSeatClassMutations(onSuccess: () => void) {
  const queryClient = useQueryClient();
  const invalidate = () => queryClient.invalidateQueries({ queryKey: ['seat-classes'] });

  const create = useMutation({
    mutationFn: (data: any) => apiClient.post('/seat-classes', data),
    onSuccess: () => { invalidate(); onSuccess(); },
  });
  const update = useMutation({
    mutationFn: ({ id, data }: { id: string; data: any }) => apiClient.patch(`/seat-classes/${id}`, data),
    onSuccess: () => { invalidate(); onSuccess(); },
  });
  const remove = useMutation({
    mutationFn: ({ id, cascade }: { id: string; cascade?: boolean }) =>
      apiClient.delete(`/seat-classes/${id}${cascade ? '?cascade=true' : ''}`),
    onSuccess: invalidate,
  });

  return { create, update, remove };
}

export function useRouteFareRuleMutations(routeId: string | null) {
  const queryClient = useQueryClient();
  const invalidate = (rid?: string) =>
    queryClient.invalidateQueries({ queryKey: ['route-fare-rules', rid ?? routeId] });

  const create = useMutation({
    mutationFn: ({ routeId: rid, ...data }: any) => apiClient.post(`/schedules/routes/${rid}/fare-rules`, data),
    onSuccess: (_: any, vars: any) => invalidate(vars.routeId),
  });
  const update = useMutation({
    mutationFn: ({ id, ...data }: any) => apiClient.patch<any>(`/schedules/routes/fare-rules/${id}`, data),
    onSuccess: invalidate,
  });
  const remove = useMutation({
    mutationFn: (id: string) => apiClient.delete<any>(`/schedules/routes/fare-rules/${id}`),
    onSuccess: invalidate,
  });

  return { create, update, remove };
}

export function useBaggageMutations() {
  const { data, isLoading, refetch } = useQuery({
    queryKey: ['baggage-allowances'],
    queryFn: () => apiClient.get<unknown>('/agents/excess-baggage/allowances'),
  });

  const create = useMutation({
    mutationFn: (data: any) => apiClient.post('/agents/excess-baggage/allowances', data),
    onSuccess: () => refetch(),
  });
  const update = useMutation({
    mutationFn: ({ id, ...data }: any) => apiClient.patch(`/agents/excess-baggage/allowances/${id}`, data),
    onSuccess: () => refetch(),
  });
  const remove = useMutation({
    mutationFn: (id: string) => apiClient.delete(`/agents/excess-baggage/allowances/${id}`),
    onSuccess: () => refetch(),
  });

  return { allowances: toArray<BaggageAllowance>(data), isLoading, create, update, remove };
}
