"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { signOut, useSession } from "next-auth/react";
import { acceptTermsAction } from "@/features/auth/actions";

export function AcceptTermsForm() {
  const router = useRouter();
  const { update } = useSession();
  const [checked, setChecked] = useState(false);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  async function handleAccept() {
    setError("");
    setLoading(true);
    const result = await acceptTermsAction({ accepted: checked });
    if (result.error) {
      setError(result.error);
      setLoading(false);
      return;
    }
    // Refresh JWT supaya middleware lihat acceptedTermsAndPrivacy=true.
    // Kalau update() gagal (network), JWT callback di server akan re-fetch
    // DB pada request berikutnya karena cookie token masih `false`.
    try {
      await update();
    } catch {
      setError(
        "Persetujuan tersimpan, tapi sesi belum ter-refresh. Coba refresh halaman atau klik lagi."
      );
      setLoading(false);
      return;
    }
    router.replace("/");
    router.refresh();
  }

  return (
    <div className="mt-6 rounded-2xl border border-neutral-200 bg-white p-6 shadow-sm">
      {error && (
        <div className="mb-4 rounded-xl bg-red-50 px-4 py-3 text-sm font-medium text-red-600">
          {error}
        </div>
      )}

      <label className="flex items-start gap-2.5 text-sm text-neutral-700">
        <input
          type="checkbox"
          checked={checked}
          onChange={(e) => setChecked(e.target.checked)}
          className="mt-0.5 h-4 w-4 shrink-0 rounded border-neutral-300 text-primary-600 focus:ring-primary-500"
        />
        <span>
          Saya telah membaca dan menyetujui{" "}
          <Link
            href="/terms"
            target="_blank"
            rel="noopener noreferrer"
            className="font-semibold text-primary-600 hover:text-primary-700"
          >
            Syarat &amp; Ketentuan
          </Link>{" "}
          dan{" "}
          <Link
            href="/privacy"
            target="_blank"
            rel="noopener noreferrer"
            className="font-semibold text-primary-600 hover:text-primary-700"
          >
            Kebijakan Privasi
          </Link>{" "}
          SeTrip.
        </span>
      </label>

      <div className="mt-5 flex flex-col gap-2 sm:flex-row">
        <button
          type="button"
          onClick={handleAccept}
          disabled={!checked || loading}
          className="flex-1 rounded-xl bg-primary-600 py-2.5 text-sm font-bold text-white shadow-lg shadow-primary-600/20 transition-colors hover:bg-primary-700 disabled:opacity-50"
        >
          {loading ? "Memproses..." : "Setuju & Lanjutkan"}
        </button>
        <button
          type="button"
          onClick={() => signOut({ callbackUrl: "/login" })}
          disabled={loading}
          className="rounded-xl border border-neutral-200 bg-white px-4 py-2.5 text-sm font-medium text-neutral-600 hover:bg-neutral-50 disabled:opacity-50"
        >
          Keluar
        </button>
      </div>
    </div>
  );
}
