'use client'

import { useEffect, useRef } from 'react'
import { AnimatePresence, motion } from 'framer-motion'
import Link from 'next/link'
import { DaliBotMessage } from './DaliBotMessage'
import { DaliBotQuickReplies } from './DaliBotQuickReplies'
import { DaliBotInput } from './DaliBotInput'
import { X, RotateCcw, Loader2, ArrowRight } from 'lucide-react'
import type { ChatMessage } from '@/types/dalibot'

interface DaliBotPanelProps {
  messages: ChatMessage[]
  isLoading: boolean
  onSend: (msg: string) => void
  onClose: () => void
  onReset: () => void
}

export function DaliBotPanel({ messages, isLoading, onSend, onClose, onReset }: DaliBotPanelProps) {
  const scrollRef = useRef<HTMLDivElement>(null)
  const lastMessage = messages[messages.length - 1]

  useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight
    }
  }, [messages])

  return (
    <motion.div
      initial={{ opacity: 0, y: 20, scale: 0.96 }}
      animate={{ opacity: 1, y: 0, scale: 1 }}
      exit={{ opacity: 0, y: 20, scale: 0.96 }}
      transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] as [number, number, number, number] }}
      className="flex flex-col overflow-hidden rounded-2xl w-[360px] max-w-[calc(100vw-2rem)]"
      style={{
        height: '520px',
        background: 'var(--dt-bg-surface)',
        border: '1px solid var(--dt-border-glass)',
        boxShadow: 'var(--dt-shadow-glow-lg), var(--dt-shadow-card)',
      }}
    >
      {/* Header */}
      <div
        className="flex items-center justify-between px-4 py-3 shrink-0"
        style={{ borderBottom: '1px solid var(--dt-border-subtle)' }}
      >
        <div className="flex items-center gap-2.5">
          <div
            className="w-8 h-8 rounded-xl flex items-center justify-center text-xs font-bold"
            style={{ background: 'var(--dt-gradient-accent)', color: '#fff' }}
          >
            D
          </div>
          <div>
            <p className="text-sm font-semibold leading-none mb-0.5" style={{ color: 'var(--dt-text-primary)' }}>
              DaliBot
            </p>
            <div className="flex items-center gap-1">
              <span className="w-1.5 h-1.5 rounded-full bg-green-400 animate-pulse" />
              <span className="text-xs" style={{ color: 'var(--dt-text-muted)' }}>Online</span>
            </div>
          </div>
        </div>
        <div className="flex items-center gap-1">
          <button
            onClick={onReset}
            className="w-7 h-7 rounded-lg flex items-center justify-center transition-colors"
            style={{ color: 'var(--dt-text-muted)' }}
            aria-label="Reset conversation"
          >
            <RotateCcw className="w-3.5 h-3.5" />
          </button>
          <button
            onClick={onClose}
            className="w-7 h-7 rounded-lg flex items-center justify-center transition-colors"
            style={{ color: 'var(--dt-text-muted)' }}
            aria-label="Close"
          >
            <X className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* Messages */}
      <div
        ref={scrollRef}
        className="flex-1 overflow-y-auto px-4 py-4 space-y-3"
        style={{ scrollbarWidth: 'thin', scrollbarColor: 'var(--dt-border-subtle) transparent' }}
      >
        <AnimatePresence initial={false}>
          {messages.map((msg) => (
            <motion.div
              key={msg.id}
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.25 }}
            >
              <DaliBotMessage message={msg} />
            </motion.div>
          ))}
        </AnimatePresence>

        {isLoading && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            className="flex items-center gap-2"
          >
            <div
              className="px-4 py-3 rounded-2xl rounded-tl-sm"
              style={{
                background: 'var(--dt-bg-elevated)',
                border: '1px solid var(--dt-border-subtle)',
              }}
            >
              <Loader2 className="w-4 h-4 animate-spin" style={{ color: 'var(--dt-accent-primary)' }} />
            </div>
          </motion.div>
        )}
      </div>

      {/* Quick replies */}
      {lastMessage?.quickReplies && lastMessage.quickReplies.length > 0 && !isLoading && (
        <div
          className="px-4 py-2 shrink-0"
          style={{ borderTop: '1px solid var(--dt-border-subtle)' }}
        >
          <DaliBotQuickReplies
            replies={lastMessage.quickReplies}
            onSelect={onSend}
            disabled={isLoading}
          />
        </div>
      )}

      {/* CTA */}
      {lastMessage?.ctaType && !isLoading && (
        <div
          className="px-4 py-3 shrink-0"
          style={{ borderTop: '1px solid var(--dt-border-subtle)' }}
        >
          {lastMessage.ctaType === 'booking' ? (
            <Link
              href="/booking"
              className="w-full inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium text-white"
              style={{ background: 'var(--dt-gradient-accent)' }}
            >
              Book a Strategy Call
              <ArrowRight className="w-4 h-4" />
            </Link>
          ) : (
            <a
              href="#roi"
              className="w-full inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-colors"
              style={{
                border: '1px solid var(--dt-border-accent)',
                color: 'var(--dt-accent-bright)',
                background: 'rgba(99,102,241,0.06)',
              }}
            >
              See ROI Calculator
              <ArrowRight className="w-4 h-4" />
            </a>
          )}
        </div>
      )}

      {/* Input */}
      <div className="px-4 pb-4 pt-2 shrink-0" style={{ borderTop: !lastMessage?.ctaType ? '1px solid var(--dt-border-subtle)' : 'none' }}>
        <DaliBotInput onSend={onSend} disabled={isLoading} />
      </div>
    </motion.div>
  )
}
