"use client";

import { useCallback, useState } from "react";

import { isSoftLaunchClientEnabled } from "@/lib/soft-launch-client";
import type { TuViFunnelSafePayload } from "@/lib/tuvi-funnel-telemetry.v1";
import { TUVI_FUNNEL_EVENT, queueTuViFunnelTelemetry } from "@/lib/tuvi-funnel-telemetry.v1";
import { postTuViReadingFeedback } from "@/lib/tu-vi-reading-feedback-api";

function RatingRow({
  label,
  value,
  onChange,
  disabled,
}: {
  label: string;
  value: number | null;
  onChange: (n: number) => void;
  disabled: boolean;
}) {
  return (
    <div className="flex flex-col gap-1.5 sm:flex-row sm:items-center sm:justify-between sm:gap-3">
      <span className="min-w-[8rem] font-sans text-[11px] text-stone-500">{label}</span>
      <div className="flex flex-wrap gap-1">
        {[1, 2, 3, 4, 5].map((n) => (
          <button
            key={n}
            type="button"
            disabled={disabled}
            onClick={() => onChange(n)}
            className={`min-h-[36px] min-w-[2.25rem] rounded border px-2 text-xs font-medium transition-colors disabled:opacity-45 ${
              value === n ?
                "border-emerald-600/60 bg-emerald-950/40 text-emerald-100"
              : "border-stone-600/50 bg-stone-950/40 text-stone-300 hover:border-stone-500/60"
            }`}
            aria-pressed={value === n}
          >
            {n}
          </button>
        ))}
      </div>
    </div>
  );
}

export type TuViReadingFeedbackSectionProps = {
  /** Result `chartId` for telemetry (e.g. `result.id`). */
  chartId: string;
  /** When viewing an account saved reading — server checks ownership. */
  savedReadingId?: string | null;
  /** e.g. tu_vi_ket_qua | tu_vi_saved_reading_detail */
  source: string;
  className?: string;
};

