'use client';

import { useState } from 'react';
import { formatPrice } from '@alqove/shared';
import { useAdminStoreLedger } from '@/lib/queries/use-admin-financials';
import { AdminLedgerAdjustmentDialog } from '@/components/admin/admin-ledger-adjustment-dialog';
import type { LedgerEntry } from '@alqove/api-client';

const PER_PAGE = 20;

const DATE_FORMATTER = new Intl.DateTimeFormat('en-US', {
  month: 'short',
  day: 'numeric',
  year: 'numeric',
  timeZone: 'UTC',
});

function formatDate(iso: string): string {
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return '';
  return DATE_FORMATTER.format(date);
}

function signedAmount(entry: LedgerEntry): {
  value: string;
  positive: boolean;
} {
  const positive = entry.direction === 'credit';
  const sign = positive ? '+' : '−';
  return { value: `${sign}${formatPrice(entry.amount_cents)}`, positive };
}

export function AdminStoreLedgerTab({ storeId }: { storeId: string }) {
  const [page, setPage] = useState(1);
  const [showAdjust, setShowAdjust] = useState(false);

  const { data, isLoading, isError } = useAdminStoreLedger(storeId, {
    page,
    per_page: PER_PAGE,
  });
  const entries = data?.data ?? [];
  const meta = data?.meta;

  return (
    <div>
      <div className="flex items-center justify-between">
        <h2 className="text-sm font-semibold text-slate-700">Ledger</h2>
        <button
          type="button"
          onClick={() => setShowAdjust(true)}
          data-testid="admin-ledger-new-adjustment"
          className="rounded-md border border-slate-300 px-3 py-1 text-xs text-slate-700 hover:bg-slate-50"
        >
          New adjustment
        </button>
      </div>

      {isError && (
        <p
          className="mt-3 rounded bg-red-50 p-3 text-sm text-red-700"
          data-testid="admin-ledger-error"
        >
          Couldn&apos;t load ledger.
        </p>
      )}

      <div className="mt-3 overflow-hidden rounded border border-slate-200 bg-white">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-slate-200">
              <th scope="col" className="px-4 py-3 text-left font-medium text-slate-500">
                Date
              </th>
              <th scope="col" className="px-4 py-3 text-left font-medium text-slate-500">
                Description
              </th>
              <th scope="col" className="px-4 py-3 text-left font-medium text-slate-500">
                Type
              </th>
              <th scope="col" className="px-4 py-3 text-right font-medium text-slate-500">
                Amount
              </th>
              <th scope="col" className="px-4 py-3 text-left font-medium text-slate-500">
                Available
              </th>
            </tr>
          </thead>
          <tbody>
            {isLoading && (
              <tr>
                <td
                  colSpan={5}
                  className="px-4 py-6 text-center text-sm text-slate-400"
                  data-testid="admin-ledger-loading"
                >
                  Loading…
                </td>
              </tr>
            )}
            {!isLoading && entries.length === 0 && (
              <tr>
                <td
                  colSpan={5}
                  className="px-4 py-6 text-center text-sm text-slate-400"
                  data-testid="admin-ledger-empty"
                >
                  No ledger entries yet.
                </td>
              </tr>
            )}
            {entries.map((entry) => {
              const signed = signedAmount(entry);
              return (
                <tr
                  key={entry.id}
                  data-testid={`admin-ledger-row-${entry.id}`}
                  className="border-b border-slate-100 last:border-0 hover:bg-slate-50"
                >
                  <td className="px-4 py-3 text-slate-700">
                    {formatDate(entry.created_at)}
                  </td>
                  <td className="px-4 py-3 text-slate-700">
                    {entry.description ?? (
                      <span className="text-slate-400">—</span>
                    )}
                  </td>
                  <td className="px-4 py-3 text-xs text-slate-500">
                    {entry.entry_type}
                  </td>
                  <td
                    className={`px-4 py-3 text-right font-mono ${
                      signed.positive ? 'text-forest-700' : 'text-rose-700'
                    }`}
                  >
                    {signed.value}
                  </td>
                  <td className="px-4 py-3 text-xs text-slate-500">
                    {formatDate(entry.available_at)}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {meta && meta.last_page > 1 && (
        <div className="mt-3 flex items-center justify-between text-xs text-slate-600">
          <span>
            Page {meta.current_page} of {meta.last_page} · {meta.total} total
          </span>
          <div className="flex gap-2">
            <button
              type="button"
              onClick={() => setPage((p) => Math.max(1, p - 1))}
              disabled={page <= 1}
              className="rounded border border-slate-300 px-3 py-1 disabled:cursor-not-allowed disabled:opacity-50 hover:bg-slate-50"
            >
              Previous
            </button>
            <button
              type="button"
              onClick={() => setPage((p) => p + 1)}
              disabled={page >= meta.last_page}
              className="rounded border border-slate-300 px-3 py-1 disabled:cursor-not-allowed disabled:opacity-50 hover:bg-slate-50"
            >
              Next
            </button>
          </div>
        </div>
      )}

      <AdminLedgerAdjustmentDialog
        open={showAdjust}
        storeId={storeId}
        onClose={() => setShowAdjust(false)}
      />
    </div>
  );
}
