"use client";

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

type Initial = {
  fullName: string;
  nik: string;
  birthDate: Date;
  address: string;
  ktpImageUrl: string;
  selfieUrl: string;
  bankName: string;
  bankAccountNumber: string;
  bankAccountName: string;
} | null;

function toYmd(d: Date): string {
  const y = d.getUTCFullYear();
  const m = String(d.getUTCMonth() + 1).padStart(2, "0");
  const day = String(d.getUTCDate()).padStart(2, "0");
  return `${y}-${m}-${day}`;
}

export function VerifyForm({ initial }: { initial: Initial }) {
  const router = useRouter();
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError("");
    setLoading(true);
    const formData = new FormData(e.currentTarget);
    const result = await submitVerificationAction(formData);
    setLoading(false);
    if (result.error) {
      setError(result.error);
      return;
    }
    router.refresh();
  }

  const inputCls =
    "w-full rounded-xl border border-neutral-200 bg-neutral-50 px-4 py-2.5 text-sm text-neutral-800 transition-colors placeholder:text-neutral-400 focus:bg-white";

  return (
    <form
      onSubmit={handleSubmit}
      className="space-y-5 rounded-2xl border border-neutral-200 bg-white p-6 shadow-sm sm:p-8"
    >
      {error && (
        <div className="rounded-xl bg-red-50 px-4 py-3 text-sm font-medium text-red-600">
          {error}
        </div>
      )}

      <section>
        <h2 className="mb-3 text-base font-bold text-neutral-900">📇 Data KTP</h2>
        <div className="grid gap-4 sm:grid-cols-2">
          <div className="sm:col-span-2">
            <label className="mb-1.5 block text-sm font-semibold text-neutral-700">
              Nama Lengkap (sesuai KTP)
            </label>
            <input
              name="fullName"
              type="text"
              required
              defaultValue={initial?.fullName ?? ""}
              className={inputCls}
              placeholder="Mis. Budi Santoso"
            />
          </div>
          <div>
            <label className="mb-1.5 block text-sm font-semibold text-neutral-700">
              NIK (16 digit)
            </label>
            <input
              name="nik"
              type="text"
              inputMode="numeric"
              pattern="\d{16}"
              maxLength={16}
              required
              defaultValue={initial?.nik ?? ""}
              className={inputCls}
              placeholder="3201xxxxxxxxxxxx"
            />
          </div>
          <div>
            <label className="mb-1.5 block text-sm font-semibold text-neutral-700">
              Tanggal Lahir
            </label>
            <input
              name="birthDate"
              type="date"
              required
              defaultValue={initial ? toYmd(new Date(initial.birthDate)) : ""}
              className={inputCls}
            />
          </div>
          <div className="sm:col-span-2">
            <label className="mb-1.5 block text-sm font-semibold text-neutral-700">
              Alamat (sesuai KTP)
            </label>
            <textarea
              name="address"
              required
              rows={3}
              defaultValue={initial?.address ?? ""}
              className={inputCls}
              placeholder="Jalan, RT/RW, kelurahan, kota, provinsi"
            />
          </div>
        </div>
      </section>

      <section>
        <h2 className="mb-3 text-base font-bold text-neutral-900">🖼️ Foto</h2>
        <p className="mb-3 text-xs text-neutral-500">
          Upload foto ke hosting (imgur, imgbb, dll) lalu paste URL-nya. Foto akan
          dilihat tim admin saat review.
        </p>
        <div className="space-y-4">
          <div>
            <label className="mb-1.5 block text-sm font-semibold text-neutral-700">
              URL Foto KTP
            </label>
            <input
              name="ktpImageUrl"
              type="url"
              required
              defaultValue={initial?.ktpImageUrl ?? ""}
              className={inputCls}
              placeholder="https://i.imgur.com/xxxx.jpg"
            />
          </div>
          <div>
            <label className="mb-1.5 block text-sm font-semibold text-neutral-700">
              URL Selfie dengan KTP
            </label>
            <input
              name="selfieUrl"
              type="url"
              required
              defaultValue={initial?.selfieUrl ?? ""}
              className={inputCls}
              placeholder="https://i.imgur.com/yyyy.jpg"
            />
          </div>
        </div>
      </section>

      <section>
        <h2 className="mb-3 text-base font-bold text-neutral-900">🏦 Rekening Bank</h2>
        <div className="grid gap-4 sm:grid-cols-2">
          <div>
            <label className="mb-1.5 block text-sm font-semibold text-neutral-700">
              Nama Bank
            </label>
            <input
              name="bankName"
              type="text"
              required
              defaultValue={initial?.bankName ?? ""}
              className={inputCls}
              placeholder="Mis. BCA, Mandiri, BRI"
            />
          </div>
          <div>
            <label className="mb-1.5 block text-sm font-semibold text-neutral-700">
              Nomor Rekening
            </label>
            <input
              name="bankAccountNumber"
              type="text"
              inputMode="numeric"
              required
              defaultValue={initial?.bankAccountNumber ?? ""}
              className={inputCls}
              placeholder="1234567890"
            />
          </div>
          <div className="sm:col-span-2">
            <label className="mb-1.5 block text-sm font-semibold text-neutral-700">
              Nama Pemilik Rekening
            </label>
            <input
              name="bankAccountName"
              type="text"
              required
              defaultValue={initial?.bankAccountName ?? ""}
              className={inputCls}
              placeholder="Sesuai buku tabungan"
            />
          </div>
        </div>
      </section>

      <button
        type="submit"
        disabled={loading}
        className="w-full 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 ? "Mengirim..." : "Ajukan Verifikasi"}
      </button>

      <p className="text-center text-xs text-neutral-500">
        Data KTP & rekening hanya digunakan untuk verifikasi dan tidak akan
        ditampilkan ke pengguna lain.
      </p>
    </form>
  );
}
