"use client";

import { useState } from "react";
import { api, WalletWithTransactions } from "@/lib/api";
import { useApi } from "@/hooks/useApi";
import { useSession } from "@/session/SessionProvider";
import { useLocale } from "@/i18n/LocaleProvider";
import {
  Button,
  ErrorState,
  Field,
  MoneyText,
  Numeric,
  PageHeader,
  SkeletonCard,
  StatTile,
  StatusBadge,
  Tone,
} from "@/components/ui";

const withdrawalTone: Record<string, Tone> = {
  PENDING: "warning",
  APPROVED: "success",
  REJECTED: "danger",
};

export default function WalletPage() {
  const { t } = useLocale();
  const { investorId } = useSession();
  const state = useApi<WalletWithTransactions>(() => api.wallet(investorId!), [investorId]);

  const [amount, setAmount] = useState("");
  const [note, setNote] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [ok, setOk] = useState(false);

  const w = state.data?.wallet;
  const tx = state.data?.transactions ?? [];
  const cur = w?.currency ?? "SAR";

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    setBusy(true);
    setError(null);
    setOk(false);
    try {
      await api.requestWithdrawal(investorId!, Number(amount), note || undefined, cur);
      setAmount("");
      setNote("");
      setOk(true);
      state.reload();
    } catch (err) {
      setError(err instanceof Error ? err.message : t("common.error"));
    } finally {
      setBusy(false);
    }
  };

  const amountNum = Number(amount);
  const overBalance = w != null && amountNum > w.available;

  return (
    <div>
      <PageHeader titleKey="nav.wallet" />

      {state.loading ? (
        <SkeletonCard rows={4} />
      ) : state.error ? (
        <ErrorState onRetry={state.reload} />
      ) : w ? (
        <div className="space-y-6">
          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
            <StatTile label={t("wallet.available")} value={`${w.available.toFixed(2)} ${cur}`} tone="brand" />
            <StatTile label={t("wallet.totalEarned")} value={`${w.totalEarned.toFixed(2)} ${cur}`} tone="success" />
            <StatTile label={t("wallet.withdrawn")} value={`${w.withdrawn.toFixed(2)} ${cur}`} />
            <StatTile label={t("wallet.pending")} value={`${w.pending.toFixed(2)} ${cur}`} tone="warning" />
          </div>

          {/* Withdraw request */}
          <form onSubmit={submit} className="card space-y-4 p-5">
            <div className="text-sm font-semibold">{t("wallet.requestTitle")}</div>
            <div className="grid gap-4 sm:grid-cols-2">
              <Field
                label={t("wallet.amount")}
                type="number"
                min="1"
                step="0.01"
                required
                value={amount}
                onChange={(e) => setAmount(e.target.value)}
                placeholder="0.00"
              />
              <Field
                label={t("wallet.note")}
                value={note}
                onChange={(e) => setNote(e.target.value)}
                placeholder={t("wallet.notePlaceholder")}
              />
            </div>
            {overBalance && <p className="text-xs text-danger">{t("wallet.overBalance")}</p>}
            {error && (
              <div className="tint tone-danger rounded-card border p-3 text-sm">{error}</div>
            )}
            {ok && (
              <div className="tint tone-success rounded-card border p-3 text-sm">
                {t("wallet.requested")}
              </div>
            )}
            <Button
              variant="primary"
              type="submit"
              disabled={busy || !amount || amountNum <= 0 || overBalance}
            >
              {busy ? t("common.loading") : t("wallet.requestSubmit")}
            </Button>
            <p className="text-xs text-muted">{t("wallet.ibanNote")}</p>
          </form>

          {/* Transactions */}
          <div>
            <div className="mb-3 text-sm font-semibold">{t("wallet.history")}</div>
            {tx.length === 0 ? (
              <p className="text-sm text-muted">{t("wallet.noHistory")}</p>
            ) : (
              <div className="card overflow-x-auto">
                <table className="w-full min-w-[560px] text-sm">
                  <thead>
                    <tr className="border-b border-line">
                      <Th>{t("wallet.colType")}</Th>
                      <Th>{t("wallet.colAmount")}</Th>
                      <Th>{t("wallet.colStatus")}</Th>
                      <Th>{t("wallet.colDate")}</Th>
                    </tr>
                  </thead>
                  <tbody>
                    {tx.map((r, i) => (
                      <tr key={i} className="border-b border-line last:border-b-0">
                        <td className="px-4 py-3">
                          {r.type === "EARNING" ? t("wallet.typeEarning") : t("wallet.typeWithdrawal")}
                        </td>
                        <td className="px-4 py-3">
                          <MoneyText
                            amount={r.type === "EARNING" ? r.amount : -r.amount}
                            currency={r.currency}
                            signed
                          />
                        </td>
                        <td className="px-4 py-3">
                          {r.status ? (
                            <StatusBadge tone={withdrawalTone[r.status] ?? "neutral"}>
                              {r.status}
                            </StatusBadge>
                          ) : (
                            <span className="text-xs text-muted-dim">-</span>
                          )}
                        </td>
                        <td className="px-4 py-3 text-xs text-muted">
                          {new Date(r.at).toLocaleString()}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>
      ) : null}
    </div>
  );
}

function Th({ children }: { children: React.ReactNode }) {
  return (
    <th className="px-4 py-3 text-start text-[11px] font-semibold uppercase tracking-wider text-muted">
      {children}
    </th>
  );
}
