'use client';

import { RefreshCw, Search } from 'lucide-react';
import { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';

import { NoResultsIllustration } from '@/components/illustrations';
import { PageHeader } from '@/components/layout/page-header';
import { Avatar } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
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 { Switch } from '@/components/ui/switch';
import { ApiError, api } from '@/lib/api-client';
import { cn } from '@/lib/utils';

interface CourierRow {
  id: string;
  name: string;
  enabled: boolean;
}

export default function AdminCouriersPage() {
  const queryClient = useQueryClient();
  const [q, setQ] = useState('');
  const [show, setShow] = useState<'all' | 'enabled' | 'disabled'>('all');
  const [refreshing, setRefreshing] = useState(false);
  const list = useQuery({
    queryKey: ['admin', 'couriers'],
    queryFn: () => api<CourierRow[]>('/admin/couriers'),
  });
  const all = list.data ?? [];
  const needle = q.trim().toLowerCase();
  const rows = all.filter(
    (courier) =>
      (needle.length === 0 || courier.name.toLowerCase().includes(needle) || courier.id.toLowerCase().includes(needle)) &&
      (show === 'all' || (show === 'enabled' ? courier.enabled : !courier.enabled)),
  );
  const enabledCount = all.filter((courier) => courier.enabled).length;

  return (
    <div className="grid gap-5">
      <PageHeader
        title="Couriers"
        description={list.data === undefined ? 'Global courier catalog enablement.' : `${enabledCount} of ${all.length} couriers enabled for all tenants.`}
        actions={
          <Button
            type="button"
            variant="secondary"
            loading={refreshing}
            onClick={() => {
              setRefreshing(true);
              void api('/admin/couriers/refresh', { method: 'POST' })
                .then(async () => {
                  toast.success('Catalog refreshed.');
                  await queryClient.invalidateQueries({ queryKey: ['admin', 'couriers'] });
                })
                .catch((error: unknown) => toast.error(error instanceof ApiError ? error.message : 'Refresh failed.'))
                .finally(() => setRefreshing(false));
            }}
          >
            {refreshing ? null : <RefreshCw className="h-4 w-4" aria-hidden="true" />}
            Refresh catalog
          </Button>
        }
      />
      <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 couriers" leading={<Search />} value={q} placeholder="Search courier name or ID" onChange={(event) => setQ(event.target.value)} />
        </div>
        <Segmented<'all' | 'enabled' | 'disabled'>
          label="Courier status"
          value={show}
          onChange={setShow}
          options={[
            { value: 'all', label: 'All' },
            { value: 'enabled', label: 'Enabled' },
            { value: 'disabled', label: 'Disabled' },
          ]}
          className="h-11 items-center self-start sm:self-auto"
        />
      </Card>

      {list.isLoading ? (
        <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3" aria-hidden="true">
          {Array.from({ length: 6 }, (_, index) => (
            <Skeleton key={index} className="h-[84px] rounded-xl" />
          ))}
        </div>
      ) : 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={<NoResultsIllustration size={110} />}
            title={all.length === 0 ? 'No couriers in the catalog' : 'No couriers match'}
            description={all.length === 0 ? 'Refresh the catalog to pull couriers from Easyship.' : 'Try another search or filter.'}
          />
        </Card>
      ) : null}
      {rows.length > 0 ? (
        <ul className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
          {rows.map((courier) => (
            <li key={courier.id}>
              <Card className={cn('flex items-center gap-3 p-4 transition-colors', !courier.enabled && 'bg-surface-muted/60')}>
                <Avatar name={courier.name} size="md" shape="square" className={cn(!courier.enabled && 'opacity-50 grayscale')} />
                <div className="min-w-0 flex-1">
                  <p className={cn('truncate font-semibold', !courier.enabled && 'text-muted-foreground')}>{courier.name}</p>
                  <p className="truncate font-mono text-caption text-subtle-foreground">{courier.id}</p>
                </div>
                <Switch
                  checked={courier.enabled}
                  label={`${courier.enabled ? 'Disable' : 'Enable'} ${courier.name}`}
                  onCheckedChange={(enabled) => {
                    void api(`/admin/couriers/${encodeURIComponent(courier.id)}`, { method: 'PUT', json: { enabled } })
                      .then(async () => {
                        await queryClient.invalidateQueries({ queryKey: ['admin', 'couriers'] });
                      })
                      .catch((error: unknown) => toast.error(error instanceof ApiError ? error.message : 'Update failed.'));
                  }}
                />
              </Card>
            </li>
          ))}
        </ul>
      ) : null}
    </div>
  );
}
