'use client';

import { useState } from 'react';
import {
  useAdminStore,
  useAdminVerifyStore,
  useAdminSuspendStore,
  useAdminUnsuspendStore,
} from '@/lib/queries/use-admin';
import { ConfirmWithJustificationDialog } from '@/components/admin/confirm-with-justification-dialog';
import { AdminStoreLedgerTab } from './admin-store-ledger-tab';
import { AdminStoreReviewsTab } from './admin-store-reviews-tab';

type Action = 'verify' | 'suspend' | 'unsuspend';
type Tab = 'overview' | 'ledger' | 'reviews';

function fmt(cents: number) {
  return `$${(cents / 100).toLocaleString(undefined, { maximumFractionDigits: 2 })}`;
}

export function StoreDetailClient({ storeId }: { storeId: string }) {
  const { data, isLoading, isError } = useAdminStore(storeId);
  const detail = data?.data;
  const verify = useAdminVerifyStore(storeId);
  const suspend = useAdminSuspendStore(storeId);
  const unsuspend = useAdminUnsuspendStore(storeId);

  const [action, setAction] = useState<Action | null>(null);
  const [tab, setTab] = useState<Tab>('overview');

  if (isLoading) return <div className="text-sm text-slate-400">Loading…</div>;
  if (isError || !detail)
    return (
      <p className="rounded bg-red-50 p-3 text-sm text-red-700">
        Couldn&apos;t load this store.
      </p>
    );

  const onConfirm = (justification: string) => {
    if (action === 'verify') {
      verify.mutate(justification, { onSuccess: () => setAction(null) });
    } else if (action === 'suspend') {
      suspend.mutate(justification, { onSuccess: () => setAction(null) });
    } else if (action === 'unsuspend') {
      unsuspend.mutate(justification, { onSuccess: () => setAction(null) });
    }
  };

  const lastError =
    verify.error?.message ?? suspend.error?.message ?? unsuspend.error?.message ?? null;

  const location = [detail.city, detail.state].filter(Boolean).join(', ') || '—';

  return (
    <div>
      <header className="rounded-lg border border-slate-200 bg-white p-4">
        <div className="flex items-start justify-between">
          <div>
            <h1 className="text-2xl font-bold text-slate-900">{detail.name}</h1>
            <p className="mt-1 text-sm text-slate-500">{location}</p>
            <div className="mt-2 flex gap-2 text-xs">
              {detail.is_suspended && (
                <span className="rounded bg-red-100 px-2 py-0.5 font-medium text-red-700">
                  Suspended
                </span>
              )}
              {detail.is_verified ? (
                <span className="rounded bg-forest-100 px-2 py-0.5 font-medium text-forest-800">
                  Verified
                </span>
              ) : (
                !detail.is_suspended && (
                  <span className="rounded bg-amber-100 px-2 py-0.5 font-medium text-amber-800">
                    Pending
                  </span>
                )
              )}
            </div>
          </div>
          {detail.owner && (
            <div className="text-right text-xs text-slate-500">
              Owner: {detail.owner.name}
              <br />
              {detail.owner.email}
            </div>
          )}
        </div>
      </header>

      {lastError && (
        <p className="mt-4 rounded bg-red-50 p-3 text-sm text-red-700">
          Action failed: {lastError}
        </p>
      )}

      <div className="mt-4 flex gap-1 border-b border-slate-200">
        <button
          type="button"
          onClick={() => setTab('overview')}
          data-testid="store-detail-tab-overview"
          className={`px-4 py-2 text-sm font-medium ${
            tab === 'overview'
              ? 'border-b-2 border-slate-900 text-slate-900'
              : 'text-slate-500 hover:text-slate-700'
          }`}
        >
          Overview
        </button>
        <button
          type="button"
          onClick={() => setTab('ledger')}
          data-testid="store-detail-tab-ledger"
          className={`px-4 py-2 text-sm font-medium ${
            tab === 'ledger'
              ? 'border-b-2 border-slate-900 text-slate-900'
              : 'text-slate-500 hover:text-slate-700'
          }`}
        >
          Ledger
        </button>
        <button
          type="button"
          onClick={() => setTab('reviews')}
          data-testid="store-detail-tab-reviews"
          className={`px-4 py-2 text-sm font-medium ${
            tab === 'reviews'
              ? 'border-b-2 border-slate-900 text-slate-900'
              : 'text-slate-500 hover:text-slate-700'
          }`}
        >
          Reviews
        </button>
      </div>

      {tab === 'ledger' && (
        <div className="mt-4">
          <AdminStoreLedgerTab storeId={storeId} />
        </div>
      )}

      {tab === 'reviews' && (
        <div className="mt-4">
          <AdminStoreReviewsTab storeId={storeId} />
        </div>
      )}

      {tab === 'overview' && (
        <>
      <section className="mt-4 rounded-lg border border-slate-200 bg-white p-4">
        <h2 className="font-semibold text-sm text-slate-700">Admin actions</h2>
        <div className="mt-2 flex gap-2">
          {!detail.is_verified && !detail.is_suspended && (
            <button
              onClick={() => setAction('verify')}
              disabled={verify.isPending}
              className="rounded-md border border-slate-300 px-3 py-1 text-sm hover:bg-slate-50 disabled:opacity-50"
            >
              Verify
            </button>
          )}
          {!detail.is_suspended && (
            <button
              onClick={() => setAction('suspend')}
              disabled={suspend.isPending}
              className="rounded-md border border-red-300 bg-red-50 px-3 py-1 text-sm text-red-700 hover:bg-red-100 disabled:opacity-50"
            >
              Suspend
            </button>
          )}
          {detail.is_suspended && (
            <button
              onClick={() => setAction('unsuspend')}
              disabled={unsuspend.isPending}
              className="rounded-md border border-slate-300 px-3 py-1 text-sm hover:bg-slate-50 disabled:opacity-50"
            >
              Unsuspend
            </button>
          )}
        </div>
      </section>

      <section className="mt-4 grid grid-cols-4 gap-3">
        <Tile label="Active items" value={detail.counters.items_active.toLocaleString()} />
        <Tile label="Draft items" value={detail.counters.items_draft.toLocaleString()} />
        <Tile label="Open orders" value={detail.counters.orders_open.toLocaleString()} />
        <Tile label="Lifetime revenue" value={fmt(detail.counters.lifetime_revenue_cents)} />
      </section>

      <section className="mt-4 rounded-lg border border-slate-200 bg-white p-4">
        <h2 className="font-semibold text-sm text-slate-700">Recent orders</h2>
        {detail.recent_orders.length === 0 ? (
          <p className="mt-2 text-sm text-slate-400">No orders yet.</p>
        ) : (
          <ul className="mt-2 text-sm divide-y divide-slate-100">
            {detail.recent_orders.map((o) => (
              <li key={o.id} className="py-2 flex justify-between">
                <span className="font-mono text-xs text-slate-700">{o.id.slice(0, 8)}</span>
                <span className="text-slate-500">{o.status}</span>
                <span>{fmt(o.total)}</span>
                <span className="text-xs text-slate-400">
                  {new Date(o.created_at).toLocaleDateString()}
                </span>
              </li>
            ))}
          </ul>
        )}
      </section>

      <section className="mt-4 rounded-lg border border-slate-200 bg-white p-4">
        <h2 className="font-semibold text-sm text-slate-700">Recent items</h2>
        {detail.recent_items.length === 0 ? (
          <p className="mt-2 text-sm text-slate-400">No items yet.</p>
        ) : (
          <ul className="mt-2 text-sm divide-y divide-slate-100">
            {detail.recent_items.map((i) => (
              <li key={i.id} className="py-2 flex justify-between">
                <span>{i.title}</span>
                <span className="text-slate-500">{i.status}</span>
                <span>{fmt(i.price)}</span>
              </li>
            ))}
          </ul>
        )}
      </section>

      {detail.is_suspended && detail.suspension_reason && (
        <section className="mt-4 rounded-lg border border-red-200 bg-red-50 p-4">
          <h2 className="font-semibold text-sm text-red-800">Suspension details</h2>
          <p className="mt-1 text-xs text-red-700">
            Suspended {detail.suspended_at && new Date(detail.suspended_at).toLocaleString()}
          </p>
          <p className="mt-2 text-sm text-red-900">{detail.suspension_reason}</p>
        </section>
      )}
        </>
      )}

      <ConfirmWithJustificationDialog
        open={action === 'verify'}
        title="Verify this store?"
        description="The store will appear in the public marketplace."
        confirmLabel="Verify"
        onConfirm={onConfirm}
        onCancel={() => setAction(null)}
        isPending={verify.isPending}
      />
      <ConfirmWithJustificationDialog
        open={action === 'suspend'}
        title="Suspend this store?"
        description="All open orders will be cancelled and refunded; the store is removed from the marketplace immediately."
        confirmLabel="Suspend"
        onConfirm={onConfirm}
        onCancel={() => setAction(null)}
        isPending={suspend.isPending}
      />
      <ConfirmWithJustificationDialog
        open={action === 'unsuspend'}
        title="Unsuspend this store?"
        description="The store will be unsuspended but stays unverified. You'll need to verify separately to bring it back into the marketplace."
        confirmLabel="Unsuspend"
        onConfirm={onConfirm}
        onCancel={() => setAction(null)}
        isPending={unsuspend.isPending}
      />
    </div>
  );
}

function Tile({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-lg border border-slate-200 bg-white p-3">
      <div className="text-xs font-medium text-slate-500">{label}</div>
      <div className="mt-1 text-xl font-bold text-slate-900">{value}</div>
    </div>
  );
}
