import { useEffect, useState } from "react";
import { Button, Card, Input, Select, Textarea } from "../../../components/ui";
import { useRepos } from "../../../data/DataContext";
import type { Persona } from "../../../domain/types";
import { useI18n } from "../../../i18n/I18nContext";
import { isPersonaReady, personaOptionLabel } from "../../../lib/personaPrompt";
import type { WizardDraft } from "../wizardState";

type Props = {
  draft: WizardDraft;
  onChange: (partial: Partial<WizardDraft>) => void;
};

export function TopicStep({ draft, onChange }: Props) {
  const repos = useRepos();
  const { t } = useI18n();
  const [personas, setPersonas] = useState<Persona[]>([]);
  const [personaId, setPersonaId] = useState("");

  useEffect(() => {
    void (async () => {
      const list = await repos.personas.list();
      const active = await repos.personas.getActiveId();
      setPersonas(list);
      setPersonaId(active || list[0]?.id || "");
    })();
  }, [repos.personas]);

  const ready = isPersonaReady(personas.find((p) => p.id === personaId));

  return (
    <Card title={t("wizard.topic.title")}>
      <div className="hb-stack">
        <Input
          label={t("wizard.topic.name")}
          name="title"
          value={draft.title}
          onChange={(e) => onChange({ title: e.target.value })}
          placeholder={t("wizard.topic.namePh")}
        />
        <Textarea
          label={t("wizard.topic.topic")}
          name="topic"
          value={draft.topic}
          onChange={(e) => onChange({ topic: e.target.value })}
          placeholder={t("wizard.topic.topicPh")}
        />
        <Select
          label={t("wizard.topic.aiView")}
          value={personaId}
          onChange={(e) => {
            setPersonaId(e.target.value);
            void repos.personas.setActiveId(e.target.value);
          }}
        >
          {personas.map((p) => (
            <option key={p.id} value={p.id}>
              {personaOptionLabel(p)}
            </option>
          ))}
        </Select>
        {!ready ? (
          <p className="text-muted" style={{ fontSize: "var(--hb-text-sm)" }}>
            {t("wizard.topic.personaNotReady")}
          </p>
        ) : null}
        <div className="hb-wizard-actions">
          <Button
            type="button"
            variant="ghost"
            onClick={() =>
              onChange({
                title: t("wizard.topic.sampleTitle"),
                topic: t("wizard.topic.sampleTopic"),
              })
            }
          >
            {t("wizard.topic.quickFill")}
          </Button>
        </div>
      </div>
    </Card>
  );
}
