import { useEffect, useState } from "react";
import { useRepos } from "../../data/DataContext";
import { useI18n } from "../../i18n/I18nContext";
import { useFormatApiError } from "../../lib/apiErrors";
import type { ServiceCase, ServiceFaq, ServiceItem, ServiceProfile } from "../../domain/types";
import { Button, Input, Textarea } from "../ui";
import { SERVICE_AREAS } from "./serviceAreas";

type Draft = {
  services: ServiceItem[];
  cases: ServiceCase[];
  faq: ServiceFaq[];
  forbidden: string;
  service_areas: string[];
  remote_ok: boolean;
  availability: string;
  tone_note: string;
};

const emptyDraft: Draft = {
  services: [{ name: "", price_min: undefined, price_max: undefined, currency: "TWD" }],
  cases: [],
  faq: [],
  forbidden: "",
  service_areas: [],
  remote_ok: false,
  availability: "",
  tone_note: "",
};

function toDraft(p: ServiceProfile): Draft {
  return {
    services: p.services.length ? p.services : emptyDraft.services,
    cases: p.cases,
    faq: p.faq,
    forbidden: p.forbidden.join("\n"),
    service_areas: p.service_areas,
    remote_ok: p.remote_ok,
    availability: p.availability ?? "",
    tone_note: p.tone_note ?? "",
  };
}

function priceValue(n: number | undefined): string {
  return n === undefined || n === 0 ? "" : String(n);
}

function parsePrice(raw: string): number | undefined {
  const n = Number(raw.trim());
  return raw.trim() === "" || !Number.isFinite(n) ? undefined : n;
}

