import { AccountAvatar, Card } from "../../../components/ui";
import type { ThreadsAccount } from "../../../domain/types";
import { useI18n } from "../../../i18n/I18nContext";
import type { WizardDraft } from "../wizardState";

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

export function CrewStep({ draft, accounts, onChange }: Props) {
  const { t } = useI18n();
  const usable = accounts.filter((a) => a.is_usable);

  function setLead(id: string) {
    const cast = draft.cast_account_ids.filter((c) => c !== id);
    const steps = draft.steps.map((s, i) =>
      i === 0 ? { ...s, account_id: id, kind: "root" as const } : s,
    );
    onChange({ lead_account_id: id, cast_account_ids: cast, steps });
  }

  function toggleCast(id: string) {
    if (id === draft.lead_account_id) return;
    const has = draft.cast_account_ids.includes(id);
    onChange({
      cast_account_ids: has
        ? draft.cast_account_ids.filter((c) => c !== id)
        : [...draft.cast_account_ids, id],
    });
  }

  return (
    <Card title={t("wizard.crew.title")}>
      <div className="hb-stack">
        <p className="hb-field__label">{t("wizard.crew.lead")}</p>
        {usable.length === 0 ? <p className="text-muted">{t("wizard.crew.noUsable")}</p> : null}
        {accounts.map((acc) => (
          <label key={`lead-${acc.id}`} className={`hb-choice${!acc.is_usable ? " is-disabled" : ""}`}>
            <input
              type="radio"
              name="lead"
              disabled={!acc.is_usable}
              checked={draft.lead_account_id === acc.id}
              onChange={() => setLead(acc.id)}
            />
            <AccountAvatar account={acc} />
            <span>
              <strong>{acc.display_name}</strong>
              <span className="text-muted"> @{acc.username}</span>
              {!acc.is_usable ? <span className="text-muted"> · {t("wizard.crew.unusable")}</span> : null}
            </span>
          </label>
        ))}

        <p className="hb-field__label" style={{ marginTop: "1rem" }}>
          {t("wizard.crew.cast")}
        </p>
        {accounts
          .filter((a) => a.id !== draft.lead_account_id)
          .map((acc) => (
            <label key={`cast-${acc.id}`} className={`hb-choice${!acc.is_usable ? " is-disabled" : ""}`}>
              <input
                type="checkbox"
                disabled={!acc.is_usable}
                checked={draft.cast_account_ids.includes(acc.id)}
                onChange={() => toggleCast(acc.id)}
              />
              <AccountAvatar account={acc} />
              <span>
                <strong>{acc.display_name}</strong>
                <span className="text-muted"> @{acc.username}</span>
              </span>
            </label>
          ))}
      </div>
    </Card>
  );
}
