import { useState, useCallback } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/contexts/AuthContext';
import { toast } from 'sonner';

export interface Conversation {
  id: string;
  title: string;
  created_at: string;
  updated_at: string;
  dify_conversation_id?: string;
}

export interface Message {
  id: string;
  content: string;
  sender_type: 'user' | 'ai';
  message_type: 'text' | 'product' | 'products' | 'order' | 'after_sales' | 'agent_intro';
  metadata?: any;
  created_at: string;
}

type LocalConversationStore = {
  conversations: Conversation[];
  messages: Record<string, Message[]>;
};

const LOCAL_CONVERSATION_STORE_KEY = 'qianjiang_guest_conversations_v1';

const createLocalId = (_prefix: string) => {
  try {
    if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
      return crypto.randomUUID();
    }
  } catch { /* 非 HTTPS 环境，使用降级方案 */ }
  // Fallback: 生成合法 UUID v4 格式（与 makeUUID 一致，保证 DB 兼容）
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    const r = Math.random() * 16 | 0;
    return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
};

const readLocalStore = (): LocalConversationStore => {
  if (typeof window === 'undefined') {
    return { conversations: [], messages: {} };
  }

  try {
    const raw = window.localStorage.getItem(LOCAL_CONVERSATION_STORE_KEY);
    if (!raw) return { conversations: [], messages: {} };

    const parsed = JSON.parse(raw) as Partial<LocalConversationStore>;
    return {
      conversations: Array.isArray(parsed.conversations) ? parsed.conversations : [],
      messages: parsed.messages && typeof parsed.messages === 'object' ? parsed.messages : {},
    };
  } catch (error) {
    console.warn('读取本地访客对话失败:', error);
    return { conversations: [], messages: {} };
  }
};

const writeLocalStore = (store: LocalConversationStore) => {
  if (typeof window === 'undefined') return;

  try {
    window.localStorage.setItem(LOCAL_CONVERSATION_STORE_KEY, JSON.stringify(store));
  } catch (error) {
    console.warn('保存本地访客对话失败:', error);
  }
};

const sortConversations = (conversations: Conversation[]) =>
  [...conversations].sort((a, b) => new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime());

