// src/components/content/content-card-sheet.tsx
"use client";

import { useEffect, useState } from "react";
import { ContentKeywordsPanel } from "@/components/content/content-keywords-panel";
import { SerpPanel } from "@/components/content/serp-panel";
import { BriefPanel } from "@/components/keywords/brief-panel";
import { KeywordPromptCard } from "@/components/keywords/planning/keyword-prompt-card";
import { SemanticAnalysisSection } from "@/components/keywords/planning/semantic-analysis-section";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  deleteContentItemAction,
  getKeywordBriefsAction,
  updateContentItemAction,
} from "@/lib/content/actions";
import type { ContentItem } from "@/lib/content/types";
import { CONTENT_STATUS_LABEL, CONTENT_STATUSES } from "@/lib/content/types";
import type { ContentStatus } from "@/lib/db/domain-schema";
import { getSerpForKeywordAction } from "@/lib/keywords/serp-actions";
import type { SerpSnapshot } from "@/lib/keywords/serp-types";
import type { KeywordBrief } from "@/lib/keywords/ytg-types";
import { getSemanticProfileAction } from "@/lib/semantic/actions";
import type { StoredSemanticProfile } from "@/lib/semantic/profile-types";

export function ContentCardSheet({
  item,
  open,
  onOpenChange,
  onSaved,
}: {
  item: ContentItem | null;
  open: boolean;
  onOpenChange: (o: boolean) => void;
  onSaved: () => void;
}) {
  const [title, setTitle] = useState("");
  const [status, setStatus] = useState<ContentStatus>("idea");
  const [assignee, setAssignee] = useState("");
  const [dueDate, setDueDate] = useState("");
  const [url, setUrl] = useState("");
  // BriefPanel expects Record<string, KeywordBrief>; build from the array
  const [briefs, setBriefs] = useState<Record<string, KeywordBrief> | null>(
    null,
  );
  const [serp, setSerp] = useState<SerpSnapshot | null>(null);
  const [semanticProfile, setSemanticProfile] =
    useState<StoredSemanticProfile | null>(null);

  useEffect(() => {
    if (!item) return;
    setTitle(item.title);
    setStatus(item.status);
    setAssignee(item.assignee ?? "");
    setDueDate(item.dueDate ? item.dueDate.slice(0, 10) : "");
    setUrl(item.url ?? "");
    setBriefs(null);
    setSerp(null);
    setSemanticProfile(null);
    if (item.primaryKeywordId) {
      getSerpForKeywordAction(item.primaryKeywordId)
        .then((rec) => {
          const key = item.keywordCountry ?? item.country;
          setSerp(rec[key] ?? Object.values(rec)[0] ?? null);
        })
        .catch(() => setSerp(null));
      getKeywordBriefsAction(item.primaryKeywordId)
        .then((bs) => {
          if (bs.length === 0) return;
          // Key by country (falls back to query) so the brief tab label matches
          // the keyword page's per-country brief record shape.
          const record: Record<string, KeywordBrief> = {};
          for (const b of bs) {
            record[b.country || b.query] = b;
          }
          setBriefs(record);
        })
        .catch(() => setBriefs(null));
      getSemanticProfileAction(item.primaryKeywordId)
        .then(setSemanticProfile)
        .catch(() => setSemanticProfile(null));
    }
  }, [item]);

  if (!item) return null;

  async function save() {
    if (!item) return;
    await updateContentItemAction(item.id, {
      title,
      status,
      assignee: assignee.trim() || null,
      dueDate: dueDate || null,
      url: url.trim() || null,
    });
    onSaved();
    onOpenChange(false);
  }

  async function remove() {
    if (!item) return;
    await deleteContentItemAction(item.id);
    onSaved();
    onOpenChange(false);
  }

  function reloadSerp() {
    if (!item?.primaryKeywordId) return;
    const kwId = item.primaryKeywordId;
    const key = item.keywordCountry ?? item.country;
    getSerpForKeywordAction(kwId)
      .then((rec) => setSerp(rec[key] ?? Object.values(rec)[0] ?? null))
      .catch(() => {});
  }

  function reloadSemanticProfile() {
    if (!item?.primaryKeywordId) return;
    getSemanticProfileAction(item.primaryKeywordId)
      .then(setSemanticProfile)
      .catch(() => {});
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="flex h-[80vh] w-[80vw] max-w-[80vw] flex-col gap-0 p-0 sm:max-w-[80vw]">
        <DialogHeader className="border-b p-4">
          <DialogTitle>Article</DialogTitle>
        </DialogHeader>
        <div className="grid flex-1 gap-3 overflow-y-auto p-4">
          <div className="grid gap-1">
            <Label htmlFor="cs-title">Titre</Label>
            <Input
              id="cs-title"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
            />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div className="grid gap-1">
              <Label>Statut</Label>
              <Select
                value={status}
                onValueChange={(v) => setStatus(v as ContentStatus)}
              >
                <SelectTrigger aria-label="Statut">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent position="popper">
                  {CONTENT_STATUSES.map((s) => (
                    <SelectItem key={s} value={s}>
                      {CONTENT_STATUS_LABEL[s]}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid gap-1">
              <Label htmlFor="cs-due">Échéance</Label>
              <Input
                id="cs-due"
                type="date"
                value={dueDate}
                onChange={(e) => setDueDate(e.target.value)}
              />
            </div>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div className="grid gap-1">
              <Label htmlFor="cs-assignee">Assigné</Label>
              <Input
                id="cs-assignee"
                value={assignee}
                onChange={(e) => setAssignee(e.target.value)}
              />
            </div>
            <div className="grid gap-1">
              <Label htmlFor="cs-url">URL</Label>
              <Input
                id="cs-url"
                value={url}
                onChange={(e) => setUrl(e.target.value)}
                placeholder="https://…"
              />
            </div>
          </div>
          <ContentKeywordsPanel contentItemId={item.id} siteId={item.siteId} />
          {item.primaryKeywordId ? (
            <SerpPanel
              keywordId={item.primaryKeywordId}
              snapshot={serp}
              onImported={reloadSerp}
            />
          ) : null}
          {briefs ? (
            <div className="rounded-lg border p-3">
              <div className="mb-2 font-medium text-sm">Brief</div>
              <BriefPanel briefs={briefs} />
            </div>
          ) : item.hasBrief ? (
            <p className="text-muted-foreground text-sm">
              Chargement du brief…
            </p>
          ) : null}
          {item.primaryKeywordId ? (
            <SemanticAnalysisSection
              keywordId={item.primaryKeywordId}
              country={item.keywordCountry ?? item.country}
              profile={semanticProfile}
              onAnalyzed={reloadSemanticProfile}
            />
          ) : null}
          {item.primaryKeywordId ? (
            <div className="rounded-lg border p-3">
              <div className="mb-2 font-medium text-sm">Rédaction</div>
              <KeywordPromptCard keywordId={item.primaryKeywordId} />
            </div>
          ) : (
            <p className="text-muted-foreground text-sm">
              Lie un mot-clé pour générer le prompt de rédaction.
            </p>
          )}
          <div className="flex justify-between pt-2">
            <Button
              variant="ghost"
              className="text-destructive"
              onClick={remove}
            >
              Supprimer
            </Button>
            <Button onClick={save}>Enregistrer</Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