export function TuViReadingFeedbackSection({ chartId, savedReadingId, source, className }: TuViReadingFeedbackSectionProps) {
  const [overall, setOverall] = useState<number | null>(null);
  const [accuracy, setAccuracy] = useState<number | null>(null);
  const [clarity, setClarity] = useState<number | null>(null);
  const [mostAcc, setMostAcc] = useState("");
  const [leastAcc, setLeastAcc] = useState("");
  const [wanted, setWanted] = useState("");
  const [busy, setBusy] = useState(false);
  const [done, setDone] = useState(false);
  const [err, setErr] = useState<string | null>(null);

  const telemetryPayload = useCallback(
    (errorCode?: string): TuViFunnelSafePayload => ({
      source,
      savedReadingId: savedReadingId?.trim() || undefined,
      ...(overall != null ? { ratingOverall: overall } : {}),
      ...(accuracy != null ? { ratingAccuracy: accuracy } : {}),
      ...(clarity != null ? { ratingClarity: clarity } : {}),
      hasMostAccurateComment: mostAcc.trim().length > 0,
      hasLeastAccurateComment: leastAcc.trim().length > 0,
      hasWantedMoreComment: wanted.trim().length > 0,
      ...(errorCode ? { errorCode } : {}),
    }),
    [source, savedReadingId, overall, accuracy, clarity, mostAcc, leastAcc, wanted],
  );

  const onSubmit = useCallback(
    async (e: React.FormEvent) => {
      e.preventDefault();
      setErr(null);
      if (overall == null || accuracy == null || clarity == null) {
        setErr("Chọn điểm 1–5 cho cả ba hạng mục.");
        return;
      }
      if (isSoftLaunchClientEnabled()) {
        queueTuViFunnelTelemetry({
          eventType: TUVI_FUNNEL_EVENT.reading_feedback_submit,
          chartId,
          payload: telemetryPayload(),
        });
      }
      setBusy(true);
      try {
        await postTuViReadingFeedback({
          savedReadingId: savedReadingId?.trim() || undefined,
          ratingOverall: overall,
          ratingAccuracy: accuracy,
          ratingClarity: clarity,
          ...(mostAcc.trim() ? { mostAccuratePart: mostAcc.trim().slice(0, 4000) } : {}),
          ...(leastAcc.trim() ? { leastAccuratePart: leastAcc.trim().slice(0, 4000) } : {}),
          ...(wanted.trim() ? { wantedMoreAbout: wanted.trim().slice(0, 4000) } : {}),
          source,
        });
        setDone(true);
        if (isSoftLaunchClientEnabled()) {
          queueTuViFunnelTelemetry({
            eventType: TUVI_FUNNEL_EVENT.reading_feedback_success,
            chartId,
            payload: telemetryPayload(),
          });
        }
      } catch (er) {
        const code = er instanceof Error ? er.message.slice(0, 64) : "unknown";
        if (isSoftLaunchClientEnabled()) {
          queueTuViFunnelTelemetry({
            eventType: TUVI_FUNNEL_EVENT.reading_feedback_failed,
            chartId,
            payload: telemetryPayload(code),
          });
        }
        setErr(er instanceof Error ? er.message : String(er));
      } finally {
        setBusy(false);
      }
    },
    [chartId, overall, accuracy, clarity, mostAcc, leastAcc, wanted, savedReadingId, source, telemetryPayload],
  );

  if (done) {
    return (
      <section
        aria-label="Phản hồi đã gửi"
        className={`rounded-xl border border-emerald-900/35 bg-emerald-950/20 px-4 py-4 ${className ?? ""}`}
      >
        <p className="font-sans text-[13px] leading-relaxed text-emerald-100/95">
          Cảm ơn bạn — phản hồi đã được ghi nhận. Mỗi ý kiến giúp chúng tôi cải thiện luận và trải nghiệm beta.
        </p>
      </section>
    );
  }

  return (
    <section
      aria-label="Góp ý về lá và luận (beta)"
      className={`rounded-xl border border-stone-700/45 bg-[#0a0c14]/75 px-4 py-4 sm:px-5 ${className ?? ""}`}
    >
      <h2 className="font-ctkp-display text-[13px] font-semibold tracking-wide text-amber-200/90">Góp ý nhanh (beta)</h2>
      <p className="mt-1 font-sans text-[11px] leading-relaxed text-stone-500">
        Tuỳ chọn — giúp đội sản phẩm hiểu điều đúng / chưa sát. Không ảnh hưởng tới lá số của bạn.
      </p>

      <form onSubmit={(ev) => void onSubmit(ev)} className="mt-4 space-y-4">
        <div className="space-y-3 rounded-lg border border-stone-800/60 bg-black/20 px-3 py-3">
          <RatingRow label="Tổng thể" value={overall} onChange={setOverall} disabled={busy} />
          <RatingRow label="Độ sát" value={accuracy} onChange={setAccuracy} disabled={busy} />
          <RatingRow label="Rõ ràng" value={clarity} onChange={setClarity} disabled={busy} />
        </div>

        <label className="block">
          <span className="font-sans text-[11px] text-stone-500">Điều nào đúng nhất? (tuỳ chọn)</span>
          <textarea
            value={mostAcc}
            onChange={(e) => setMostAcc(e.target.value)}
            disabled={busy}
            rows={2}
            maxLength={2000}
            className="mt-1 w-full resize-y rounded-lg border border-stone-600/50 bg-stone-950/80 px-3 py-2 font-sans text-[13px] text-stone-100"
            placeholder="Một đoạn hoặc chủ đề bạn thấy khớp…"
          />
        </label>
        <label className="block">
          <span className="font-sans text-[11px] text-stone-500">Điều nào chưa sát? (tuỳ chọn)</span>
          <textarea
            value={leastAcc}
            onChange={(e) => setLeastAcc(e.target.value)}
            disabled={busy}
            rows={2}
            maxLength={2000}
            className="mt-1 w-full resize-y rounded-lg border border-stone-600/50 bg-stone-950/80 px-3 py-2 font-sans text-[13px] text-stone-100"
            placeholder="Phần mơ hồ, lệch hoặc thiếu…"
          />
        </label>
        <label className="block">
          <span className="font-sans text-[11px] text-stone-500">Bạn muốn luận sâu thêm điều gì? (tuỳ chọn)</span>
          <textarea
            value={wanted}
            onChange={(e) => setWanted(e.target.value)}
            disabled={busy}
            rows={2}
            maxLength={2000}
            className="mt-1 w-full resize-y rounded-lg border border-stone-600/50 bg-stone-950/80 px-3 py-2 font-sans text-[13px] text-stone-100"
            placeholder="Cung, chủ đề, hoặc giai đoạn…"
          />
        </label>

        {err ?
          <p className="rounded-lg border border-red-900/40 bg-red-950/20 px-3 py-2 font-sans text-[12px] text-red-200/90" role="alert">
            {err}
          </p>
        : null}

        <button
          type="submit"
          disabled={busy}
          className="min-h-[44px] w-full rounded-lg border border-emerald-700/45 bg-emerald-950/35 px-4 py-2 font-ctkp-serif text-[12px] font-medium tracking-wide text-emerald-100/95 hover:bg-emerald-950/50 disabled:opacity-50 sm:w-auto"
        >
          {busy ? "Đang gửi…" : "Gửi góp ý"}
        </button>
      </form>
    </section>
  );
}
