'use client';

import { useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { apiClient } from '@/infrastructure/api/api-client';
import { queryKeys } from '@/infrastructure/api/query-keys';
import { formatDistanceToNow } from 'date-fns';
import { Server, AlertTriangle, ListTodo, Clock } from 'lucide-react';

/* ---------- tiny type helpers (backend shapes) ---------- */

interface ServerItem {
  id: string;
  name: string;
  status: string;
}

interface AlertEvent {
  id: string;
  severity: 'critical' | 'warning' | 'info';
  message: string;
  serverId?: string;
  firedAt: string;
}

interface TaskItem {
  id: string;
  title: string;
  status: string;
  createdAt: string;
}

interface StandingOrderItem {
  id: string;
  name: string;
}

/** Normalise backend responses: backends may return a raw array or { items/data, total }. */
function normalise<T>(raw: unknown): { items: T[]; total: number } {
  if (Array.isArray(raw)) return { items: raw, total: raw.length };
  const obj = raw as Record<string, unknown>;
  const items = (obj.items ?? obj.data ?? []) as T[];
  const total = (obj.total as number) ?? items.length;
  return { items, total };
}

/* ---------- severity badge ---------- */

function SeverityBadge({ severity }: { severity: string }) {
  const colors: Record<string, string> = {
    critical: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
    warning: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400',
    info: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
  };
  return (
    <span
      className={`inline-block px-2 py-0.5 rounded text-xs font-medium ${
        colors[severity] ?? 'bg-muted text-muted-foreground'
      }`}
    >
      {severity}
    </span>
  );
}

/* ---------- status badge ---------- */

function StatusBadge({ status }: { status: string }) {
  const colors: Record<string, string> = {
    running: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
    completed: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
    failed: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
    pending: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400',
  };
  return (
    <span
      className={`inline-block px-2 py-0.5 rounded text-xs font-medium ${
        colors[status] ?? 'bg-muted text-muted-foreground'
      }`}
    >
      {status}
    </span>
  );
}

/* ---------- stat card ---------- */

interface StatCardProps {
  label: string;
  count: number | undefined;
  icon: React.ReactNode;
  loading: boolean;
}

function StatCard({ label, count, icon, loading }: StatCardProps) {
  return (
    <div className="p-4 bg-card rounded-lg border flex items-center gap-4">
      <div className="p-3 rounded-md bg-primary/10 text-primary">{icon}</div>
      <div>
        <p className="text-sm text-muted-foreground">{label}</p>
        <p className="text-3xl font-bold mt-1">
          {loading ? (
            <span className="inline-block w-8 h-8 rounded bg-muted animate-pulse" />
          ) : (
            (count ?? 0)
          )}
        </p>
      </div>
    </div>
  );
}

/* ---------- page ---------- */

export default function DashboardPage() {
  const { t } = useTranslation('dashboard');
  const { t: tc } = useTranslation('common');

  const {
    data: serversRaw,
    isLoading: serversLoading,
  } = useQuery({
    queryKey: queryKeys.servers.list(),
    queryFn: () => apiClient<unknown>('/api/v1/inventory/servers'),
  });

  const {
    data: alertsRaw,
    isLoading: alertsLoading,
  } = useQuery({
    queryKey: queryKeys.alerts.events(),
    queryFn: () => apiClient<unknown>('/api/v1/monitor/alerts/events'),
  });

  const {
    data: tasksRaw,
    isLoading: tasksLoading,
  } = useQuery({
    queryKey: queryKeys.tasks.list(),
    queryFn: () => apiClient<unknown>('/api/v1/ops/tasks'),
  });

  const {
    data: ordersRaw,
    isLoading: ordersLoading,
  } = useQuery({
    queryKey: queryKeys.standingOrders.list(),
    queryFn: () => apiClient<unknown>('/api/v1/ops/standing-orders'),
  });

  const serversData = serversRaw ? normalise<ServerItem>(serversRaw) : undefined;
  const alertsData = alertsRaw ? normalise<AlertEvent>(alertsRaw) : undefined;
  const tasksData = tasksRaw ? normalise<TaskItem>(tasksRaw) : undefined;
  const standingOrdersData = ordersRaw ? normalise<StandingOrderItem>(ordersRaw) : undefined;

  const recentAlerts = (alertsData?.items ?? []).slice(0, 5);
  const recentTasks = (tasksData?.items ?? []).slice(0, 5);

  return (
    <div>
      <h1 className="text-2xl font-bold mb-6">{t('title')}</h1>

      {/* ---- stat cards ---- */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        <StatCard
          label={t('stats.totalServers')}
          count={serversData?.total}
          icon={<Server className="h-5 w-5" />}
          loading={serversLoading}
        />
        <StatCard
          label={t('stats.activeAlerts')}
          count={alertsData?.total}
          icon={<AlertTriangle className="h-5 w-5" />}
          loading={alertsLoading}
        />
        <StatCard
          label={t('stats.runningTasks')}
          count={tasksData?.total}
          icon={<ListTodo className="h-5 w-5" />}
          loading={tasksLoading}
        />
        <StatCard
          label={t('stats.standingOrders')}
          count={standingOrdersData?.total}
          icon={<Clock className="h-5 w-5" />}
          loading={ordersLoading}
        />
      </div>

      {/* ---- recent alerts ---- */}
      <div className="bg-card rounded-lg border p-4 mb-6">
        <h2 className="text-lg font-semibold mb-3">{t('recentAlerts.title')}</h2>
        {alertsLoading ? (
          <p className="text-sm text-muted-foreground">{tc('loading')}</p>
        ) : recentAlerts.length === 0 ? (
          <p className="text-sm text-muted-foreground">{t('recentAlerts.empty')}</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b text-left text-muted-foreground">
                  <th className="pb-2 pr-4 font-medium">{t('recentAlerts.severity')}</th>
                  <th className="pb-2 pr-4 font-medium">{t('recentAlerts.message')}</th>
                  <th className="pb-2 pr-4 font-medium">{t('recentAlerts.server')}</th>
                  <th className="pb-2 font-medium">{t('recentAlerts.time')}</th>
                </tr>
              </thead>
              <tbody>
                {recentAlerts.map((alert) => (
                  <tr key={alert.id} className="border-b last:border-b-0">
                    <td className="py-2 pr-4">
                      <SeverityBadge severity={alert.severity} />
                    </td>
                    <td className="py-2 pr-4 max-w-xs truncate">{alert.message}</td>
                    <td className="py-2 pr-4 text-muted-foreground">
                      {alert.serverId ?? '--'}
                    </td>
                    <td className="py-2 text-muted-foreground whitespace-nowrap">
                      {formatDistanceToNow(new Date(alert.firedAt), { addSuffix: true })}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* ---- recent tasks ---- */}
      <div className="bg-card rounded-lg border p-4">
        <h2 className="text-lg font-semibold mb-3">{t('recentTasks.title')}</h2>
        {tasksLoading ? (
          <p className="text-sm text-muted-foreground">{tc('loading')}</p>
        ) : recentTasks.length === 0 ? (
          <p className="text-sm text-muted-foreground">{t('recentTasks.empty')}</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b text-left text-muted-foreground">
                  <th className="pb-2 pr-4 font-medium">{t('recentTasks.name')}</th>
                  <th className="pb-2 pr-4 font-medium">{t('recentTasks.status')}</th>
                  <th className="pb-2 font-medium">{t('recentTasks.created')}</th>
                </tr>
              </thead>
              <tbody>
                {recentTasks.map((task) => (
                  <tr key={task.id} className="border-b last:border-b-0">
                    <td className="py-2 pr-4">{task.title}</td>
                    <td className="py-2 pr-4">
                      <StatusBadge status={task.status} />
                    </td>
                    <td className="py-2 text-muted-foreground whitespace-nowrap">
                      {formatDistanceToNow(new Date(task.createdAt), { addSuffix: true })}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
