'use client';

import { ChevronRight, Search } from 'lucide-react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';

import { TenantStatusBadge } from '@/components/admin/tenant-status-badge';
import { EmptyBoxIllustration, NoResultsIllustration } from '@/components/illustrations';
import { PageHeader } from '@/components/layout/page-header';
import { Avatar } from '@/components/ui/avatar';
import { Card } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Segmented } from '@/components/ui/segmented';
import { EmptyState, ErrorState } from '@/components/ui/states';
import { Skeleton } from '@/components/ui/skeleton';
import { ApiError, apiEnvelope } from '@/lib/api-client';
import { formatMoney } from '@/lib/money';
import { formatRelative } from '@/lib/shipments';

interface TenantRow {
  id: string;
  name: string;
  status: string;
  ownerEmail: string | null;
  walletBalanceMinor: number;
  shipmentsCount: number;
  createdAt: string;
  currency: string;
}

export default function AdminTenantsPage() {
  const router = useRouter();
  const [q, setQ] = useState('');
  const [status, setStatus] = useState('');
  const query = `?page=1&pageSize=50${q.trim() ? `&q=${encodeURIComponent(q.trim())}` : ''}${status ? `&status=${status}` : ''}`;
  const list = useQuery({
    queryKey: ['admin', 'tenants', query],
    queryFn: () => apiEnvelope<{ data: TenantRow[] }>(`/admin/tenants${query}`),
  });
  const rows = list.data?.data ?? [];
  const filtered = q.trim().length > 0 || status.length > 0;

  return (
    <div className="grid gap-5">
      <PageHeader title="Tenants" description="Search and open tenant workspaces." />
      <Card className="flex flex-col gap-3 p-3 sm:flex-row sm:items-center">
        <div className="min-w-0 flex-1">
          <Input type="search" aria-label="Search tenants" leading={<Search />} value={q} placeholder="Search name or owner email" onChange={(event) => setQ(event.target.value)} />
        </div>
        <Segmented<'' | 'ACTIVE' | 'SUSPENDED'>
          label="Tenant status"
          value={status as '' | 'ACTIVE' | 'SUSPENDED'}
          onChange={setStatus}
          options={[
            { value: '', label: 'All' },
            { value: 'ACTIVE', label: 'Active' },
            { value: 'SUSPENDED', label: 'Suspended' },
          ]}
          className="h-11 items-center self-start sm:self-auto"
        />
      </Card>

      {list.isLoading ? (
        <Card className="overflow-hidden p-0" aria-hidden="true">
          {Array.from({ length: 6 }, (_, index) => (
            <div key={index} className="flex h-16 items-center gap-4 border-b border-border px-5 last:border-b-0">
              <Skeleton className="h-9 w-9 rounded-md" />
              <Skeleton className="h-4 w-48" />
              <Skeleton className="ml-auto h-5 w-16 rounded-pill" />
            </div>
          ))}
        </Card>
      ) : null}
      {list.error instanceof ApiError ? (
        <Card>
          <ErrorState message={list.error.message} requestId={list.error.requestId} onRetry={() => void list.refetch()} />
        </Card>
      ) : null}
      {list.data !== undefined && rows.length === 0 ? (
        <Card>
          <EmptyState
            illustration={filtered ? <NoResultsIllustration size={110} /> : <EmptyBoxIllustration size={110} />}
            title={filtered ? 'No tenants match your search' : 'No tenants yet'}
          />
        </Card>
      ) : null}
      {rows.length > 0 ? (
        <Card className="overflow-hidden p-0">
          <div className="overflow-x-auto">
            <table className="w-full min-w-[760px] text-left text-small">
              <thead>
                <tr className="h-11 border-b border-border bg-surface-muted/80 text-caption font-semibold uppercase tracking-[0.08em] text-muted-foreground">
                  <th scope="col" className="pl-5 pr-3 font-semibold">Tenant</th>
                  <th scope="col" className="px-3 font-semibold">Status</th>
                  <th scope="col" className="px-3 text-right font-semibold">Wallet</th>
                  <th scope="col" className="px-3 text-right font-semibold">Shipments</th>
                  <th scope="col" className="px-3 font-semibold">Created</th>
                  <th scope="col" className="w-10 pr-4">
                    <span className="sr-only">Open</span>
                  </th>
                </tr>
              </thead>
              <tbody>
                {rows.map((tenant) => (
                  <tr
                    key={tenant.id}
                    className="group h-16 cursor-pointer border-b border-border transition-colors last:border-b-0 hover:bg-surface-muted/60"
                    onClick={() => router.push(`/admin/tenants/${tenant.id}`)}
                  >
                    <td className="pl-5 pr-3">
                      <span className="flex items-center gap-3">
                        <Avatar name={tenant.name} size="md" shape="square" />
                        <span className="min-w-0">
                          <Link
                            href={`/admin/tenants/${tenant.id}`}
                            onClick={(event) => event.stopPropagation()}
                            className="block truncate font-semibold text-foreground underline-offset-4 hover:underline"
                          >
                            {tenant.name}
                          </Link>
                          <span className="block truncate text-caption text-muted-foreground">{tenant.ownerEmail ?? 'No owner'}</span>
                        </span>
                      </span>
                    </td>
                    <td className="px-3">
                      <TenantStatusBadge status={tenant.status} />
                    </td>
                    <td className="px-3 text-right font-semibold tabular-nums">{formatMoney(tenant.walletBalanceMinor, tenant.currency)}</td>
                    <td className="px-3 text-right tabular-nums">{tenant.shipmentsCount.toLocaleString()}</td>
                    <td className="whitespace-nowrap px-3 text-muted-foreground">{formatRelative(tenant.createdAt)}</td>
                    <td className="pr-4">
                      <ChevronRight className="h-4 w-4 text-subtle-foreground transition-transform group-hover:translate-x-0.5" aria-hidden="true" />
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>
      ) : null}
    </div>
  );
}
