import { Sparkles, User } from 'lucide-react'
import { MarkdownContent } from '@/components/ui/MarkdownContent'
import { SuggestedFlowCard } from './SuggestedFlowCard'
import type { SuggestedFlow } from '@/types/copilot'

interface ChatMessageProps {
  role: 'user' | 'assistant'
  content: string
  suggestedFlows?: SuggestedFlow[]
  imageUrls?: string[]
}

export function ChatMessage({ role, content, suggestedFlows, imageUrls }: ChatMessageProps) {
  return (
    <div className={`flex gap-3 ${role === 'user' ? 'flex-row-reverse' : ''}`}>
      {/* Avatar */}
      <div
        className={`shrink-0 w-8 h-8 rounded-full flex items-center justify-center ${
          role === 'assistant'
            ? 'bg-primary/15 text-primary'
            : 'bg-elevated text-muted-foreground'
        }`}
      >
        {role === 'assistant' ? <Sparkles size={14} /> : <User size={14} />}
      </div>

      {/* Content */}
      <div className={`max-w-[80%] space-y-2 ${role === 'user' ? 'text-right' : ''}`}>
        {/* Image attachments (user messages only) */}
        {role === 'user' && imageUrls && imageUrls.length > 0 && (
          <div className={`flex flex-wrap gap-2 ${role === 'user' ? 'justify-end' : ''}`}>
            {imageUrls.map((url, i) => (
              <a key={i} href={url} target="_blank" rel="noopener noreferrer">
                <img
                  src={url}
                  alt={`Attachment ${i + 1}`}
                  className="h-24 w-auto max-w-[200px] rounded-xl object-cover border border-border cursor-pointer hover:opacity-90 transition-opacity"
                />
              </a>
            ))}
          </div>
        )}

        <div
          className={`rounded-2xl px-4 py-3 text-[0.875rem] leading-relaxed ${
            role === 'user'
              ? 'bg-primary/15 text-foreground'
              : 'bg-input text-foreground border border-border'
          }`}
        >
          <MarkdownContent content={content} className="text-[0.875rem] leading-relaxed" />
        </div>

        {/* Suggested flows (assistant only) */}
        {role === 'assistant' && suggestedFlows && suggestedFlows.length > 0 && (
          <div className="space-y-1.5">
            <span className="font-sans text-xs text-[0.625rem] uppercase tracking-widest text-muted-foreground">
              Related Flows
            </span>
            {suggestedFlows.map(flow => (
              <SuggestedFlowCard key={flow.tree_id} flow={flow} />
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
