import React, { useState, useRef, useEffect } from 'react';
import { Layout, Input, Button, List, Typography, Space, Spin } from 'antd';
import { SendOutlined, RobotOutlined, UserOutlined } from '@ant-design/icons';
import { ENV } from '../../config/env';
import { useAppSelector } from '../../redux/hooks';
import axios from 'axios';
import { Link } from 'react-router-dom';

const { Content, Header } = Layout;
const { Text } = Typography;

interface ChatMessage {
  role: 'user' | 'assistant';
  content: string;
}

const AiChatPage: React.FC = () => {
  const { user } = useAppSelector((state) => state.auth);
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [loading, setLoading] = useState(false);
  const listRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // Scroll to bottom when messages change
    if (listRef.current) {
      listRef.current.scrollTop = listRef.current.scrollHeight;
    }
  }, [messages, loading]);

  const handleSend = async () => {
    if (!inputValue.trim()) return;
    
    const query = inputValue.trim();
    setInputValue('');
    setMessages(prev => [...prev, { role: 'user', content: query }]);
    setLoading(true);
    
    try {
      const response = await axios.post(`${ENV.AI_API_URL}/api/ai/chat`, {
        query,
        user_id: user?.id || 25
      });
      
      setMessages(prev => [...prev, { role: 'assistant', content: response.data.answer }]);
    } catch (error: any) {
      console.error("AI API Error:", error);
      setMessages(prev => [...prev, { role: 'assistant', content: "Sorry, I encountered an error. Is the AI server running?" }]);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Layout style={{ height: '100vh', background: '#f5f5f5' }}>
      <Header style={{ background: '#fff', padding: '0 24px', display: 'flex', alignItems: 'center', boxShadow: '0 1px 4px rgba(0,21,41,.08)', zIndex: 1 }}>
        <Space>
          <RobotOutlined style={{ fontSize: 24, color: '#16a34a' }} />
          <Typography.Title level={4} style={{ margin: 0 }}>AVS AI Assistant</Typography.Title>
        </Space>
        <div style={{ marginLeft: 'auto' }}>
          <Link to="/dashboard">Back to Dashboard</Link>
        </div>
      </Header>
      
      <Content style={{ padding: '24px', display: 'flex', flexDirection: 'column' }}>
        <div 
          ref={listRef}
          style={{ 
            flex: 1, 
            background: '#fff', 
            padding: '24px', 
            borderRadius: '8px', 
            overflowY: 'auto',
            marginBottom: '24px',
            boxShadow: '0 1px 2px rgba(0,0,0,0.05)'
          }}
        >
          {messages.length === 0 ? (
            <div style={{ textAlign: 'center', color: '#999', marginTop: '100px' }}>
              <RobotOutlined style={{ fontSize: 48, color: '#ccc', marginBottom: '16px' }} />
              <p>Hello! I am your AVS AI Assistant. Ask me anything about the system or your business.</p>
            </div>
          ) : (
            <List
              dataSource={messages}
              renderItem={(msg) => (
                <List.Item style={{ borderBottom: 'none', padding: '12px 0', justifyContent: msg.role === 'user' ? 'flex-end' : 'flex-start' }}>
                  <Space align="start" style={{ maxWidth: '75%', flexDirection: msg.role === 'user' ? 'row-reverse' : 'row' }}>
                    <div style={{ 
                      width: 32, 
                      height: 32, 
                      borderRadius: '50%', 
                      background: msg.role === 'user' ? '#16a34a' : '#f0f2f5',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      color: msg.role === 'user' ? '#fff' : '#666'
                    }}>
                      {msg.role === 'user' ? <UserOutlined /> : <RobotOutlined />}
                    </div>
                    <div style={{
                      background: msg.role === 'user' ? '#e6f4ea' : '#f0f2f5',
                      padding: '12px 16px',
                      borderRadius: '12px',
                      borderTopRightRadius: msg.role === 'user' ? 0 : '12px',
                      borderTopLeftRadius: msg.role === 'assistant' ? 0 : '12px',
                    }}>
                      <Text style={{ whiteSpace: 'pre-wrap' }}>{msg.content}</Text>
                    </div>
                  </Space>
                </List.Item>
              )}
            />
          )}
          {loading && (
            <div style={{ display: 'flex', alignItems: 'flex-start', padding: '12px 0' }}>
               <Space align="start" style={{ maxWidth: '75%' }}>
                 <div style={{ width: 32, height: 32, borderRadius: '50%', background: '#f0f2f5', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#666' }}>
                   <RobotOutlined />
                 </div>
                 <div style={{ padding: '12px 16px', borderRadius: '12px', borderTopLeftRadius: 0, background: '#f0f2f5' }}>
                   <Spin size="small" />
                 </div>
               </Space>
            </div>
          )}
        </div>
        
        <div style={{ display: 'flex', gap: '8px' }}>
          <Input 
            size="large"
            placeholder="Type your question..." 
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onPressEnter={handleSend}
            disabled={loading}
          />
          <Button 
            type="primary" 
            size="large" 
            icon={<SendOutlined />} 
            onClick={handleSend}
            loading={loading}
          >
            Send
          </Button>
        </div>
      </Content>
    </Layout>
  );
};

export default AiChatPage;