/** 服務檔案是每會員一份，不隸屬任何品牌；判定與回覆生成都讀它。 */
export function ServiceProfileForm({ showIntro = true }: { showIntro?: boolean }) {
  const { t, locale } = useI18n();
  const repos = useRepos();
  const formatError = useFormatApiError();
  const [draft, setDraft] = useState<Draft>(emptyDraft);
  const [exists, setExists] = useState(false);
  const [updatedAt, setUpdatedAt] = useState<number | undefined>(undefined);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const [saved, setSaved] = useState(false);

  useEffect(() => {
    let alive = true;
    setLoading(true);
    repos.radar
      .getServiceProfile()
      .then((p) => {
        if (!alive) return;
        setExists(p.exists);
        setUpdatedAt(p.updated_at);
        if (p.exists) setDraft(toDraft(p));
        setError("");
      })
      .catch((e) => {
        if (alive) setError(formatError(e));
      })
      .finally(() => {
        if (alive) setLoading(false);
      });
    return () => {
      alive = false;
    };
    // 不掛 formatError：它隨語言變動，切語言時重抓會把使用者未存的編輯蓋掉。
  }, [repos]); // eslint-disable-line react-hooks/exhaustive-deps

  function patch(next: Partial<Draft>) {
    setDraft((d) => ({ ...d, ...next }));
    setSaved(false);
  }

  function patchService(index: number, next: Partial<ServiceItem>) {
    patch({ services: draft.services.map((s, i) => (i === index ? { ...s, ...next } : s)) });
  }

  async function save() {
    setSaving(true);
    setError("");
    try {
      const next = await repos.radar.saveServiceProfile({
        services: draft.services
          .filter((s) => s.name.trim() !== "")
          .map((s) => ({
            name: s.name.trim(),
            price_min: s.price_min,
            price_max: s.price_max,
            currency: s.currency?.trim() || "TWD",
          })),
        cases: draft.cases.filter((c) => c.title.trim() !== ""),
        faq: draft.faq.filter((f) => f.question.trim() !== "" && f.answer.trim() !== ""),
        // 一行一條，比逗號分隔安全：禁語本身可能含標點。
        forbidden: draft.forbidden
          .split("\n")
          .map((s) => s.trim())
          .filter(Boolean),
        service_areas: draft.service_areas,
        remote_ok: draft.remote_ok,
        availability: draft.availability.trim(),
        tone_note: draft.tone_note.trim(),
      });
      setDraft(toDraft(next));
      setExists(next.exists);
      setUpdatedAt(next.updated_at);
      setSaved(true);
    } catch (e) {
      // 後端訊息會指到欄位（例如 services[0].name required），照實顯示比翻成通用句有用。
      setError(formatError(e));
    } finally {
      setSaving(false);
    }
  }

  if (loading) return <p className="text-muted">{t("common.loading")}</p>;

  return (
    <section className="hb-radar-page" aria-label={t("radar.profile.title")}>
      {showIntro ? <div className="hb-radar-section">
        <h2 className="hb-radar-section__title">{t("radar.profile.title")}</h2>
        <p className="hb-radar-section__hint">
          {exists ? t("radar.profile.subtitle") : t("radar.profile.firstTimeHint")}
        </p>
        {updatedAt ? (
          <p className="hb-radar-section__hint">
            {t("radar.profile.updatedAt", {
              at: new Date(Math.trunc(updatedAt / 1_000_000)).toLocaleString(locale === "en" ? "en-US" : "zh-TW"),
            })}
          </p>
        ) : null}
      </div> : null}

      {error ? (
        <p className="hb-banner-error" role="alert">
          {error}
        </p>
      ) : null}
      {saved ? (
        <p className="hb-banner-ok" role="status">
          {t("radar.profile.saved")}
        </p>
      ) : null}

      <div className="hb-radar-section">
        <h3 className="hb-radar-section__title">{t("radar.profile.services")}</h3>
        <p className="hb-radar-section__hint">{t("radar.profile.servicesHint")}</p>
        {draft.services.map((s, i) => (
          <div className="hb-radar-row" key={`service-${i}`}>
            <Input
              label={t("radar.profile.serviceName")}
              value={s.name}
              onChange={(e) => patchService(i, { name: e.target.value })}
              placeholder={t("radar.profile.serviceNamePh")}
            />
            <Input
              label={t("radar.profile.priceMin")}
              type="number"
              inputMode="numeric"
              value={priceValue(s.price_min)}
              onChange={(e) => patchService(i, { price_min: parsePrice(e.target.value) })}
            />
            <Input
              label={t("radar.profile.priceMax")}
              type="number"
              inputMode="numeric"
              value={priceValue(s.price_max)}
              onChange={(e) => patchService(i, { price_max: parsePrice(e.target.value) })}
            />
            <Button
              type="button"
              variant="ghost"
              onClick={() => patch({ services: draft.services.filter((_, idx) => idx !== i) })}
              disabled={draft.services.length === 1}
            >
              {t("common.delete")}
            </Button>
          </div>
        ))}
        <Button
          type="button"
          variant="secondary"
          onClick={() =>
            patch({ services: [...draft.services, { name: "", currency: "TWD" }] })
          }
        >
          {t("radar.profile.addService")}
        </Button>
      </div>

      <div className="hb-radar-section">
        <h3 className="hb-radar-section__title">{t("radar.profile.areas")}</h3>
        <p className="hb-radar-section__hint">{t("radar.profile.areasHint")}</p>
        <div className="hb-radar-area-grid">
          {SERVICE_AREAS.map((area) => {
            const on = draft.service_areas.includes(area.code);
            return (
              <button
                key={area.code}
                type="button"
                aria-pressed={on}
                className={`hb-radar-chip${on ? " is-active" : ""}`}
                onClick={() =>
                  patch({
                    service_areas: on
                      ? draft.service_areas.filter((c) => c !== area.code)
                      : [...draft.service_areas, area.code],
                  })
                }
              >
                {locale === "en" ? area.code : area.label}
              </button>
            );
          })}
        </div>
        <label className="hb-radar-check">
          <input
            type="checkbox"
            checked={draft.remote_ok}
            onChange={(e) => patch({ remote_ok: e.target.checked })}
          />
          <span>{t("radar.profile.remoteOk")}</span>
        </label>
      </div>

      <div className="hb-radar-section">
        <h3 className="hb-radar-section__title">{t("radar.profile.forbidden")}</h3>
        <p className="hb-radar-section__hint">{t("radar.profile.forbiddenHint")}</p>
        <Textarea
          name="radar-forbidden"
          label={t("radar.profile.forbidden")}
          rows={4}
          value={draft.forbidden}
          onChange={(e) => patch({ forbidden: e.target.value })}
          placeholder={t("radar.profile.forbiddenPh")}
        />
      </div>

      <div className="hb-radar-section">
        <h3 className="hb-radar-section__title">{t("radar.profile.cases")}</h3>
        <p className="hb-radar-section__hint">{t("radar.profile.casesHint")}</p>
        {draft.cases.map((c, i) => (
          <div className="hb-radar-row" key={`case-${i}`}>
            <Input
              label={t("radar.profile.caseTitle")}
              value={c.title}
              onChange={(e) =>
                patch({ cases: draft.cases.map((x, idx) => (idx === i ? { ...x, title: e.target.value } : x)) })
              }
            />
            <Input
              label={t("radar.profile.caseSummary")}
              value={c.summary ?? ""}
              onChange={(e) =>
                patch({ cases: draft.cases.map((x, idx) => (idx === i ? { ...x, summary: e.target.value } : x)) })
              }
            />
            <Button
              type="button"
              variant="ghost"
              onClick={() => patch({ cases: draft.cases.filter((_, idx) => idx !== i) })}
            >
              {t("common.delete")}
            </Button>
          </div>
        ))}
        <Button
          type="button"
          variant="secondary"
          onClick={() => patch({ cases: [...draft.cases, { title: "" }] })}
        >
          {t("radar.profile.addCase")}
        </Button>
      </div>

      <div className="hb-radar-section">
        <h3 className="hb-radar-section__title">{t("radar.profile.faq")}</h3>
        <p className="hb-radar-section__hint">{t("radar.profile.faqHint")}</p>
        {draft.faq.map((f, i) => (
          <div className="hb-radar-row" key={`faq-${i}`}>
            <Input
              label={t("radar.profile.faqQuestion")}
              value={f.question}
              onChange={(e) =>
                patch({ faq: draft.faq.map((x, idx) => (idx === i ? { ...x, question: e.target.value } : x)) })
              }
            />
            <Input
              label={t("radar.profile.faqAnswer")}
              value={f.answer}
              onChange={(e) =>
                patch({ faq: draft.faq.map((x, idx) => (idx === i ? { ...x, answer: e.target.value } : x)) })
              }
            />
            <Button
              type="button"
              variant="ghost"
              onClick={() => patch({ faq: draft.faq.filter((_, idx) => idx !== i) })}
            >
              {t("common.delete")}
            </Button>
          </div>
        ))}
        <Button
          type="button"
          variant="secondary"
          onClick={() => patch({ faq: [...draft.faq, { question: "", answer: "" }] })}
        >
          {t("radar.profile.addFaq")}
        </Button>
      </div>

      <div className="hb-radar-section">
        <Textarea
          label={t("radar.profile.availability")}
          hint={t("radar.profile.availabilityHint")}
          rows={2}
          value={draft.availability}
          onChange={(e) => patch({ availability: e.target.value })}
        />
        <Textarea
          label={t("radar.profile.toneNote")}
          hint={t("radar.profile.toneNoteHint")}
          rows={2}
          value={draft.tone_note}
          onChange={(e) => patch({ tone_note: e.target.value })}
        />
      </div>

      <div className="hb-radar-actions">
        <Button type="button" onClick={() => void save()} disabled={saving}>
          {saving ? t("common.saving") : t("common.save")}
        </Button>
      </div>
    </section>
  );
}
