import axios from 'axios';
import { GlobalFunctions } from '@/GlobalFunctions';

export interface UserProfile {
  success: boolean;
  id?: string;
  nome: string;
  email: string;
  whatsapp: string;
  followup: boolean;
  message?: string;
}

export interface CreateUserRequest {
  nome: string;
  email: string;
  whatsapp: string;
  followup: boolean;
}

export interface UpdateUserRequest {
  nome: string;
  whatsapp: string;
  followup: boolean;
}

export interface FinancialIndicators {
  success: boolean;
  id: string;
  nome: string;
  email: string;
  total_despesas: string;
  total_corporativo: string;
  total_pessoal: string;
  message?: string;
}

export interface ExpenseItem {
  id: string;
  data_hora: string;
  descricao: string;
  tipo: 'pessoal' | 'corporativo';
  valor: string;
  categoria_id: number;
  categoria_nome: string;
  usuario_nome: string;
  usuario_email: string;
}

export interface ExpensesResponse {
  success: boolean;
  total_registros: number;
  total_paginas: number;
  per_page: number;
  pagina_atual: number;
  data: ExpenseItem[];
}

export interface ExpensesFilters {
  page?: number;
  per_page?: number;
  descricao?: string;
  categoria_id?: number;
  data_inicial?: string;
  data_final?: string;
}

export interface ExpenseCategory {
  id: number;
  nome: string;
  descricao: string;
  criado_em: string;
  atualizado_em: string;
}

type AxiosLikeError = { response?: { data?: unknown; status?: number } };

class PersonalAgent {
  private async buildHeaders(): Promise<Record<string, string>> {
    const token = await GlobalFunctions.getToken();
    const apiKey = import.meta.env.VITE_API_KEY || '';
    const headers: Record<string, string> = { 'Content-Type': 'application/json' };
    if (apiKey) headers['apikey'] = apiKey;
    if (token) headers['Authorization'] = `Bearer ${token}`;
    return headers;
  }

  private resolveEmail(userEmail?: string): string {
    return userEmail || GlobalFunctions.getUsuarioLogado().email;
  }

  private handleError(error: unknown, fallback: string): never {
    const e = error as AxiosLikeError;
    if (e?.response?.data) throw e.response.data;
    throw {
      success: false,
      message: error instanceof Error ? error.message : fallback,
      status: e?.response?.status,
    };
  }

  async getUserProfile(userEmail?: string): Promise<UserProfile> {
    const email = this.resolveEmail(userEmail);
    if (!email) throw { success: false, message: 'Email do usuário não fornecido' };

    try {
      const headers = await this.buildHeaders();
      const response = await axios.get<UserProfile>(
        `https://prod-hgtx-intelligence-n8n.hgtx.com.br/webhook/2299acaf-70ee-47e3-a6fc-56dcc678d651/codex/agente-pessoal/user/${email}`,
        { headers }
      );
      return response.data;
    } catch (error: unknown) {
      const e = error as AxiosLikeError;
      if (e?.response?.data) return e.response.data as UserProfile;
      throw { success: false, message: error instanceof Error ? error.message : 'Erro ao buscar perfil do usuário', status: e?.response?.status };
    }
  }

  async createUser(request: CreateUserRequest): Promise<UserProfile> {
    if (!request.nome?.trim()) throw { success: false, message: 'Nome é obrigatório' };
    if (!request.email?.trim()) throw { success: false, message: 'Email é obrigatório' };
    if (!request.whatsapp?.trim()) throw { success: false, message: 'WhatsApp é obrigatório' };

    try {
      const headers = await this.buildHeaders();
      const response = await axios.post<UserProfile>(
        'https://prod-hgtx-intelligence-n8n.hgtx.com.br/webhook/codex/agente-pessoal/user',
        {
          nome: request.nome.trim(),
          email: request.email.trim(),
          whatsapp: request.whatsapp.replace(/\D/g, ''),
          followup: request.followup,
        },
        { headers }
      );
      return response.data;
    } catch (error: unknown) {
      this.handleError(error, 'Erro ao criar usuário');
    }
  }

