'use client';

import { useQuery } from '@tanstack/react-query';
import { adminClient } from '@/lib/api';
import { formatCount } from '@/lib/format';
import { Card } from '@/components/ui/Card';
import { EmptyState } from '@/components/ui/EmptyState';
import { SkeletonBlock } from '@/components/ui/Skeleton';
import { Button } from '@/components/ui/Button';
import { Badge } from '@/components/ui/Badge';

export default function InsightsPage() {
  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ['insights'],
    queryFn: () => adminClient.getInsights(),
    refetchInterval: 6000,
  });

  const { data: providers = [] } = useQuery({
    queryKey: ['providers'],
    queryFn: () => adminClient.getProviders(),
  });

  const totals = (data?.totals || {}) as Record<string, number>;
  const byChannel = (data?.by_channel || {}) as Record<
    string,
    number | { total?: number; delivered?: number; failed?: number }
  >;
  const byApp = ((data as any)?.by_app || {}) as Record<
    string,
    { total: number; delivered: number; failed: number; avg_ms: number }
  >;
  const byProvider = ((data as any)?.by_provider || {}) as Record<
    string,
    {
      name?: string;
      deleted?: boolean;
      total: number;
      delivered: number;
      failed: number;
      avg_ms: number;
    }
  >;

  const channelRows = Object.entries(byChannel).map(([ch, value]) => {
    const total = typeof value === 'number' ? value : Number(value?.total ?? 0);
    const delivered = typeof value === 'number' ? value : Number(value?.delivered ?? 0);
    const failed = typeof value === 'number' ? 0 : Number(value?.failed ?? 0);
    return { ch, total, delivered, failed };
  });

  const appRows = Object.entries(byApp);
  const providerRows = Object.entries(byProvider);

  const totalCount = totals.total ?? 0;
  const deliveredCount = totals.delivered ?? 0;
  const failedCount = totals.failed ?? 0;
  const successRate =
    totalCount > 0 ? Math.round((deliveredCount / Math.max(1, deliveredCount + failedCount)) * 100) : null;

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-2xl font-bold tracking-tight m-0 mb-1">Telemetry & Routing Insights</h1>
        <p className="text-muted m-0 text-sm">
          Application-wise volume, channel delivery rates, and provider latency across your gateway.
        </p>
      </div>

      {isLoading ? (
        <Card>
          <SkeletonBlock rows={4} />
        </Card>
      ) : isError ? (
        <Card>
          <EmptyState
            title="Could not load insights"
            description="Sign in again, or check that the gateway is running."
            action={<Button onClick={() => refetch()}>Retry</Button>}
          />
        </Card>
      ) : (
        <>
          <div className="grid gap-3.5 mb-4" style={{ gridTemplateColumns: 'repeat(auto-fit,minmax(190px,1fr))' }}>
            <div className="zy-stat-3d p-[18px]" title={String(totalCount)}>
              <span className="text-muted text-[13px]">Total Dispatched</span>
              <b className="block text-[26px] tracking-tight mt-0.5 font-mono">
                {formatCount(totalCount)}
              </b>
            </div>
            <div className="zy-stat-3d p-[18px]" title={String(deliveredCount)}>
              <span className="text-muted text-[13px]">Delivered</span>
              <b className="block text-[26px] tracking-tight mt-0.5 text-ok font-mono">
                {formatCount(deliveredCount)}
              </b>
            </div>
            <div className="zy-stat-3d p-[18px]" title={String(failedCount)}>
              <span className="text-muted text-[13px]">Failed</span>
              <b className="block text-[26px] tracking-tight mt-0.5 text-danger font-mono">
                {formatCount(failedCount)}
              </b>
            </div>
            <div className="zy-stat-3d p-[18px]">
              <span className="text-muted text-[13px]">Delivery Success Rate</span>
              <b className="block text-[26px] tracking-tight mt-0.5 text-accent font-mono">
                {successRate !== null ? `${successRate}%` : '—'}
              </b>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
            <Card className="mb-0">
              <h2 className="text-base font-semibold m-0 mb-3">By Application</h2>
              {!appRows.length ? (
                <EmptyState title="No application traffic yet" description="Dispatch a message to see per-app telemetry." />
              ) : (
                <div className="space-y-2.5">
                  {appRows.map(([appName, stat]) => (
                    <div
                      key={appName}
                      className="flex items-center justify-between gap-2 p-3 rounded-[var(--r)] bg-bg border border-line flex-wrap"
                    >
                      <div className="min-w-0">
                        <b className="text-sm text-text block truncate">{appName}</b>
                        <span className="text-xs text-muted font-mono">
                          Avg latency: {stat.avg_ms} ms
                        </span>
                      </div>
                      <div className="flex items-center gap-2 font-mono text-xs flex-wrap">
                        <span title={`${stat.delivered} delivered`}>
                          <Badge tone="ok">{formatCount(stat.delivered)} ok</Badge>
                        </span>
                        {stat.failed > 0 && (
                          <span title={`${stat.failed} failed`}>
                            <Badge tone="danger">{formatCount(stat.failed)} failed</Badge>
                          </span>
                        )}
                        <span title={`${stat.total} total`}>
                          <Badge tone="muted">{formatCount(stat.total)} total</Badge>
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </Card>

            <Card className="mb-0">
              <h2 className="text-base font-semibold m-0 mb-3">By Channel</h2>
              {!channelRows.length ? (
                <EmptyState title="No channel data yet" description="Send messages to see the channel distribution." />
              ) : (
                <div className="space-y-2.5">
                  {channelRows.map((row) => (
                    <div
                      key={row.ch}
                      className="flex items-center justify-between gap-2 p-3 rounded-[var(--r)] bg-bg border border-line flex-wrap"
                    >
                      <span className="capitalize font-semibold text-sm">{row.ch}</span>
                      <div className="flex items-center gap-2 font-mono text-xs flex-wrap">
                        <span title={`${row.delivered} delivered`}>
                          <Badge tone="ok">{formatCount(row.delivered)} delivered</Badge>
                        </span>
                        {row.failed > 0 && (
                          <span title={`${row.failed} failed`}>
                            <Badge tone="danger">{formatCount(row.failed)} failed</Badge>
                          </span>
                        )}
                        <b title={`${row.total} total`}>{formatCount(row.total)} total</b>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </Card>
          </div>

          <Card className="mb-0">
            <h2 className="text-base font-semibold m-0 mb-3">Provider Route Performance</h2>
            {!providerRows.length ? (
              <EmptyState title="No provider dispatches yet" description="Provider latency and reliability appear here." />
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                {providerRows.map(([provId, stat]) => {
                  const matchedProv = providers.find((p) => p.id === provId);
                  const isDeleted = Boolean(stat.deleted) || (!matchedProv && provId !== 'unassigned');
                  const displayName = stat.name || matchedProv?.name || provId;
                  return (
                    <div
                      key={provId}
                      className={`p-3.5 rounded-[var(--r)] bg-bg border flex flex-col justify-between gap-2.5 ${
                        isDeleted ? 'border-dashed border-muted opacity-90' : 'border-line'
                      }`}
                    >
                      <div className="flex items-start justify-between gap-2">
                        <div className="min-w-0">
                          <div className="flex items-center gap-1.5 flex-wrap min-w-0">
                            <b className="text-sm text-text truncate">{displayName}</b>
                            {isDeleted ? <Badge tone="muted">Deleted</Badge> : null}
                          </div>
                          <span className="font-mono text-[11px] text-muted block truncate">
                            {provId}
                          </span>
                        </div>
                        <Badge tone={stat.failed === 0 ? 'ok' : 'warn'}>
                          {stat.avg_ms} ms avg
                        </Badge>
                      </div>
                      <div className="flex items-center justify-between text-xs text-muted font-mono flex-wrap gap-1.5">
                        <span title={`${stat.delivered} delivered`}>
                          Delivered: <b className="text-ok">{formatCount(stat.delivered)}</b>
                        </span>
                        <span title={`${stat.failed} failed`}>
                          Failed: <b className={stat.failed > 0 ? 'text-danger' : 'text-text'}>{formatCount(stat.failed)}</b>
                        </span>
                        <span title={`${stat.total} total`}>
                          Total: <b className="text-text">{formatCount(stat.total)}</b>
                        </span>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </Card>
        </>
      )}
    </div>
  );
}
