"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { CircleCheck, CircleX, RefreshCw } from "lucide-react";
import {
  reopenVerificationAction,
  requestReuploadAction,
  reviewVerificationAction,
} from "@/features/organizer/actions";

const REUPLOAD_FIELD_LABELS: { value: string; label: string }[] = [
  { value: "ktpImage", label: "Foto KTP" },
  { value: "liveness", label: "Foto liveness (pegang kertas SETRIP)" },
  { value: "nik", label: "NIK" },
  { value: "bankInfo", label: "Info rekening" },
  { value: "address", label: "Alamat" },
];

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 [showReopen, setShowReopen] = useState(false);
  const [showReupload, setShowReupload] = useState(false);
  const [rejectionReason, setRejectionReason] = useState("");
  const [reopenNote, setReopenNote] = useState("");
  const [reuploadNote, setReuploadNote] = useState("");
  const [reuploadFields, setReuploadFields] = useState<string[]>([]);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  function toggleReuploadField(value: string) {
    setReuploadFields((prev) =>
      prev.includes(value)
        ? prev.filter((v) => v !== value)
        : [...prev, value]
    );
  }

  async function requestReupload() {
    setError("");
    setLoading(true);
    const result = await requestReuploadAction(
      verification.id,
      reuploadFields,
      reuploadNote
    );
    setLoading(false);
    if ("error" in result && result.error) {
      setError(result.error);
      return;
    }
    setShowReupload(false);
    setReuploadFields([]);
    setReuploadNote("");
    router.refresh();
  }

  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();
  }

  async function reopen() {
    setError("");
    setLoading(true);
    const result = await reopenVerificationAction(verification.id, reopenNote);
    setLoading(false);
    if ("error" in result && result.error) {
      setError(result.error);
      return;
    }
    setShowReopen(false);
    setReopenNote("");
    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 === "REJECTED" && (
        <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>
          )}
          {!showReopen ? (
            <button
              type="button"
              onClick={() => setShowReopen(true)}
              disabled={loading}
              className="inline-flex items-center gap-1.5 rounded-xl border border-amber-300 bg-white px-4 py-2 text-sm font-bold text-amber-700 hover:bg-amber-50 disabled:opacity-50"
            >
              <RefreshCw size={18} strokeWidth={2} aria-hidden />
              Buka kembali ke PENDING
            </button>
          ) : (
            <div className="space-y-2 rounded-xl border border-amber-200 bg-amber-50/60 p-3">
              <label className="block text-xs font-semibold text-amber-900">
                Catatan reopen (min 10 karakter — akan disimpan di rejection
                reason sebagai history)
              </label>
              <textarea
                value={reopenNote}
                onChange={(e) => setReopenNote(e.target.value)}
                rows={2}
                maxLength={500}
                placeholder="contoh: Organizer kirim ulang foto KTP jelas via email, siap di-review ulang."
                className="w-full rounded-xl border border-amber-200 bg-white px-3 py-2 text-sm focus:bg-white focus:border-amber-400"
              />
              <div className="flex gap-2">
                <button
                  type="button"
                  onClick={reopen}
                  disabled={loading || reopenNote.trim().length < 10}
                  className="rounded-xl bg-amber-600 px-4 py-2 text-sm font-bold text-white hover:bg-amber-700 disabled:cursor-not-allowed disabled:opacity-50"
                >
                  {loading ? "Memproses..." : "Konfirmasi Reopen"}
                </button>
                <button
                  type="button"
                  onClick={() => {
                    setShowReopen(false);
                    setReopenNote("");
                  }}
                  disabled={loading}
                  className="rounded-xl border border-neutral-200 bg-white px-4 py-2 text-sm font-medium text-neutral-600 hover:bg-neutral-50 disabled:opacity-50"
                >
                  Batal
                </button>
              </div>
            </div>
          )}
        </div>
      )}

      {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="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>
          ) : showReupload ? (
            <div className="space-y-3 rounded-xl border border-amber-200 bg-amber-50/60 p-3">
              <div>
                <label className="mb-1 block text-xs font-semibold text-amber-900">
                  Field yang perlu di-upload ulang (min 1)
                </label>
                <div className="flex flex-wrap gap-2">
                  {REUPLOAD_FIELD_LABELS.map((f) => {
                    const checked = reuploadFields.includes(f.value);
                    return (
                      <label
                        key={f.value}
                        className={`cursor-pointer rounded-full border px-3 py-1 text-xs font-medium ${
                          checked
                            ? "border-amber-600 bg-amber-600 text-white"
                            : "border-amber-200 bg-white text-amber-800 hover:bg-amber-100"
                        }`}
                      >
                        <input
                          type="checkbox"
                          checked={checked}
                          onChange={() => toggleReuploadField(f.value)}
                          className="sr-only"
                        />
                        {f.label}
                      </label>
                    );
                  })}
                </div>
              </div>
              <div>
                <label className="mb-1 block text-xs font-semibold text-amber-900">
                  Catatan untuk organizer (min 10 char — akan dilihat user)
                </label>
                <textarea
                  value={reuploadNote}
                  onChange={(e) => setReuploadNote(e.target.value)}
                  rows={2}
                  maxLength={500}
                  placeholder="contoh: Foto KTP terlalu buram, tolong foto ulang dengan pencahayaan lebih baik."
                  className="w-full rounded-xl border border-amber-200 bg-white px-3 py-2 text-sm focus:border-amber-400"
                />
              </div>
              <div className="flex gap-2">
                <button
                  type="button"
                  onClick={requestReupload}
                  disabled={
                    loading ||
                    reuploadFields.length === 0 ||
                    reuploadNote.trim().length < 10
                  }
                  className="rounded-xl bg-amber-600 px-4 py-2 text-sm font-bold text-white hover:bg-amber-700 disabled:cursor-not-allowed disabled:opacity-50"
                >
                  {loading ? "Memproses..." : "Kirim Permintaan"}
                </button>
                <button
                  type="button"
                  onClick={() => {
                    setShowReupload(false);
                    setReuploadFields([]);
                    setReuploadNote("");
                  }}
                  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 className="flex flex-wrap gap-2">
              <button
                type="button"
                onClick={() => decide("APPROVED")}
                disabled={loading}
                className="inline-flex items-center gap-1.5 rounded-xl bg-primary-600 px-4 py-2 text-sm font-bold text-white hover:bg-primary-700 disabled:opacity-50"
              >
                <CircleCheck size={18} strokeWidth={2} aria-hidden />
                Setujui
              </button>
              <button
                type="button"
                onClick={() => setShowReupload(true)}
                disabled={loading}
                className="inline-flex items-center gap-1.5 rounded-xl border border-amber-300 bg-white px-4 py-2 text-sm font-bold text-amber-700 hover:bg-amber-50 disabled:opacity-50"
              >
                <RefreshCw size={18} strokeWidth={2} aria-hidden />
                Minta re-upload
              </button>
              <button
                type="button"
                onClick={() => setShowReject(true)}
                disabled={loading}
                className="inline-flex items-center gap-1.5 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"
              >
                <CircleX size={18} strokeWidth={2} aria-hidden />
                Tolak
              </button>
            </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>
  );
}
