"use client";

import { useModule } from "@/lib/modules";

import { useEffect, useState } from "react";
import { Banknote, Loader2, Check, Clock, X } from "lucide-react";
import clsx from "clsx";

type Request = {
  id: string;
  amount: number;
  method: string;
  status: "pending" | "approved" | "declined" | "paid";
  requestedAt: string;
};

const METHOD_LABELS: Record<string, string> = {
  paypal: "PayPal",
  bank: "Bank transfer",
  crypto: "Crypto",
};

/** Ask to cash out, and see where past requests got to. */
export function WithdrawPanel() {
  // Hidden when this module is switched off in System settings.
  const moduleOn = useModule("wallet");

  const [data, setData] = useState<{
    available: number;
    minimum: number;
    methods: string[];
    requests: Request[];
  } | null>(null);
  const [amount, setAmount] = useState("");
  const [method, setMethod] = useState("");
  const [destination, setDestination] = useState("");
  const [busy, setBusy] = useState(false);
  const [note, setNote] = useState<string | null>(null);

  const load = () =>
    fetch("/api/wallet/withdraw")
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => {
        setData(d);

  if (!moduleOn) return null;

        if (d && !method) setMethod(d.methods[0] ?? "");
      })
      .catch(() => {});

  useEffect(() => {
    load();
    // Only on mount — the method default shouldn't reset as you type.
  }, []);

  async function submit() {
    setBusy(true);
    const res = await fetch("/api/wallet/withdraw", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ amount: Number(amount), method, destination }),
    }).catch(() => null);
    setBusy(false);

    const d = res ? await res.json() : null;
    if (!res || !res.ok) {
      setNote(d?.error ?? "Couldn't send that request");
      setTimeout(() => setNote(null), 3000);
      return;
    }

    setAmount("");
    setDestination("");
    setNote("Request sent — an admin will review it.");
    setTimeout(() => setNote(null), 3000);
    load();
  }

  if (!data) return null;

  const money = (n: number) => `$${n.toFixed(2)}`;

  return (
    <div className="wd-card">
      <h3>
        <Banknote size={17} /> Withdraw
      </h3>

      <p className="wd-avail">
        <b>{money(data.available)}</b> available
        <em>Minimum {money(data.minimum)}</em>
      </p>

      <div className="wd-form">
        <input
          type="number"
          value={amount}
          onChange={(e) => setAmount(e.target.value)}
          placeholder="Amount"
          className="wd-input"
        />

        <div className="wd-methods">
          {data.methods.map((m) => (
            <button
              key={m}
              onClick={() => setMethod(m)}
              className={clsx("wd-method", method === m && "on")}
            >
              {METHOD_LABELS[m] ?? m}
            </button>
          ))}
        </div>

        <input
          value={destination}
          onChange={(e) => setDestination(e.target.value)}
          placeholder={
            method === "paypal"
              ? "PayPal email"
              : method === "crypto"
                ? "Wallet address"
                : "Account details"
          }
          className="wd-input"
        />

        <button
          onClick={submit}
          disabled={busy || !amount || !destination}
          className="wd-submit"
        >
          {busy ? <Loader2 size={15} className="animate-spin" /> : <Banknote size={15} />}
          Request withdrawal
        </button>
      </div>

      {note && <p className="wd-note">{note}</p>}

      {data.requests.length > 0 && (
        <div className="wd-list">
          {data.requests.slice(0, 5).map((r) => (
            <div key={r.id} className="wd-row">
              <span className={clsx("wd-status", r.status)}>
                {r.status === "pending" ? (
                  <Clock size={11} />
                ) : r.status === "declined" ? (
                  <X size={11} />
                ) : (
                  <Check size={11} />
                )}
                {r.status}
              </span>
              <span className="flex-1 min-w-0">{METHOD_LABELS[r.method] ?? r.method}</span>
              <b>{money(r.amount)}</b>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
