'use client'
import { useState, useRef, useEffect } from 'react'

interface Message {
  role: 'user' | 'assistant'
  content: string
}

const QUICK_PROMPTS = [
  "My maize leaves are turning yellow",
  "When should I plant tomatoes?",
  "How do I prevent Fall Armyworm?",
  "Best fertilizer for beans?",
  "Signs of milk fever in cows?",
  "How to make organic pesticide?",
]

export default function FarmChat() {
  const [messages, setMessages] = useState<Message[]>([])
  const [input, setInput] = useState('')
  const [loading, setLoading] = useState(false)
  const [county, setCounty] = useState('')
  const [showSetup, setShowSetup] = useState(true)
  const messagesEndRef = useRef<HTMLDivElement>(null)
  const inputRef = useRef<HTMLTextAreaElement>(null)

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }, [messages])

  const sendMessage = async (text: string) => {
    if (!text.trim() || loading) return

    const userMessage: Message = { role: 'user', content: text }
    const newMessages = [...messages, userMessage]
    setMessages(newMessages)
    setInput('')
    setLoading(true)

    try {
      const res = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          messages: newMessages,
          context: { county: county || undefined },
        }),
      })
      const data = await res.json()
      if (data.error) throw new Error(data.error)
      setMessages([...newMessages, { role: 'assistant', content: data.message }])
    } catch {
      setMessages([...newMessages, {
        role: 'assistant',
        content: "Sorry, I couldn't connect right now. Please check your internet and try again.",
      }])
    } finally {
      setLoading(false)
    }
  }

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

  if (showSetup && messages.length === 0) {
    return (
      <div className="px-4 py-5">
        <div className="animate-fade-up mb-5">
          <h2 className="font-display text-2xl font-bold text-soil-900 mb-1">Ask Shamba AI</h2>
          <p className="text-soil-500 text-sm">Your farming questions answered, any time. Ask about crops, pests, soil, weather — anything.</p>
        </div>

        {/* Optional county for context */}
        <div className="shamba-card p-4 mb-5 animate-fade-up stagger-1">
          <p className="text-xs font-semibold text-soil-500 uppercase tracking-wide mb-2">Optional: Your county (for better advice)</p>
          <input
            type="text"
            value={county}
            onChange={e => setCounty(e.target.value)}
            placeholder="e.g. Nakuru, Kisumu, Meru..."
            className="w-full px-3 py-2.5 rounded-xl border border-soil-200 bg-soil-50 text-sm text-soil-700 focus:outline-none focus:ring-2 focus:ring-leaf-400"
          />
        </div>

        {/* Quick prompts */}
        <div className="animate-fade-up stagger-2">
          <p className="text-xs font-semibold text-soil-500 uppercase tracking-wide mb-3">Common Questions</p>
          <div className="space-y-2">
            {QUICK_PROMPTS.map((prompt, i) => (
              <button
                key={i}
                onClick={() => { setShowSetup(false); sendMessage(prompt) }}
                className="w-full text-left px-4 py-3.5 shamba-card rounded-xl flex items-center justify-between gap-3 active:scale-95 transition-transform"
              >
                <span className="text-sm text-soil-700">{prompt}</span>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" className="text-soil-300 shrink-0">
                  <path d="M9 18l6-6-6-6" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
                </svg>
              </button>
            ))}
          </div>
        </div>

        <button
          onClick={() => setShowSetup(false)}
          className="w-full mt-4 py-4 bg-leaf-600 text-white rounded-2xl font-display font-semibold text-base active:scale-95 transition-transform shadow-lg shadow-leaf-200"
        >
          💬 Ask Your Own Question
        </button>
      </div>
    )
  }

  return (
    <div className="flex flex-col h-[calc(100vh-140px)]">
      {/* Chat header */}
      <div className="px-4 py-3 border-b border-gray-100 flex items-center gap-3 bg-white/80 backdrop-blur-sm">
        <div className="w-8 h-8 rounded-full bg-leaf-600 flex items-center justify-center shrink-0">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
            <path d="M12 22V10" stroke="white" strokeWidth="2.5" strokeLinecap="round"/>
            <path d="M12 10C12 10 6 8 4 3C8 1 12 5 12 10Z" fill="white"/>
            <path d="M12 10C12 10 18 8 20 3C16 1 12 5 12 10Z" fill="white" opacity="0.7"/>
          </svg>
        </div>
        <div>
          <p className="font-display font-semibold text-soil-800 text-sm">Shamba AI</p>
          <p className="text-xs text-leaf-500">Online · Always here</p>
        </div>
        {county && (
          <span className="ml-auto text-xs bg-soil-100 text-soil-500 px-2 py-1 rounded-full">📍 {county}</span>
        )}
      </div>

      {/* Messages */}
      <div className="flex-1 overflow-y-auto px-4 py-4 space-y-4">
        {messages.length === 0 && (
          <div className="text-center py-8 animate-fade-up">
            <div className="w-16 h-16 rounded-2xl bg-leaf-100 flex items-center justify-center mx-auto mb-3">
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none">
                <path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" stroke="#3d9636" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </div>
            <p className="font-display font-semibold text-soil-700">What's your farming question?</p>
            <p className="text-xs text-soil-400 mt-1">Ask about crops, pests, soil, weather...</p>
          </div>
        )}

        {messages.map((msg, i) => (
          <div key={i} className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}>
            {msg.role === 'assistant' && (
              <div className="w-7 h-7 rounded-full bg-leaf-600 flex items-center justify-center shrink-0 mr-2 mt-1">
                <span className="text-xs text-white font-bold">AI</span>
              </div>
            )}
            <div className={`max-w-[82%] px-4 py-3 rounded-2xl text-sm leading-relaxed ${
              msg.role === 'user'
                ? 'bg-leaf-600 text-white rounded-br-sm'
                : 'bg-white border border-gray-100 text-soil-700 rounded-bl-sm shadow-sm'
            }`}>
              {msg.content.split('\n').map((line, j) => (
                <p key={j} className={j > 0 ? 'mt-1.5' : ''}>{line}</p>
              ))}
            </div>
          </div>
        ))}

        {loading && (
          <div className="flex justify-start animate-fade-up">
            <div className="w-7 h-7 rounded-full bg-leaf-600 flex items-center justify-center shrink-0 mr-2 mt-1">
              <span className="text-xs text-white font-bold">AI</span>
            </div>
            <div className="bg-white border border-gray-100 px-4 py-3 rounded-2xl rounded-bl-sm shadow-sm">
              <div className="flex gap-1.5 items-center h-4">
                {[0, 1, 2].map(i => (
                  <div key={i} className="w-2 h-2 rounded-full bg-leaf-400 animate-bounce" style={{ animationDelay: `${i * 0.15}s` }}/>
                ))}
              </div>
            </div>
          </div>
        )}
        <div ref={messagesEndRef}/>
      </div>

      {/* Quick prompts when chat is active */}
      {messages.length > 0 && messages.length < 4 && (
        <div className="px-4 py-2 flex gap-2 overflow-x-auto">
          {QUICK_PROMPTS.slice(0, 3).map((p, i) => (
            <button
              key={i}
              onClick={() => sendMessage(p)}
              className="shrink-0 text-xs bg-white border border-leaf-200 text-leaf-700 px-3 py-2 rounded-full whitespace-nowrap active:bg-leaf-50"
            >
              {p}
            </button>
          ))}
        </div>
      )}

      {/* Input area */}
      <div className="px-4 py-3 bg-white border-t border-gray-100">
        <div className="flex items-end gap-2">
          <textarea
            ref={inputRef}
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="Ask about your farm..."
            rows={1}
            className="flex-1 px-4 py-3 rounded-2xl border border-soil-200 bg-soil-50 text-sm text-soil-800 resize-none focus:outline-none focus:ring-2 focus:ring-leaf-400 placeholder-soil-300"
            style={{ maxHeight: '120px' }}
          />
          <button
            onClick={() => sendMessage(input)}
            disabled={!input.trim() || loading}
            className="w-11 h-11 rounded-2xl bg-leaf-600 flex items-center justify-center shrink-0 disabled:opacity-40 active:scale-90 transition-transform shadow-md shadow-leaf-200"
          >
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
              <path d="M22 2L11 13M22 2L15 22l-4-9-9-4 20-7z" stroke="white" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        </div>
      </div>
    </div>
  )
}
