// ───────────────────────────────────────────────
// AI Assistant Page (/(dashboard)/ai-assistant)
// ───────────────────────────────────────────────
// Route: /ai-assistant
// Purpose: AI-powered sales assistant with
//   conversational chat and Facebook lead
//   scraping by job title. Users select a target
//   job, trigger a Facebook scrape, and review
//   results in the chat panel.
// Layout: Two-column — main chat area + right
//   sidebar with job selector / details.
// ───────────────────────────────────────────────

"use client"

import { useState, useCallback, useRef } from "react"
import { AIChat, type AIChatHandle } from "@/components/ai/ai-chat"
import { JobSelector } from "@/components/ai/job-selector"
import { Bot, ChevronRight } from "lucide-react"

/**
 * AIAssistantPage
 * ───────────────
 * Manages the AI chat + job search workflow.
 * Selected job is shown in the sidebar; search
 * triggers a Facebook scrape via an external
 * scraper service with a 6-minute timeout.
 *
 * @returns AI assistant layout.
 */
export default function AIAssistantPage() {
  const [selectedJob, setSelectedJob] = useState<{ job_title: string; keywords: string[]; industry: string; description: string } | null>(null)
  const [recentPrompts, setRecentPrompts] = useState<string[]>([])
  const [searching, setSearching] = useState(false)
  const aiChatRef = useRef<AIChatHandle | null>(null)

  const handleJobSelect = useCallback((job: typeof selectedJob) => {
    setSelectedJob(job)
  }, [])

  // ── Facebook lead scraper handler ──
  const handleSearch = useCallback(async (job: NonNullable<typeof selectedJob>) => {
    setSearching(true)
    const keyword = job.keywords?.[0] || job.job_title
    aiChatRef.current?.addAssistantMessage(`🔍 Searching Facebook for **${job.job_title}** leads...`)

    // 6-minute hard abort, with a "still searching" status message at 45 s
    const controller = new AbortController()
    const timeoutId = setTimeout(() => controller.abort(), 360000)
    const statusId = setTimeout(() => {
      aiChatRef.current?.addAssistantMessage("⏳ Still searching Facebook (this can take up to 5 minutes)...")
    }, 45000)

    const scrapBase = process.env.NEXT_PUBLIC_SCRAPER_URL || "http://localhost:3008"

    try {
      const res = await fetch(`${scrapBase}/scrape/facebook?force=true&query=${encodeURIComponent(keyword)}`, { method: "POST", signal: controller.signal })
      clearTimeout(timeoutId)
      clearTimeout(statusId)
      const data = await res.json()

      if (data.success && data.leads?.length > 0) {
        // Format scraped leads as a markdown list for the chat
        const leadLines = data.leads
          .filter(Boolean)
          .map((lead: Record<string, string>, i: number) =>
            `**${i + 1}.** ${lead?.author || "Unknown"}\n> ${(lead?.content || "").slice(0, 300)}\n> 🔗 ${lead?.url || "(no link available)"}`
          )
        const leadsText = leadLines.join("\n\n")
        aiChatRef.current?.addAssistantMessage(`✅ Found **${data.leads.length}** leads:\n\n${leadsText}`)
      } else {
        const reason = data.error || data.flag_reason || "No leads found this time"
        aiChatRef.current?.addAssistantMessage(`⚠️ ${reason}`)
      }
    } catch (err: any) {
      clearTimeout(timeoutId)
      clearTimeout(statusId)
      const msg = err.name === "AbortError"
        ? "❌ Scraper timed out after 5 minutes. Try again or check the scraper service."
        : `❌ ${err instanceof Error ? err.message : "Search failed"}`
      aiChatRef.current?.addAssistantMessage(msg)
    } finally {
      setSearching(false)
    }
  }, [])

  const handleRecentPromptClick = useCallback((prompt: string) => {
    aiChatRef.current?.fillInput(prompt)
  }, [])

  // Keep track of last 3 sent prompts for quick reuse
  const handleMessageSent = useCallback((msg: string) => {
    setRecentPrompts((prev) => {
      const next = [msg, ...prev.filter((p) => p !== msg)].slice(0, 3)
      return next
    })
  }, [])

  return (
    <div className="flex h-[calc(100vh-3.5rem)] bg-background">
      {/* ── Main chat panel ── */}
      <div className="flex-1 flex flex-col min-w-0 border border-foreground transition-colors overflow-hidden">
        {/* Header */}
        <div className="bg-card/80 backdrop-blur-md border-b border-border px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-primary to-primary flex items-center justify-center" style={{boxShadow: "0 0 40px hsl(var(--primary) / 0.3)"}}>
                <Bot className="h-5 w-5 text-white" />
              </div>
              <div>
                <h1 className="text-foreground font-bold text-lg">AI Sales Assistant</h1>
                <p className="text-muted-foreground text-xs mt-0.5">Powered by local AI</p>
              </div>
            </div>
            {/* Status indicator */}
            <div className="flex items-center gap-4">
              <div className="flex items-center gap-2">
                <span className="w-2 h-2 rounded-full bg-[#22c55e] animate-pulse" />
                <span className="text-[#22c55e] text-xs font-medium">Online</span>
              </div>
              <div className="w-px h-5 bg-border" />
              <div className="bg-muted/50 rounded-lg px-3 py-1.5">
                <span className="text-muted-foreground text-xs">Local AI Model</span>
              </div>
            </div>
          </div>
        </div>
        <AIChat ref={aiChatRef} onMessageSent={handleMessageSent} />
      </div>

      {/* ── Right sidebar: Job selector ── */}
      <div className="w-[300px] flex-none bg-sidebar border border-foreground transition-colors p-5 overflow-y-auto h-full flex flex-col">
        <div>
          <div className="flex items-center gap-2 mb-3">
            <span className="w-1.5 h-1.5 rounded-full bg-primary" />
            <span className="text-primary text-[10px] font-bold uppercase tracking-[0.15em]">Target Job</span>
          </div>
          <JobSelector onSelect={handleJobSelect} onSearch={handleSearch} searching={searching} />
          {/* Selected job details card */}
          {selectedJob && (
            <div className="bg-card/50 border border-border rounded-xl p-3.5 mt-3 space-y-2">
              <h4 className="text-sm font-semibold text-foreground">{selectedJob.job_title}</h4>
              <span className="text-xs px-2 py-0.5 rounded-md bg-primary/10 text-primary font-medium inline-block">{selectedJob.industry}</span>
              <p className="text-xs text-muted-foreground leading-relaxed">{selectedJob.description}</p>
              <div className="flex flex-wrap gap-1.5">
                {selectedJob.keywords.map((kw, i) => (
                  <span key={i} className="text-xs px-2 py-0.5 rounded-md bg-muted/50 text-muted-foreground">{kw}</span>
                ))}
              </div>
            </div>
          )}
        </div>

      </div>
    </div>
  )
}
