'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { apiClient, ApiClientError } from '@/lib/apiClient';
import type { ApiResponse } from '@/lib/types';
import type {
  GlossaryListItem,
  Glossary,
  GlossaryListResponse,
  GlossaryDetailResponse,
  GlossaryCreateInput,
  GlossaryUpdateInput,
} from './types';

const GLOSSARIES_QUERY_KEY = ['glossaries'];

export type GlossaryErrorCode = 
  | 'PRO_FEATURE_REQUIRED' 
  | 'TERMS_LIMIT_EXCEEDED' 
  | 'GLOSSARY_NOT_FOUND'
  | 'INVALID_GLOSSARY_ID'
  | 'UNAUTHORIZED';

export interface GlossaryTemplate {
  id: string;
  name: string;
  description: string;
  source_lang: string;
  target_lang: string;
  terms_count: number;
  file: string;
}

export interface GlossaryTemplatesResponse {
  data: GlossaryTemplate[];
  meta: { total: number };
}

export interface GlossaryError {
  status: number;
  code: GlossaryErrorCode;
  message: string;
}

interface UseGlossariesOptions {
  page?: number;
  perPage?: number;
}

export function useGlossaries(options: UseGlossariesOptions = {}) {
  const { page = 1, perPage = 50 } = options;
  const queryClient = useQueryClient();
  const router = useRouter();

  const {
    data: glossariesData,
    isLoading,
    error,
  } = useQuery<GlossaryListResponse, ApiClientError>({
    queryKey: [...GLOSSARIES_QUERY_KEY, page, perPage],
    queryFn: async () => {
      return apiClient.get<GlossaryListResponse>(`/api/v1/glossaries?page=${page}&per_page=${perPage}`);
    },
    retry: (failureCount, err) => {
      if (err.status === 403 || err.status === 401) return false;
      return failureCount < 2;
    },
  });

  // Handle 401 redirect
  if (error?.status === 401) {
    router.push('/auth/login');
  }

  const glossaries = glossariesData?.data ?? [];
  const total = glossariesData?.meta?.total ?? 0;

  const createMutation = useMutation({
    mutationFn: async (input: GlossaryCreateInput): Promise<Glossary> => {
      const response = await apiClient.post<GlossaryDetailResponse>('/api/v1/glossaries', input);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: GLOSSARIES_QUERY_KEY });
    },
  });

  const updateMutation = useMutation({
    mutationFn: async ({ id, data }: { id: string; data: GlossaryUpdateInput }): Promise<Glossary> => {
      const response = await apiClient.patch<GlossaryDetailResponse>(`/api/v1/glossaries/${id}`, data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: GLOSSARIES_QUERY_KEY });
    },
  });

  const deleteMutation = useMutation({
    mutationFn: async (id: string): Promise<void> => {
      await apiClient.delete(`/api/v1/glossaries/${id}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: GLOSSARIES_QUERY_KEY });
    },
  });

  const createGlossary = async (input: GlossaryCreateInput) => {
    return createMutation.mutateAsync(input);
  };

  const updateGlossary = async (id: string, data: GlossaryUpdateInput) => {
    return updateMutation.mutateAsync({ id, data });
  };

  const deleteGlossary = async (id: string) => {
    return deleteMutation.mutateAsync(id);
  };

  const importTemplateMutation = useMutation({
    mutationFn: async ({ templateId, name }: { templateId: string; name?: string }): Promise<Glossary> => {
      const params = new URLSearchParams({ template_id: templateId });
      if (name) params.set('name', name);
      const response = await apiClient.post<GlossaryDetailResponse>(
        `/api/v1/glossaries/import?${params.toString()}`
      );
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: GLOSSARIES_QUERY_KEY });
    },
  });

  const importTemplate = async (templateId: string, name?: string) => {
    return importTemplateMutation.mutateAsync({ templateId, name });
  };

  const parseError = (error: Error | null): GlossaryError | null => {
    if (!error) return null;
    
    const apiError = error as ApiClientError;
    const status = apiError.status || 500;
    const code = apiError.code as GlossaryErrorCode | string;
    const message = apiError.message;
    
    if (status === 401) {
      return { status: 401, code: 'UNAUTHORIZED', message: message || 'Session expired' };
    }
    if (status === 403 && code === 'PRO_FEATURE_REQUIRED') {
      return { status: 403, code: 'PRO_FEATURE_REQUIRED', message: message || 'Pro feature required' };
    }
    if (status === 400 && code === 'TERMS_LIMIT_EXCEEDED') {
      return { status: 400, code: 'TERMS_LIMIT_EXCEEDED', message: message || 'Maximum 500 terms per glossary' };
    }
    if (status === 404 && code === 'GLOSSARY_NOT_FOUND') {
      return { status: 404, code: 'GLOSSARY_NOT_FOUND', message: message || 'Glossary not found' };
    }
    if (status === 400 && code === 'INVALID_GLOSSARY_ID') {
      return { status: 400, code: 'INVALID_GLOSSARY_ID', message: message || 'Invalid glossary ID' };
    }
    
    return { status, code: code as GlossaryErrorCode, message };
  };

  return {
    glossaries,
    total,
    isLoading,
    error,
    errorDetails: parseError(error),
    isCreating: createMutation.isPending,
    isUpdating: updateMutation.isPending,
    isDeleting: deleteMutation.isPending,
    createGlossary,
    updateGlossary,
    deleteGlossary,
    createError: createMutation.error,
    updateError: updateMutation.error,
    deleteError: deleteMutation.error,
    isImportingTemplate: importTemplateMutation.isPending,
    importTemplateError: importTemplateMutation.error,
    parseCreateError: () => parseError(createMutation.error),
    parseUpdateError: () => parseError(updateMutation.error),
    parseDeleteError: () => parseError(deleteMutation.error),
    importTemplate,
  };
}

export function useGlossaryTemplates() {
  const { data, isLoading, error } = useQuery<GlossaryTemplatesResponse, ApiClientError>({
    queryKey: ['glossary-templates'],
    queryFn: async () => {
      return apiClient.get<GlossaryTemplatesResponse>('/api/v1/glossaries/templates/list');
    },
    staleTime: 5 * 60 * 1000, // templates rarely change
    retry: 1,
  });

  return {
    templates: data?.data ?? [],
    isLoading,
    error,
  };
}

export function useGlossary(id: string | null) {
  const {
    data,
    isLoading,
    error,
  } = useQuery<GlossaryDetailResponse, ApiClientError>({
    queryKey: [...GLOSSARIES_QUERY_KEY, id],
    queryFn: async () => {
      if (!id) throw new Error('Glossary ID is required');
      return apiClient.get<GlossaryDetailResponse>(`/api/v1/glossaries/${id}`);
    },
    enabled: !!id,
    retry: (failureCount, err) => {
      if (err.status === 403 || err.status === 404) return false;
      return failureCount < 2;
    },
  });

  const glossary = data?.data ?? null;

  return {
    glossary,
    isLoading,
    error,
  };
}
