"use client";

import { useState } from "react";
import {
  PageHeader,
  StatTile,
  MoneyText,
  Numeric,
  Button,
  Sheet,
  StatusBadge,
  SegmentedControl,
  EmptyState,
  ErrorState,
  SkeletonTable,
  Tone,
} from "@/components/ui";
import { useApi } from "@/hooks/useApi";
import { api, InvestorAccount, InvestorDetail, Withdrawal } from "@/lib/api";
import { useLocale } from "@/i18n/LocaleProvider";

type Tab = "all" | "pending" | "withdrawals";

const statusTone: Record<string, Tone> = {
  ACTIVE: "success",
  PENDING: "warning",
  SUSPENDED: "danger",
  REJECTED: "danger",
};

export default function InvestorsPage() {
  const { t } = useLocale();
  const [tab, setTab] = useState<Tab>("all");
  const [detailId, setDetailId] = useState<string | null>(null);

  return (
    <div>
      <PageHeader
        titleKey="nav.investors"
        actions={
          <SegmentedControl<Tab>
            value={tab}
            onChange={setTab}
            options={[
              { value: "all", label: t("inv.tabAll") },
              { value: "pending", label: t("inv.tabPending") },
              { value: "withdrawals", label: t("inv.tabWithdrawals") },
            ]}
          />
        }
      />

      {tab === "all" && <AllInvestors onView={setDetailId} />}
      {tab === "pending" && <PendingSignups />}
      {tab === "withdrawals" && <Withdrawals />}

      <InvestorDetailSheet id={detailId} onClose={() => setDetailId(null)} />
    </div>
  );
}

/* ------------------------------------------------------------------ all list */

