'use client';

import { useCallback, useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { fetchWithAuth } from '@/lib/auth';
import { ADMIN_NAV_QUICK_LINKS, type AdminNavItem } from '@/lib/admin-nav';

const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? '';

function adminUrl(path: string): string {
  const p = path.startsWith('/') ? path : `/${path}`;
  if (!API_BASE) return p;
  return `${API_BASE.replace(/\/$/, '')}${p}`;
}

interface KpiState {
  toolCalls: number | null;
  incidentDossiers: number | null;
  evaluationsCount: number | null;
  loading: boolean;
  error: string | null;
}

export default function AdminDashboardPage() {
  const router = useRouter();
  const [kpi, setKpi] = useState<KpiState>({
    toolCalls: null,
    incidentDossiers: null,
    evaluationsCount: null,
    loading: true,
    error: null,
  });

  const loadKpis = useCallback(async () => {
    setKpi((k) => ({ ...k, loading: true, error: null }));
    try {
      const [statsRes, incRes, evalRes ] = await Promise.all([
        fetchWithAuth(adminUrl('/api/stats/summary')),
        fetchWithAuth(
          adminUrl('/api/admin/incidents?limit=1&offset=0&active_only=true')
        ),
        fetchWithAuth(adminUrl('/api/admin/evaluations/summary')),
      ]);

      let toolCalls: number | null = null;
      if (statsRes.ok) {
        const j = await statsRes.json();
        toolCalls = typeof j.total_calls === 'number' ? j.total_calls : null;
      }

      let incidentDossiers: number | null = null;
      if (incRes.ok) {
        const j = await incRes.json();
        incidentDossiers = typeof j.total === 'number' ? j.total : null;
      }

      let evaluationsCount: number | null = null;
      if (evalRes.ok) {
        const j = await evalRes.json();
        evaluationsCount =
          typeof j.total_evaluated === 'number' ? j.total_evaluated : null;
      }

      setKpi({
        toolCalls,
        incidentDossiers,
        evaluationsCount,
        loading: false,
        error: null,
      });
    } catch {
      setKpi((k) => ({
        ...k,
        loading: false,
        error: 'Some metrics could not be loaded. Links below still work.',
      }));
    }
  }, []);

  useEffect(() => {
    loadKpis();
  }, [loadKpis]);

  const kpiCard = (
    title: string,
    value: string,
    hint: string,
    href: string,
    accent: string
  ) => (
    <Link
      href={href}
      style={{ textDecoration: 'none', color: 'inherit' }}
    >
      <div
        style={{
          padding: '1.25rem',
          borderRadius: '12px',
          background: '#fff',
          border: '1px solid #ececf4',
          boxShadow: '0 2px 8px rgba(92,95,188,0.06)',
          height: '100%',
          transition: 'box-shadow 0.15s',
        }}
        onMouseEnter={(e) => {
          e.currentTarget.style.boxShadow = '0 4px 14px rgba(92,95,188,0.12)';
        }}
        onMouseLeave={(e) => {
          e.currentTarget.style.boxShadow = '0 2px 8px rgba(92,95,188,0.06)';
        }}
      >
        <div style={{ fontSize: 12, fontWeight: 600, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
          {title}
        </div>
        <div style={{ fontSize: 28, fontWeight: 700, color: accent, marginTop: 6 }}>
          {value}
        </div>
        <div style={{ fontSize: 13, color: '#6b7280', marginTop: 8 }}>{hint}</div>
      </div>
    </Link>
  );

  const sectionCard = (item: AdminNavItem) => (
    <button
      key={item.href}
      type="button"
      onClick={() => router.push(item.href)}
      style={{
        display: 'flex',
        alignItems: 'flex-start',
        gap: 12,
        padding: '14px 16px',
        borderRadius: 12,
        border: '1px solid #ececf4',
        background: '#fff',
        cursor: 'pointer',
        textAlign: 'left',
        width: '100%',
        boxShadow: '0 2px 8px rgba(92,95,188,0.05)',
        transition: 'border-color 0.15s, box-shadow 0.15s',
      }}
      onMouseEnter={(e) => {
        e.currentTarget.style.borderColor = 'rgba(92,95,188,0.35)';
        e.currentTarget.style.boxShadow = '0 4px 12px rgba(92,95,188,0.1)';
      }}
      onMouseLeave={(e) => {
        e.currentTarget.style.borderColor = '#ececf4';
        e.currentTarget.style.boxShadow = '0 2px 8px rgba(92,95,188,0.05)';
      }}
    >
      <span style={{ fontSize: 22, lineHeight: 1.2 }}>{item.icon}</span>
      <div>
        <div style={{ fontSize: 15, fontWeight: 600, color: '#1a1a2e' }}>{item.label}</div>
        <div style={{ fontSize: 13, color: '#6b7280', marginTop: 4, lineHeight: 1.45 }}>
          {item.description}
        </div>
      </div>
    </button>
  );

  return (
    <div style={{ paddingTop: 8 }}>
      <div style={{ marginBottom: 28 }}>
        <h1 style={{ margin: 0, fontSize: 22, fontWeight: 700, color: '#1a1a2e' }}>
          Overview
        </h1>
        <p style={{ margin: '6px 0 0', fontSize: 14, color: '#6b7280' }}>
          High-level metrics and shortcuts to every admin area. Use the sidebar for quick navigation.
        </p>
      </div>

      {kpi.error && (
        <div
          style={{
            padding: 12,
            borderRadius: 8,
            background: '#fffbeb',
            border: '1px solid #fde68a',
            color: '#92400e',
            fontSize: 13,
            marginBottom: 16,
          }}
        >
          {kpi.error}
        </div>
      )}

      <div
        style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))',
          gap: '1rem',
          marginBottom: '2rem',
        }}
      >
        {kpiCard(
          'Tool calls',
          kpi.loading ? '…' : kpi.toolCalls != null ? kpi.toolCalls.toLocaleString() : '—',
          'Skill and built-in tool invocations',
          '/admin/stats',
          '#5c5fbc'
        )}
        {kpiCard(
          'Active incidents',
          kpi.loading ? '…' : kpi.incidentDossiers != null ? String(kpi.incidentDossiers) : '—',
          'Non-merged incidents (trends & drill-down)',
          '/admin/incidents',
          '#7c3aed'
        )}
        {kpiCard(
          'Workspaces evaluated',
          kpi.loading ? '…' : kpi.evaluationsCount != null ? String(kpi.evaluationsCount) : '—',
          'Diagnostic evaluation records',
          '/admin/evaluations',
          '#047857'
        )}
      </div>

      <h2
        style={{
          fontSize: 13,
          fontWeight: 700,
          color: '#9ca3af',
          letterSpacing: '0.06em',
          textTransform: 'uppercase',
          margin: '0 0 12px',
        }}
      >
        All sections
      </h2>
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
          gap: 12,
        }}
      >
        {ADMIN_NAV_QUICK_LINKS.map(sectionCard)}
      </div>
    </div>
  );
}
