import { useState, useEffect, useCallback } from 'react';
import { supportApi, Ticket, SupportMetrics, KnowledgeBaseArticle } from '@/services/supportApi';
import { useToast } from '@/hooks/use-toast';

export const useSupport = () => {
  const [tickets, setTickets] = useState<Ticket[]>([]);
  const [metrics, setMetrics] = useState<SupportMetrics | null>(null);
  const [knowledgeBase, setKnowledgeBase] = useState<KnowledgeBaseArticle[]>([]);
  const [chatSessions, setChatSessions] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const { toast } = useToast();

  // Load tickets
  const loadTickets = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      console.log('Loading support tickets...');
      
      const ticketsData = await supportApi.getTickets();
      setTickets(ticketsData);
      
      console.log(`Loaded ${ticketsData.length} tickets`);
      
      if (ticketsData.length === 0) {
        toast({
          title: "Info",
          description: "No hay tickets disponibles en este momento",
        });
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to load tickets';
      console.error('Error loading tickets:', errorMessage);
      setError(errorMessage);
      
      toast({
        title: "Error",
        description: "Error al cargar los tickets. Mostrando datos de demostración.",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  }, [toast]);

  // Load metrics
  const loadMetrics = useCallback(async () => {
    try {
      console.log('Loading support metrics...');
      const metricsData = await supportApi.getSupportMetrics();
      setMetrics(metricsData);
      console.log('Support metrics loaded:', metricsData);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to load metrics';
      console.error('Error loading metrics:', errorMessage);
    }
  }, []);

  // Load knowledge base
  const loadKnowledgeBase = useCallback(async () => {
    try {
      console.log('Loading knowledge base...');
      const kbData = await supportApi.getKnowledgeBase();
      setKnowledgeBase(kbData);
      console.log(`Loaded ${kbData.length} knowledge base articles`);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to load knowledge base';
      console.error('Error loading knowledge base:', errorMessage);
    }
  }, []);

  // Load chat sessions
  const loadChatSessions = useCallback(async () => {
    try {
      console.log('Loading chat sessions...');
      const chatData = await supportApi.getChatSessions();
      setChatSessions(chatData);
      console.log(`Loaded ${chatData.length} chat sessions`);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to load chat sessions';
      console.error('Error loading chat sessions:', errorMessage);
    }
  }, []);

  // Create ticket
  const createTicket = useCallback(async (ticketData: Omit<Ticket, 'id' | 'createdAt' | 'updatedAt' | 'responses'>) => {
    try {
      setLoading(true);
      console.log('Creating new ticket:', ticketData);
      
      const newTicket = await supportApi.createTicket(ticketData);
      setTickets(prev => [newTicket, ...prev]);
      
      toast({
        title: "Éxito",
        description: "Ticket creado correctamente",
      });
      
      return newTicket;
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to create ticket';
      console.error('Error creating ticket:', errorMessage);
      
      toast({
        title: "Error",
        description: "Error al crear el ticket",
        variant: "destructive",
      });
      
      throw err;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  // Update ticket status
  const updateTicketStatus = useCallback(async (ticketId: string, status: Ticket['status']) => {
    try {
      console.log(`Updating ticket ${ticketId} status to ${status}`);
      
      const updatedTicket = await supportApi.updateTicketStatus(ticketId, status);
      setTickets(prev => prev.map(ticket => 
        ticket.id === ticketId ? updatedTicket : ticket
      ));
      
      toast({
        title: "Éxito",
        description: "Estado del ticket actualizado",
      });
      
      return updatedTicket;
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to update ticket';
      console.error('Error updating ticket:', errorMessage);
      
      toast({
        title: "Error",
        description: "Error al actualizar el ticket",
        variant: "destructive",
      });
      
      throw err;
    }
  }, [toast]);

  // Add ticket response
  const addTicketResponse = useCallback(async (ticketId: string, message: string) => {
    try {
      console.log(`Adding response to ticket ${ticketId}`);
      
      const response = await supportApi.addTicketResponse(ticketId, message);
      
      setTickets(prev => prev.map(ticket => 
        ticket.id === ticketId 
          ? { ...ticket, responses: [...ticket.responses, response] }
          : ticket
      ));
      
      toast({
        title: "Éxito",
        description: "Respuesta añadida al ticket",
      });
      
      return response;
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to add response';
      console.error('Error adding response:', errorMessage);
      
      toast({
        title: "Error",
        description: "Error al añadir respuesta",
        variant: "destructive",
      });
      
      throw err;
    }
  }, [toast]);

  // Clear error
  const clearError = useCallback(() => {
    setError(null);
  }, []);

  // Initial load
  useEffect(() => {
    loadTickets();
    loadMetrics();
    loadKnowledgeBase();
    loadChatSessions();
  }, [loadTickets, loadMetrics, loadKnowledgeBase, loadChatSessions]);

  return {
    tickets,
    metrics,
    knowledgeBase,
    chatSessions,
    loading,
    error,
    loadTickets,
    loadMetrics,
    loadKnowledgeBase,
    loadChatSessions,
    createTicket,
    updateTicketStatus,
    addTicketResponse,
    clearError
  };
};