function AllInvestors({ onView }: { onView: (id: string) => void }) {
  const { t } = useLocale();
  const state = useApi(() => api.investorAccounts(), []);
  const [busy, setBusy] = useState<string | null>(null);

  const act = async (fn: () => Promise<unknown>, id: string) => {
    setBusy(id);
    try {
      await fn();
      state.reload();
    } finally {
      setBusy(null);
    }
  };

  const rows = state.data ?? [];
  if (state.loading) return <SkeletonTable rows={6} />;
  if (state.error) return <ErrorState onRetry={state.reload} />;
  if (rows.length === 0)
    return <EmptyState icon={<span className="text-xl">🧑‍💼</span>} title={t("inv.emptyAll")} />;

  return (
    <div className="card overflow-x-auto">
      <table className="w-full min-w-[720px] text-sm">
        <thead>
          <tr className="border-b border-line">
            <Th>{t("inv.colName")}</Th>
            <Th>{t("inv.colScooters")}</Th>
            <Th>{t("inv.colStatus")}</Th>
            <Th>{t("common.actions")}</Th>
          </tr>
        </thead>
        <tbody>
          {rows.map((i) => (
            <tr key={i.id} className="border-b border-line last:border-b-0">
              <td className="px-4 py-3">
                <div className="font-medium">{i.name}</div>
                <div className="text-xs text-muted">{i.email}</div>
              </td>
              <td className="px-4 py-3">
                <Numeric>{i.ownedScooterCount}</Numeric>
              </td>
              <td className="px-4 py-3">
                <StatusBadge tone={statusTone[i.status] ?? "neutral"}>{i.status}</StatusBadge>
              </td>
              <td className="px-4 py-3">
                <div className="flex flex-wrap gap-2">
                  <Button variant="secondary" onClick={() => onView(i.id)}>
                    {t("inv.view")}
                  </Button>
                  {i.status === "ACTIVE" ? (
                    <Button
                      variant="danger"
                      disabled={busy === i.id}
                      onClick={() => act(() => api.suspendInvestor(i.id), i.id)}
                    >
                      {t("inv.suspend")}
                    </Button>
                  ) : i.status === "SUSPENDED" ? (
                    <Button
                      variant="secondary"
                      disabled={busy === i.id}
                      onClick={() => act(() => api.reactivateInvestor(i.id), i.id)}
                    >
                      {t("inv.reactivate")}
                    </Button>
                  ) : null}
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

/* ------------------------------------------------------------- pending signups */

function PendingSignups() {
  const { t } = useLocale();
  const state = useApi(() => api.pendingInvestors(), []);
  const [busy, setBusy] = useState<string | null>(null);

  const act = async (fn: () => Promise<unknown>, id: string) => {
    setBusy(id);
    try {
      await fn();
      state.reload();
    } finally {
      setBusy(null);
    }
  };

  const rows = state.data ?? [];
  if (state.loading) return <SkeletonTable rows={4} />;
  if (state.error) return <ErrorState onRetry={state.reload} />;
  if (rows.length === 0)
    return <EmptyState icon={<span className="text-xl">✅</span>} title={t("inv.emptyPending")} />;

  return (
    <div className="card overflow-x-auto">
      <table className="w-full min-w-[720px] text-sm">
        <thead>
          <tr className="border-b border-line">
            <Th>{t("inv.colName")}</Th>
            <Th>{t("inv.colPhone")}</Th>
            <Th>{t("inv.colRequested")}</Th>
            <Th>{t("common.actions")}</Th>
          </tr>
        </thead>
        <tbody>
          {rows.map((i: InvestorAccount) => (
            <tr key={i.id} className="border-b border-line last:border-b-0">
              <td className="px-4 py-3">
                <div className="font-medium">{i.name}</div>
                <div className="text-xs text-muted">{i.email}</div>
              </td>
              <td className="px-4 py-3">{i.phone ?? "-"}</td>
              <td className="px-4 py-3 text-xs text-muted">
                {i.createdAt ? new Date(i.createdAt).toLocaleDateString() : "-"}
              </td>
              <td className="px-4 py-3">
                <div className="flex flex-wrap gap-2">
                  <Button
                    variant="primary"
                    disabled={busy === i.id}
                    onClick={() => act(() => api.approveInvestor(i.id), i.id)}
                  >
                    {t("inv.approve")}
                  </Button>
                  <Button
                    variant="danger"
                    disabled={busy === i.id}
                    onClick={() => act(() => api.rejectInvestor(i.id), i.id)}
                  >
                    {t("inv.reject")}
                  </Button>
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

/* ---------------------------------------------------------------- withdrawals */

function Withdrawals() {
  const { t } = useLocale();
  const state = useApi(() => api.withdrawals(false), []);
  const [busy, setBusy] = useState<string | null>(null);

  const act = async (fn: () => Promise<unknown>, id: string) => {
    setBusy(id);
    try {
      await fn();
      state.reload();
    } finally {
      setBusy(null);
    }
  };

  const rows = state.data ?? [];
  if (state.loading) return <SkeletonTable rows={5} />;
  if (state.error) return <ErrorState onRetry={state.reload} />;
  if (rows.length === 0)
    return <EmptyState icon={<span className="text-xl">💸</span>} title={t("inv.emptyWithdrawals")} />;

  return (
    <div className="card overflow-x-auto">
      <table className="w-full min-w-[820px] text-sm">
        <thead>
          <tr className="border-b border-line">
            <Th>{t("inv.colInvestor")}</Th>
            <Th>{t("inv.colAmount")}</Th>
            <Th>{t("inv.colIban")}</Th>
            <Th>{t("inv.colStatus")}</Th>
            <Th>{t("common.actions")}</Th>
          </tr>
        </thead>
        <tbody>
          {rows.map((r: Withdrawal) => (
            <tr key={r.id} className="border-b border-line last:border-b-0">
              <td className="px-4 py-3">
                <div className="font-medium">{r.investorName ?? r.investorId.slice(0, 8)}</div>
                <div className="text-xs text-muted">
                  {new Date(r.requestedAt).toLocaleDateString()}
                </div>
              </td>
              <td className="px-4 py-3">
                <MoneyText amount={r.amount} currency={r.currency} />
              </td>
              <td className="px-4 py-3 font-mono text-xs">{r.iban ?? "-"}</td>
              <td className="px-4 py-3">
                <StatusBadge tone={statusTone[r.status] ?? "neutral"}>{r.status}</StatusBadge>
              </td>
              <td className="px-4 py-3">
                {r.status === "PENDING" ? (
                  <div className="flex flex-wrap gap-2">
                    <Button
                      variant="primary"
                      disabled={busy === r.id}
                      onClick={() => act(() => api.approveWithdrawal(r.id), r.id)}
                    >
                      {t("inv.approve")}
                    </Button>
                    <Button
                      variant="danger"
                      disabled={busy === r.id}
                      onClick={() => act(() => api.rejectWithdrawal(r.id), r.id)}
                    >
                      {t("inv.reject")}
                    </Button>
                  </div>
                ) : (
                  <span className="text-xs text-muted">{r.decidedBy ?? "-"}</span>
                )}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

/* --------------------------------------------------------------- detail sheet */

function InvestorDetailSheet({ id, onClose }: { id: string | null; onClose: () => void }) {
  const { t } = useLocale();
  const state = useApi<InvestorDetail | null>(
    () => (id ? api.investorDetail(id) : Promise.resolve(null)),
    [id],
  );

  const d = state.data;
  const cur = d?.wallet.currency ?? "SAR";

  return (
    <Sheet open={id != null} onClose={onClose} title={d?.investor.name ?? t("inv.detailTitle")}>
      {state.loading || !d ? (
        <SkeletonTable rows={4} />
      ) : (
        <div className="space-y-5">
          <div className="text-center text-sm text-muted">{d.investor.email}</div>

          <div className="grid grid-cols-2 gap-3">
            <StatTile label={t("wallet.available")} value={`${d.wallet.available.toFixed(2)} ${cur}`} tone="brand" />
            <StatTile label={t("wallet.totalEarned")} value={`${d.wallet.totalEarned.toFixed(2)} ${cur}`} tone="success" />
            <StatTile label={t("wallet.withdrawn")} value={`${d.wallet.withdrawn.toFixed(2)} ${cur}`} />
            <StatTile label={t("inv.scooters")} value={d.investor.ownedScooterCount} tone="info" />
          </div>

          {/* Per-scooter earnings */}
          <div>
            <div className="mb-2 text-sm font-semibold">{t("inv.perScooter")}</div>
            {d.scooters.length === 0 ? (
              <p className="text-sm text-muted">{t("inv.noScooters")}</p>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b border-line text-xs text-muted">
                      <th className="py-2 text-start font-medium">{t("inv.colVehicle")}</th>
                      <th className="py-2 text-end font-medium">{t("inv.colRides")}</th>
                      <th className="py-2 text-end font-medium">{t("inv.colEarned")}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {d.scooters.map((s) => (
                      <tr key={s.scooterId} className="border-b border-line/60">
                        <td className="py-2">{s.qrCode ?? s.scooterId.slice(0, 8)}</td>
                        <td className="py-2 text-end">
                          <Numeric>{s.rides}</Numeric>
                        </td>
                        <td className="py-2 text-end">
                          <Numeric>{s.totalEarnings.toFixed(2)}</Numeric> {cur}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>

          {/* Transaction history */}
          <div>
            <div className="mb-2 text-sm font-semibold">{t("wallet.history")}</div>
            {d.transactions.length === 0 ? (
              <p className="text-sm text-muted">{t("wallet.noHistory")}</p>
            ) : (
              <div className="max-h-64 overflow-y-auto">
                <table className="w-full text-sm">
                  <tbody>
                    {d.transactions.map((r, i) => (
                      <tr key={i} className="border-b border-line/60">
                        <td className="py-2">
                          {r.type === "EARNING" ? t("wallet.typeEarning") : t("wallet.typeWithdrawal")}
                          {r.status ? ` · ${r.status}` : ""}
                        </td>
                        <td className="py-2 text-end">
                          <MoneyText
                            amount={r.type === "EARNING" ? r.amount : -r.amount}
                            currency={r.currency}
                            signed
                          />
                        </td>
                        <td className="py-2 text-end text-xs text-muted">
                          {new Date(r.at).toLocaleDateString()}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>
      )}
    </Sheet>
  );
}

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