  async updateUser(userId: string, request: UpdateUserRequest): Promise<UserProfile> {
    if (!userId?.trim()) throw { success: false, message: 'ID do usuário é obrigatório' };
    if (!request.nome?.trim()) throw { success: false, message: 'Nome é obrigatório' };
    if (!request.whatsapp?.trim()) throw { success: false, message: 'WhatsApp é obrigatório' };

    try {
      const headers = await this.buildHeaders();
      const response = await axios.post<UserProfile>(
        `https://prod-hgtx-intelligence-n8n.hgtx.com.br/webhook/2299acaf-70ee-47e3-a6fc-56dcc678d651/codex/agente-pessoal/user/${userId}`,
        {
          nome: request.nome.trim(),
          whatsapp: request.whatsapp.replace(/\D/g, ''),
          followup: request.followup,
        },
        { headers }
      );
      return response.data;
    } catch (error: unknown) {
      this.handleError(error, 'Erro ao atualizar usuário');
    }
  }

  async getFinancialIndicators(userEmail?: string): Promise<FinancialIndicators> {
    const email = this.resolveEmail(userEmail);
    if (!email) throw { success: false, message: 'Email do usuário é obrigatório' };

    try {
      const headers = await this.buildHeaders();
      const response = await axios.get<FinancialIndicators>(
        `https://prod-hgtx-intelligence-n8n.hgtx.com.br/webhook/2299acaf-70ee-47e3-a6fc-56dcc678d651/codex/agente-pessoal/financas/indicadores/${email}`,
        { headers }
      );
      return response.data;
    } catch (error: unknown) {
      this.handleError(error, 'Erro ao buscar indicadores financeiros');
    }
  }

  async getExpenses(userEmail?: string, filters?: ExpensesFilters): Promise<ExpensesResponse> {
    const email = this.resolveEmail(userEmail);
    if (!email) throw { success: false, message: 'Email do usuário é obrigatório' };

    const empty: ExpensesResponse = {
      success: true,
      total_registros: 0,
      total_paginas: 0,
      per_page: filters?.per_page || 10,
      pagina_atual: filters?.page || 1,
      data: [],
    };

    try {
      const headers = await this.buildHeaders();
      const params = new URLSearchParams();
      if (filters?.page) params.append('page', filters.page.toString());
      if (filters?.per_page) params.append('per_page', filters.per_page.toString());
      if (filters?.descricao) params.append('descricao', filters.descricao);
      if (filters?.categoria_id) params.append('categoria_id', filters.categoria_id.toString());
      if (filters?.data_inicial) params.append('data_inicial', filters.data_inicial);
      if (filters?.data_final) params.append('data_final', filters.data_final);

      const qs = params.toString();
      const url = `https://prod-hgtx-intelligence-n8n.hgtx.com.br/webhook/2299acaf-70ee-47e3-a6fc-56dcc678d651/codex/agente-pessoal/financas/${email}${qs ? `?${qs}` : ''}`;

      const response = await axios.get<ExpensesResponse[]>(url, { headers });

      if (!Array.isArray(response.data) || response.data.length === 0) return empty;

      const result = response.data[0];
      result.data = Array.isArray(result.data) ? result.data.filter((item) => item && item.id) : [];
      if (result.data.length === 0) {
        result.total_registros = 0;
        result.total_paginas = 0;
      }
      return result;
    } catch (error: unknown) {
      this.handleError(error, 'Erro ao buscar despesas');
    }
  }

  async getCategories(): Promise<ExpenseCategory[]> {
    try {
      const headers = await this.buildHeaders();
      const response = await axios.get<ExpenseCategory[]>(
        'https://prod-hgtx-intelligence-n8n.hgtx.com.br/webhook/codex/agente-pessoal/categorias',
        { headers }
      );
      return Array.isArray(response.data) ? response.data : [];
    } catch (error: unknown) {
      console.error('Erro ao buscar categorias:', error);
      return [];
    }
  }
}

export const personalAgent = new PersonalAgent();
