"use client";

import { FormEvent, useEffect, useState } from "react";
import { Brain, Send } from "lucide-react";
import { STRATEGY_PROMPTS } from "@/lib/constants";
import { getBadAdsModel } from "@/lib/ml/bad-ads-strategy";
import type { MLStrategyBrief } from "@/lib/ml/bad-ads-strategy";
import { getBusiness } from "@/lib/data-store";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import type { AIMessage, Business } from "@/lib/types";

const mlModel = getBadAdsModel();

export default function StrategyPage() {
  const [business, setBusiness] = useState<Business | null>(null);
  const [messages, setMessages] = useState<AIMessage[]>([
    {
      id: "seed",
      role: "assistant",
      content:
        "I'm your BrandLxft AI co-founder with ML-backed ad strategy. I was trained on 500 annotated ads from the CHI 2021 Ad Perceptions dataset — ask about growth, ads, content, competitors, or brand trust.",
      createdAt: new Date().toISOString(),
    },
  ]);
  const [lastMlBrief, setLastMlBrief] = useState<MLStrategyBrief | null>(null);
  const [value, setValue] = useState("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    getBusiness().then(setBusiness);
  }, []);

  const send = async (text: string) => {
    if (!text.trim()) return;
    const userMessage: AIMessage = {
      id: crypto.randomUUID(),
      role: "user",
      content: text,
      createdAt: new Date().toISOString(),
    };
    const nextMessages = [...messages, userMessage];
    setMessages(nextMessages);
    setValue("");
    setLoading(true);

    try {
      const res = await fetch("/api/ai/strategy", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ messages: nextMessages, business }),
      });
      const data = (await res.json()) as { message?: string; mlBrief?: MLStrategyBrief };
      if (data.mlBrief) setLastMlBrief(data.mlBrief);
      setMessages((prev) => [
        ...prev,
        {
          id: crypto.randomUUID(),
          role: "assistant",
          content: data.message ?? "Focus on your highest-confidence opportunity this week.",
          createdAt: new Date().toISOString(),
        },
      ]);
    } catch {
      setMessages((prev) => [
        ...prev,
        {
          id: crypto.randomUUID(),
          role: "assistant",
          content: "I couldn't reach the ML strategy engine. Try again shortly.",
          createdAt: new Date().toISOString(),
        },
      ]);
    } finally {
      setLoading(false);
    }
  };

  const onSubmit = (e: FormEvent) => {
    e.preventDefault();
    send(value);
  };

  const riskStyles = {
    low: "border-emerald-500/30 bg-emerald-500/10 text-emerald-300",
    medium: "border-amber-500/30 bg-amber-500/10 text-amber-300",
    high: "border-red-500/30 bg-red-500/10 text-red-300",
  };

  return (
    <div className="space-y-4 py-4">
      <Card className="border-violet-500/20">
        <CardContent className="flex flex-wrap items-center justify-between gap-3 p-4 text-sm">
          <div className="flex items-center gap-2">
            <Brain className="h-5 w-5 text-violet-400" />
            <div>
              <p className="font-medium text-slate-100">ML Ad Perceptions Engine</p>
              <p className="text-xs text-slate-400">
                Trained on {mlModel.sampleCount} ads ·{" "}
                <a href={mlModel.paperUrl} target="_blank" rel="noopener noreferrer" className="text-sky-400 hover:text-sky-300">
                  CHI 2021 study
                </a>{" "}
                ·{" "}
                <a href={mlModel.sourceUrl} target="_blank" rel="noopener noreferrer" className="text-sky-400 hover:text-sky-300">
                  dataset
                </a>
              </p>
            </div>
          </div>
          {lastMlBrief?.adCopyScore ? (
            <Badge className={riskStyles[lastMlBrief.adCopyScore.riskLevel]}>
              Ad risk: {lastMlBrief.adCopyScore.riskLevel} · {lastMlBrief.adCopyScore.predictedRating}/7 predicted
            </Badge>
          ) : (
            <Badge className="border-violet-500/30 bg-violet-500/10 text-violet-300">Ready</Badge>
          )}
        </CardContent>
      </Card>

      <div className="flex flex-wrap gap-2">
        {STRATEGY_PROMPTS.map((prompt) => (
          <button
            key={prompt}
            type="button"
            onClick={() => send(prompt)}
            className="rounded-full border border-slate-800 bg-slate-900 px-3 py-1.5 text-xs text-slate-300 hover:bg-slate-800"
          >
            {prompt}
          </button>
        ))}
      </div>

      <Card className="h-[calc(100vh-14rem)]">
        <CardHeader>
          <CardTitle>AI Strategy Room</CardTitle>
        </CardHeader>
        <CardContent className="flex h-[calc(100%-4rem)] flex-col gap-4">
          <div className="flex-1 space-y-3 overflow-y-auto rounded-xl border border-slate-800 p-3">
            {messages.map((message) => (
              <div
                key={message.id}
                className={`max-w-[85%] whitespace-pre-wrap rounded-xl p-3 text-sm ${
                  message.role === "user" ? "ml-auto bg-sky-500/15 text-sky-100" : "bg-slate-900 text-slate-200"
                }`}
              >
                {message.content}
              </div>
            ))}
          </div>
          <form onSubmit={onSubmit} className="flex gap-2">
            <Input value={value} onChange={(e) => setValue(e.target.value)} placeholder="Ask your ML-backed AI co-founder..." />
            <Button type="submit" disabled={loading} className="gap-2">
              <Send className="h-4 w-4" />
              {loading ? "Thinking..." : "Send"}
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
