"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { reviewVerificationAction } from "@/features/organizer/actions";

type Verification = {
  id: string;
  fullName: string;
  /** NIK plaintext, sudah di-decrypt di server sebelum sampai ke komponen ini. */
  nik: string;
  birthDate: Date;
  address: string;
  bankName: string;
  bankAccountNumber: string;
  bankAccountName: string;
  status: "PENDING" | "APPROVED" | "REJECTED";
  rejectionReason: string | null;
  reviewedAt: Date | null;
  createdAt: Date;
  user: { id: string; name: string; email: string };
  reviewedBy: { id: string; name: string; email: string } | null;
};

function formatDate(d: Date): string {
  return new Date(d).toLocaleString("id-ID", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  });
}

export function ReviewCard({ verification }: { verification: Verification }) {
  const router = useRouter();
  const [showReject, setShowReject] = useState(false);
  const [rejectionReason, setRejectionReason] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  async function decide(decision: "APPROVED" | "REJECTED") {
    setError("");
    setLoading(true);
    const fd = new FormData();
    fd.set("verificationId", verification.id);
    fd.set("decision", decision);
    if (decision === "REJECTED") fd.set("rejectionReason", rejectionReason);
    const result = await reviewVerificationAction(fd);
    setLoading(false);
    if (result.error) {
      setError(result.error);
      return;
    }
    setShowReject(false);
    setRejectionReason("");
    router.refresh();
  }

  return (
    <article className="rounded-2xl border border-neutral-200 bg-white p-5 shadow-sm sm:p-6">
      <header className="mb-4 flex flex-wrap items-start justify-between gap-3 border-b border-neutral-100 pb-4">
        <div>
          <h3 className="text-base font-bold text-neutral-900">
            {verification.user.name}
          </h3>
          <p className="text-xs text-neutral-500">
            {verification.user.email} · diajukan{" "}
            {formatDate(verification.createdAt)}
          </p>
        </div>
        <StatusPill status={verification.status} />
      </header>

      <div className="grid gap-4 sm:grid-cols-2">
        <Field label="Nama Lengkap" value={verification.fullName} />
        <Field label="NIK" value={verification.nik} mono />
        <Field
          label="Tanggal Lahir"
          value={formatDate(verification.birthDate)}
        />
        <Field
          label="Bank"
          value={`${verification.bankName} · ${verification.bankAccountNumber}`}
        />
        <Field label="Pemilik Rekening" value={verification.bankAccountName} />
        <Field label="Alamat" value={verification.address} fullWidth />
      </div>

      <div className="mt-5 grid gap-4 sm:grid-cols-2">
        <ImagePreview
          label="Foto KTP"
          src={`/api/files/kyc/${verification.id}/ktp`}
        />
        <ImagePreview
          label="Foto memegang kertas SETRIP"
          src={`/api/files/kyc/${verification.id}/liveness`}
        />
      </div>

      {verification.status === "REJECTED" && verification.rejectionReason && (
        <div className="mt-4 rounded-xl bg-red-50 p-3 text-sm text-red-700">
          <span className="font-semibold">Alasan ditolak:</span>{" "}
          {verification.rejectionReason}
        </div>
      )}

      {verification.reviewedBy && verification.reviewedAt && (
        <p className="mt-4 text-xs text-neutral-500">
          Diproses oleh {verification.reviewedBy.name} pada{" "}
          {formatDate(verification.reviewedAt)}
        </p>
      )}

      {verification.status === "PENDING" && (
        <div className="mt-5 border-t border-neutral-100 pt-4">
          {error && (
            <div className="mb-3 rounded-lg bg-red-50 px-3 py-2 text-xs text-red-600">
              {error}
            </div>
          )}
          {!showReject ? (
            <div className="flex flex-wrap gap-2">
              <button
                type="button"
                onClick={() => decide("APPROVED")}
                disabled={loading}
                className="rounded-xl bg-primary-600 px-4 py-2 text-sm font-bold text-white hover:bg-primary-700 disabled:opacity-50"
              >
                ✅ Setujui
              </button>
              <button
                type="button"
                onClick={() => setShowReject(true)}
                disabled={loading}
                className="rounded-xl border border-red-200 bg-white px-4 py-2 text-sm font-bold text-red-600 hover:bg-red-50 disabled:opacity-50"
              >
                ❌ Tolak
              </button>
            </div>
          ) : (
            <div className="space-y-2">
              <textarea
                value={rejectionReason}
                onChange={(e) => setRejectionReason(e.target.value)}
                rows={2}
                placeholder="Alasan penolakan (akan dilihat user)"
                className="w-full rounded-xl border border-neutral-200 bg-neutral-50 px-3 py-2 text-sm focus:bg-white"
              />
              <div className="flex gap-2">
                <button
                  type="button"
                  onClick={() => decide("REJECTED")}
                  disabled={loading || !rejectionReason.trim()}
                  className="rounded-xl bg-red-600 px-4 py-2 text-sm font-bold text-white hover:bg-red-700 disabled:opacity-50"
                >
                  Konfirmasi Tolak
                </button>
                <button
                  type="button"
                  onClick={() => {
                    setShowReject(false);
                    setRejectionReason("");
                  }}
                  className="rounded-xl border border-neutral-200 bg-white px-4 py-2 text-sm font-medium text-neutral-600 hover:bg-neutral-50"
                >
                  Batal
                </button>
              </div>
            </div>
          )}
        </div>
      )}
    </article>
  );
}

function Field({
  label,
  value,
  mono,
  fullWidth,
}: {
  label: string;
  value: string;
  mono?: boolean;
  fullWidth?: boolean;
}) {
  return (
    <div className={fullWidth ? "sm:col-span-2" : ""}>
      <p className="text-xs font-semibold uppercase tracking-wide text-neutral-500">
        {label}
      </p>
      <p
        className={`mt-0.5 text-sm text-neutral-800 ${mono ? "font-mono" : ""}`}
      >
        {value}
      </p>
    </div>
  );
}

function ImagePreview({ label, src }: { label: string; src: string }) {
  return (
    <div>
      <p className="mb-1.5 text-xs font-semibold uppercase tracking-wide text-neutral-500">
        {label}
      </p>
      <a
        href={src}
        target="_blank"
        rel="noopener noreferrer"
        className="block overflow-hidden rounded-xl border border-neutral-200 bg-neutral-100"
      >
        <div className="relative aspect-4/3 w-full">
          {/* Secure endpoint sends Cache-Control: private,no-store. Use plain <img> to skip Next/Image optimizer. */}
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img src={src} alt={label} className="h-full w-full object-cover" />
        </div>
      </a>
    </div>
  );
}

function StatusPill({
  status,
}: {
  status: "PENDING" | "APPROVED" | "REJECTED";
}) {
  const cfg = {
    PENDING: {
      label: "Pending",
      cls: "bg-amber-50 text-amber-700 ring-amber-200",
    },
    APPROVED: {
      label: "Disetujui",
      cls: "bg-primary-50 text-primary-700 ring-primary-200",
    },
    REJECTED: { label: "Ditolak", cls: "bg-red-50 text-red-700 ring-red-200" },
  }[status];
  return (
    <span
      className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold ring-1 ${cfg.cls}`}
    >
      {cfg.label}
    </span>
  );
}