export const useConversations = () => {
  const { user } = useAuth();
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [currentConversationId, setCurrentConversationId] = useState<string | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [isLoading] = useState(false);

  // 获取对话列表
  const fetchConversations = useCallback(async () => {
    if (!user) {
      const store = readLocalStore();
      const localConversations = sortConversations(store.conversations);
      setConversations(localConversations);
      return localConversations;
    }
    
    try {
      const { data, error } = await supabase
        .from('conversations')
        .select('*, messages(id)')
        .eq('user_id', user.id)
        .order('updated_at', { ascending: false });
      
      if (error) throw error;
      
      // 过滤掉没有消息的空白对话
      const conversationsWithMessages = (data || []).filter(
        (conv: any) => conv.messages && conv.messages.length > 0
      );
      
      // 删除空白对话
      const emptyConversations = (data || []).filter(
        (conv: any) => !conv.messages || conv.messages.length === 0
      );
      
      if (emptyConversations.length > 0) {
        for (const conv of emptyConversations) {
          await supabase
            .from('conversations')
            .delete()
            .eq('id', conv.id)
            .eq('user_id', user.id);
        }
      }
      
      const cleanConversations = conversationsWithMessages.map((conv: any) => ({
        id: conv.id,
        title: conv.title,
        created_at: conv.created_at,
        updated_at: conv.updated_at,
        dify_conversation_id: conv.dify_conversation_id
      }));
      
      setConversations(cleanConversations);
      return cleanConversations;
    } catch (error) {
      console.error('获取对话列表失败:', error);
      return [];
    }
  }, [user]);

  // 获取消息记录
  const fetchMessages = useCallback(async (conversationId: string) => {
    if (!user) {
      const localMessages = readLocalStore().messages[conversationId] || [];
      setMessages(localMessages);
      return localMessages;
    }
    
    try {
      const { data, error } = await supabase
        .from('messages')
        .select('*')
        .eq('conversation_id', conversationId)
        .eq('user_id', user.id)
        .order('created_at', { ascending: true });
      
      if (error) throw error;
      
      const formattedMessages: Message[] = (data || []).map(msg => ({
        id: msg.id,
        content: msg.content,
        sender_type: msg.sender_type as 'user' | 'ai',
        message_type: msg.message_type as Message['message_type'],
        metadata: msg.metadata,
        created_at: msg.created_at
      }));
      
      setMessages(formattedMessages);
      return formattedMessages;
    } catch (error) {
      console.error('获取消息记录失败:', error);
      return [];
    }
  }, [user]);

  // 创建新对话
  const createConversation = useCallback(async (title: string = 'New Conversation') => {
    if (!user) {
      const now = new Date().toISOString();
      const localConversation: Conversation = {
        id: createLocalId('conversation'),
        title,
        created_at: now,
        updated_at: now,
      };
      const store = readLocalStore();
      const nextConversations = sortConversations([localConversation, ...store.conversations]);

      writeLocalStore({ ...store, conversations: nextConversations, messages: { ...store.messages, [localConversation.id]: [] } });
      setConversations(nextConversations);
      setCurrentConversationId(localConversation.id);
      setMessages([]);

      return localConversation;
    }
    
    try {
      const { data, error } = await supabase
        .from('conversations')
        .insert([
          {
            user_id: user.id,
            title: title
          }
        ])
        .select()
        .single();
      
      if (error) throw error;
      
      setConversations(prev => [data, ...prev]);
      setCurrentConversationId(data.id);
      setMessages([]);
      
      return data;
    } catch (error) {
      console.error('创建对话失败:', error);
      toast.error('创建对话失败');
      return null;
    }
  }, [user]);

  // 更新对话
  const updateConversation = useCallback(async (
    conversationId: string, 
    updates: Partial<Conversation>
  ) => {
    if (!user) {
      const store = readLocalStore();
      const nextConversations = sortConversations(store.conversations.map(conv =>
        conv.id === conversationId ? { ...conv, ...updates, updated_at: updates.updated_at || new Date().toISOString() } : conv
      ));

      writeLocalStore({ ...store, conversations: nextConversations });
      setConversations(nextConversations);
      return true;
    }
    
    try {
      const { error } = await supabase
        .from('conversations')
        .update(updates)
        .eq('id', conversationId)
        .eq('user_id', user.id);
      
      if (error) throw error;
      
      setConversations(prev => prev.map(conv => 
        conv.id === conversationId ? { ...conv, ...updates } : conv
      ));
      
      return true;
    } catch (error) {
      console.error('更新对话失败:', error);
      return false;
    }
  }, [user]);

  // 删除对话
  const deleteConversation = useCallback(async (conversationId: string) => {
    if (!user) {
      const store = readLocalStore();
      const { [conversationId]: _, ...remainingMessages } = store.messages;
      const remainingConversations = sortConversations(store.conversations.filter(conv => conv.id !== conversationId));

      writeLocalStore({ conversations: remainingConversations, messages: remainingMessages });
      setConversations(remainingConversations);

      if (currentConversationId === conversationId) {
        if (remainingConversations.length > 0) {
          setCurrentConversationId(remainingConversations[0].id);
          setMessages(remainingMessages[remainingConversations[0].id] || []);
        } else {
          setCurrentConversationId(null);
          setMessages([]);
        }
      }

      toast.success('对话删除成功');
      return true;
    }
    
    try {
      // 先删除对话中的消息
      await supabase
        .from('messages')
        .delete()
        .eq('conversation_id', conversationId)
        .eq('user_id', user.id);
      
      // 再删除对话
      const { error } = await supabase
        .from('conversations')
        .delete()
        .eq('id', conversationId)
        .eq('user_id', user.id);
      
      if (error) throw error;
      
      setConversations(prev => prev.filter(conv => conv.id !== conversationId));
      
      // 如果删除的是当前对话，重置状态
      if (currentConversationId === conversationId) {
        const remainingConversations = conversations.filter(conv => conv.id !== conversationId);
        if (remainingConversations.length > 0) {
          await selectConversation(remainingConversations[0].id);
        } else {
          setCurrentConversationId(null);
          setMessages([]);
        }
      }
      
      toast.success('对话删除成功');
      return true;
    } catch (error) {
      console.error('删除对话失败:', error);
      toast.error('删除对话失败');
      return false;
    }
  }, [user, currentConversationId, conversations]);

  // 选择对话
  const selectConversation = useCallback(async (conversationId: string) => {
    setCurrentConversationId(conversationId);
    await fetchMessages(conversationId);
  }, [fetchMessages]);

  // 保存消息
  const saveMessage = useCallback(async (messageData: {
    content: string;
    sender_type: 'user' | 'ai';
    message_type: Message['message_type'];
    metadata?: any;
  }, conversationId: string) => {
    if (!user) {
      const now = new Date().toISOString();
      const localMessage: Message = {
        id: createLocalId('message'),
        content: messageData.content,
        sender_type: messageData.sender_type,
        message_type: messageData.message_type,
        metadata: messageData.metadata || null,
        created_at: now,
      };
      const store = readLocalStore();
      const existingMessages = store.messages[conversationId] || [];
      const nextMessages = [...existingMessages, localMessage];
      const nextConversations = sortConversations(store.conversations.map(conv =>
        conv.id === conversationId ? { ...conv, updated_at: now } : conv
      ));

      writeLocalStore({ ...store, conversations: nextConversations, messages: { ...store.messages, [conversationId]: nextMessages } });
      setConversations(nextConversations);
      setMessages(prev => [...prev, localMessage]);
      return localMessage;
    }
    
    try {
      const { data, error } = await supabase
        .from('messages')
        .insert([
          {
            content: messageData.content,
            sender_type: messageData.sender_type,
            message_type: messageData.message_type,
            metadata: messageData.metadata || null,
            conversation_id: conversationId,
            user_id: user.id
          }
        ])
        .select()
        .single();
      
      if (error) throw error;
      
      const formattedMessage: Message = {
        id: data.id,
        content: data.content,
        sender_type: data.sender_type as 'user' | 'ai',
        message_type: data.message_type as Message['message_type'],
        metadata: data.metadata,
        created_at: data.created_at
      };
      
      setMessages(prev => [...prev, formattedMessage]);
      return formattedMessage;
    } catch (error) {
      console.error('保存消息失败:', error);
      return null;
    }
  }, [user]);

  // 专用：保存 Dify 的 conversation_id（统一登录/访客）
  const updateDifyConversationId = useCallback(async (
    conversationId: string,
    difyConversationId: string
  ) => {
    if (!conversationId || !difyConversationId) return false;

    // 立即更新本地 state，避免后续读取竞态
    setConversations(prev => prev.map(conv =>
      conv.id === conversationId
        ? { ...conv, dify_conversation_id: difyConversationId }
        : conv
    ));

    if (!user) {
      const store = readLocalStore();
      const nextConversations = store.conversations.map(conv =>
        conv.id === conversationId
          ? { ...conv, dify_conversation_id: difyConversationId }
          : conv
      );
      writeLocalStore({ ...store, conversations: nextConversations });
      return true;
    }

    try {
      const { error } = await supabase
        .from('conversations')
        .update({ dify_conversation_id: difyConversationId })
        .eq('id', conversationId)
        .eq('user_id', user.id);
      if (error) throw error;
      return true;
    } catch (error) {
      console.error('保存 Dify 会话ID 失败:', error);
      return false;
    }
  }, [user]);

  return {
    conversations,
    currentConversationId,
    messages,
    isLoading,
    setMessages,
    setCurrentConversationId,
    fetchConversations,
    fetchMessages,
    createConversation,
    updateConversation,
    updateDifyConversationId,
    deleteConversation,
    selectConversation,
    saveMessage
  };
};
