import React, { useState, useEffect, useRef } from 'react';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { aiResponse as fetchAiResponse } from '../../stores/openAiSlice';
import BaseButton from '../BaseButton';
import CardBox from '../CardBox';
import FormField from '../FormField';
import { mdiSend, mdiRobot, mdiAccount } from '@mdi/js';
import BaseIcon from '../BaseIcon';
import LoadingSpinner from '../LoadingSpinner';

interface Props {
  matter: any;
}

const MatterAssistant = ({ matter }: Props) => {
  const dispatch = useAppDispatch();
  const { aiResponse, isAskingResponse, errorMessage } = useAppSelector((state) => state.openAi);
  const [prompt, setPrompt] = useState('');
  const [messages, setMessages] = useState<Array<{ role: string; content: string }>>([]);
  const bottomRef = useRef<null | HTMLDivElement>(null);

  // Scroll to bottom on new messages
  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages, isAskingResponse]);

  // Handle incoming AI response
  useEffect(() => {
    if (!isAskingResponse && aiResponse) {
      // Extract text from the complex response structure
      // Structure: data.output[] -> item.type=="message" -> content[] -> item.type=="output_text" -> text
      let text = '';
      try {
        if (aiResponse.output && Array.isArray(aiResponse.output)) {
          const messageOutput = aiResponse.output.find((o: any) => o.type === 'message');
          if (messageOutput && messageOutput.content && Array.isArray(messageOutput.content)) {
            const textContent = messageOutput.content.find((c: any) => c.type === 'output_text');
            if (textContent) {
              text = textContent.text;
            }
          }
        }
      } catch (err) {
        console.error('Error parsing AI response:', err);
        text = 'Error: Could not parse response from AI.';
      }

      if (text) {
          // Check if we already have this response (simple check to avoid duplicate adds on re-renders)
          setMessages((prev) => {
              const lastMsg = prev[prev.length - 1];
              if (lastMsg && lastMsg.role === 'assistant' && lastMsg.content === text) {
                  return prev;
              }
              return [...prev, { role: 'assistant', content: text }];
          });
      }
    }
  }, [aiResponse, isAskingResponse]);

  const handleSend = () => {
    if (!prompt.trim()) return;

    // Add user message immediately
    const userMsg = { role: 'user', content: prompt };
    setMessages((prev) => [...prev, userMsg]);
    setPrompt('');

    // Construct system context
    const partiesList = matter.matter_parties_matter
      ? matter.matter_parties_matter.map((p: any) => `${p.display_name} (${p.party_role})`).join(', ')
      : 'None';

    const systemPrompt = `You are a helpful legal assistant for the case "${matter.title}".
    
    Context:
    - Description: ${matter.description || 'N/A'}
    - Jurisdiction: ${matter.jurisdiction || 'N/A'}
    - Court: ${matter.court_name || 'N/A'}
    - Case Number: ${matter.case_number || 'N/A'}
    - Parties Involved: ${partiesList}
    
    Answer the user's questions based on this context. Be professional, concise, and accurate. If you don't know something, say so.`;

    // Dispatch AI request
    // We send the FULL history plus system prompt for context, or just system + last prompt?
    // Ideally full history, but for simplicity/token limits, let's send System + Last User Prompt for now.
    // If we wanted history, we'd map `messages` to the input array.
    
    // Let's try sending recent history (last 5 messages) to maintain conversation flow.
    const historyPayload = messages.slice(-5).map(m => ({ role: m.role, content: m.content }));

    dispatch(fetchAiResponse({
      input: [
        { role: 'system', content: systemPrompt },
        ...historyPayload,
        { role: 'user', content: prompt } // Add current prompt
      ],
      options: { poll_interval: 2, poll_timeout: 60 } // Faster polling
    }));
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  return (
    <div className="flex flex-col h-[600px] border rounded-lg overflow-hidden bg-white shadow-sm">
      {/* Header */}
      <div className="bg-gray-100 p-4 border-b flex justify-between items-center">
        <div className="flex items-center gap-2">
            <BaseIcon path={mdiRobot} size="24" className="text-blue-600" />
            <h3 className="font-bold text-gray-700">Case Assistant</h3>
        </div>
        <div className="text-xs text-gray-500">
            Context: {matter.title}
        </div>
      </div>

      {/* Messages Area */}
      <div className="flex-1 overflow-y-auto p-4 space-y-4 bg-gray-50">
        {messages.length === 0 && (
          <div className="text-center text-gray-400 mt-10">
            <BaseIcon path={mdiRobot} size="48" className="mx-auto mb-2 opacity-50" />
            <p>Ask me anything about this case.</p>
            <p className="text-sm">&quot;Draft a motion...&quot;, &quot;Summarize the parties...&quot;, &quot;Check jurisdiction...&quot;</p>
          </div>
        )}

        {messages.map((msg, index) => (
          <div
            key={index}
            className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}
          >
            <div
              className={`max-w-[80%] rounded-lg p-3 ${
                msg.role === 'user'
                  ? 'bg-blue-600 text-white rounded-br-none'
                  : 'bg-white border text-gray-800 rounded-bl-none shadow-sm'
              }`}
            >
              {msg.role === 'assistant' && (
                <div className="flex items-center gap-1 mb-1 opacity-50 text-xs">
                  <BaseIcon path={mdiRobot} size="12" />
                  <span>Assistant</span>
                </div>
              )}
               <div className="whitespace-pre-wrap text-sm">{msg.content}</div>
            </div>
          </div>
        ))}

        {isAskingResponse && (
          <div className="flex justify-start">
             <div className="bg-white border text-gray-800 rounded-lg rounded-bl-none shadow-sm p-3 flex items-center gap-2">
                <LoadingSpinner className="w-4 h-4 text-blue-600" />
                <span className="text-xs text-gray-500">Thinking...</span>
             </div>
          </div>
        )}

        {errorMessage && (
             <div className="text-center text-red-500 text-sm my-2">
                 Error: {errorMessage}
             </div>
        )}

        <div ref={bottomRef} />
      </div>

      {/* Input Area */}
      <div className="p-4 bg-white border-t">
        <div className="flex gap-2">
          <div className="flex-1">
             <textarea
                className="w-full border-gray-300 rounded focus:ring-blue-500 focus:border-blue-500 text-sm"
                rows={2}
                placeholder="Type your request here..."
                value={prompt}
                onChange={(e) => setPrompt(e.target.value)}
                onKeyDown={handleKeyDown}
                disabled={isAskingResponse}
             />
          </div>
          <BaseButton
            icon={mdiSend}
            color="info"
            onClick={handleSend}
            disabled={isAskingResponse || !prompt.trim()}
            className="h-full"
          />
        </div>
        <div className="text-xs text-gray-400 mt-1 text-center">
            AI can make mistakes. Please verify important information.
        </div>
      </div>
    </div>
  );
};

export default MatterAssistant;