// src/components/keywords/dispatch/dispatch-view.tsx — Dispatch full-screen view.
"use client";

import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import { toast } from "sonner";
import { SerpPanel } from "@/components/content/serp-panel";
import { BriefPanel } from "@/components/keywords/brief-panel";
import { SemanticAnalysisSection } from "@/components/keywords/planning/semantic-analysis-section";
import { Button } from "@/components/ui/button";
import { Flag } from "@/components/ui/flag";
import { Input } from "@/components/ui/input";
import { createContentItemAction } from "@/lib/content/actions";
import type { DispatchCountry } from "@/lib/keywords/queries";
import type { Keyword } from "@/lib/keywords/types";
import type { StoredSemanticProfile } from "@/lib/semantic/profile-types";

export function DispatchView({
  keyword,
  countries,
  profile,
}: {
  keyword: Keyword;
  countries: DispatchCountry[];
  profile: StoredSemanticProfile | null;
}) {
  const router = useRouter();
  const [pending, start] = useTransition();
  const [country, setCountry] = useState(countries[0]?.country ?? "");
  const [title, setTitle] = useState(keyword.term);
  const [dueDate, setDueDate] = useState("");
  const [assignee, setAssignee] = useState("");

  const active = countries.find((c) => c.country === country);
  const ready =
    active &&
    active.analysis.serp.state === "ok" &&
    active.analysis.onpage.state === "ok" &&
    active.analysis.brief.state === "ok";

  function send() {
    start(async () => {
      try {
        await createContentItemAction(keyword.id, country, {
          title,
          dueDate: dueDate || null,
          assignee: assignee || null,
        });
        toast.success("Envoyé en production");
        router.push("/content/planning");
      } catch {
        toast.error("Échec de l'envoi en production");
      }
    });
  }

  return (
    <div className="flex h-[calc(100vh-3.5rem)] flex-col">
      {/* Header */}
      <div className="flex shrink-0 items-center gap-3 border-b px-4 py-3">
        <Button
          variant="ghost"
          size="sm"
          onClick={() => router.back()}
          className="-ml-2"
        >
          ← Retour
        </Button>
        <span className="font-semibold text-sm">{keyword.term}</span>
        {/* Country tabs */}
        <div className="ml-4 flex gap-1">
          {countries.map((c) => (
            <button
              key={c.country}
              type="button"
              aria-pressed={c.country === country}
              onClick={() => setCountry(c.country)}
              className="inline-flex items-center gap-1.5 rounded-md px-3 py-1 text-sm transition-colors aria-pressed:bg-primary aria-pressed:text-primary-foreground hover:bg-muted"
            >
              <Flag code={c.country} className="h-3.5" /> {c.country}
            </button>
          ))}
        </div>
      </div>

      {/* Body */}
      <div className="flex min-h-0 flex-1">
        {/* Left — scrolling zone */}
        <div className="flex-1 overflow-y-auto space-y-6 p-6">
          <SerpPanel
            keywordId={keyword.id}
            snapshot={active?.snapshot ?? null}
            onImported={() => router.refresh()}
          />
          <SemanticAnalysisSection
            keywordId={keyword.id}
            country={keyword.locale.country}
            profile={profile}
            onAnalyzed={() => router.refresh()}
          />
          <BriefPanel briefs={keyword.briefs} />
        </div>

        {/* Right rail */}
        <div className="w-80 shrink-0 border-l flex flex-col gap-5 p-6">
          <h2 className="font-semibold text-sm">Dispatch</h2>

          <div className="space-y-1">
            <label
              className="text-xs text-muted-foreground"
              htmlFor="dispatch-title"
            >
              Titre
            </label>
            <Input
              id="dispatch-title"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="Titre de l'article"
            />
          </div>

          <div className="space-y-1">
            <label
              className="text-xs text-muted-foreground"
              htmlFor="dispatch-due"
            >
              Échéance
            </label>
            <Input
              id="dispatch-due"
              type="date"
              value={dueDate}
              onChange={(e) => setDueDate(e.target.value)}
            />
          </div>

          <div className="space-y-1">
            <label
              className="text-xs text-muted-foreground"
              htmlFor="dispatch-assignee"
            >
              Assigné
            </label>
            <Input
              id="dispatch-assignee"
              value={assignee}
              onChange={(e) => setAssignee(e.target.value)}
              placeholder="nom@exemple.com"
            />
          </div>

          <div className="mt-auto">
            <Button
              className="w-full"
              disabled={pending || !country || !ready}
              onClick={send}
            >
              {pending ? "Envoi…" : "Envoyer en production"}
            </Button>
            {active && !ready && (
              <p className="mt-2 text-center text-xs text-muted-foreground">
                SERP, on-page et brief requis
              </p>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
