"use client";

import { useState, useEffect, useMemo, useCallback } from "react";
import { useSettings } from "@/app/lib/settings";
import {
  listClientStatistics,
  getClientStatistics,
  refreshClientStatistics,
  type ClientStatistics,
  type ClientTableStatistics,
  ApiError,
} from "@/app/lib/api";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { ScrollArea } from "./ui/scroll-area";
import { toast } from "sonner";
import {
  BarChart3,
  RefreshCw,
  Loader2,
  AlertCircle,
  Server,
  Clock,
  ArrowLeft,
  Database,
  Activity,
  Hash,
  Shield,
  CheckCircle2,
  XCircle,
  Zap,
} from "lucide-react";
import { cn } from "@/app/lib/utils";

function formatNumber(n: number): string {
  if (n >= 1_000_000) return `${(n / 1_000_000)?.toFixed(1)}M`;
  if (n >= 1_000) return `${(n / 1_000)?.toFixed(1)}K`;
  return n.toLocaleString();
}

function formatDate(d: string | null): string {
  if (!d) return "Never";
  try {
    return new Date(d).toLocaleString(undefined, {
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch {
    return d;
  }
}

function StatCard({
  icon: Icon,
  label,
  value,
  subValue,
  color = "text-primary",
}: {
  icon: React.ComponentType<{ className?: string }>;
  label: string;
  value: string | number;
  subValue?: string;
  color?: string;
}) {
  return (
    <div className="rounded-lg border border-border bg-card p-4">
      <div className="flex items-center gap-2 text-muted-foreground mb-2">
        <Icon className="h-4 w-4" />
        <span className="text-caption uppercase tracking-wider">{label}</span>
      </div>
      <div className={cn("text-xl font-bold tabular-nums", color)}>
        {typeof value === "number" ? formatNumber(value) : value}
      </div>
      {subValue && (
        <span className="text-caption text-muted-foreground mt-0.5 block">
          {subValue}
        </span>
      )}
    </div>
  );
}

function operationBadgeVariant(
  op: string,
): "default" | "success" | "warning" | "destructive" {
  switch (op.toLowerCase()) {
    case "fetch":
    case "select":
      return "default";
    case "insert":
    case "create":
      return "success";
    case "update":
      return "warning";
    case "delete":
      return "destructive";
    default:
      return "default";
  }
}

export default function ClientStatisticsPage() {
  const { apiKey, localBackupApiKey, baseUrl } = useSettings();
  const effectiveApiKey = apiKey || localBackupApiKey;
  const ctx = useMemo(
    () => ({ baseUrl, apiKey, localBackupApiKey }),
    [baseUrl, apiKey, localBackupApiKey],
  );

  const [allStats, setAllStats] = useState<ClientStatistics[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [lastRefresh, setLastRefresh] = useState<Date | null>(null);
  const [refreshing, setRefreshing] = useState(false);

  const [selectedClient, setSelectedClient] = useState<string | null>(null);
  const [clientDetail, setClientDetail] = useState<ClientStatistics | null>(
    null,
  );
  const [tableStats, setTableStats] = useState<ClientTableStatistics[]>([]);
  const [detailLoading, setDetailLoading] = useState(false);

  const loadAll = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const stats = await listClientStatistics(ctx);
      setAllStats(stats);
      setLastRefresh(new Date());
    } catch (err) {
      const msg =
        err instanceof ApiError
          ? err.message
          : "Failed to load client statistics";
      setError(msg);
    } finally {
      setLoading(false);
    }
  }, [ctx]);

  useEffect(() => {
    if (!effectiveApiKey) {
      setLoading(false);
      setError(
        "Provide your Athena P12 key in Settings to view client statistics",
      );
      return;
    }
    loadAll();
  }, [effectiveApiKey, loadAll]);

  const handleRefresh = useCallback(async () => {
    setRefreshing(true);
    try {
      const stats = await refreshClientStatistics(ctx);
      setAllStats(stats);
      setLastRefresh(new Date());
      toast.success("Statistics refreshed from logs");
    } catch (err) {
      const msg =
        err instanceof ApiError ? err.message : "Failed to refresh statistics";
      toast.error("Refresh failed", { description: msg });
    } finally {
      setRefreshing(false);
    }
  }, [ctx]);

  const handleSelectClient = useCallback(
    async (clientName: string) => {
      setSelectedClient(clientName);
      setDetailLoading(true);
      try {
        const result = await getClientStatistics(ctx, clientName);
        setClientDetail(result.statistics);
        setTableStats(result.tables);
      } catch (err) {
        const msg =
          err instanceof ApiError
            ? err.message
            : "Failed to load client details";
        toast.error("Load failed", { description: msg });
        setClientDetail(null);
        setTableStats([]);
      } finally {
        setDetailLoading(false);
      }
    },
    [ctx],
  );

  const handleBack = useCallback(() => {
    setSelectedClient(null);
    setClientDetail(null);
    setTableStats([]);
  }, []);

  const totals = useMemo(() => {
    return allStats.reduce(
      (acc, s) => ({
        requests: acc.requests + s.total_requests,
        operations: acc.operations + s.total_operations,
        cached: acc.cached + s.total_cached_requests,
        successful: acc.successful + s.successful_requests,
        failed: acc.failed + s.failed_requests,
      }),
      { requests: 0, operations: 0, cached: 0, successful: 0, failed: 0 },
    );
  }, [allStats]);

  if (!effectiveApiKey) {
    return (
      <div className="flex flex-1 flex-col items-center justify-center gap-4">
        <Shield className="h-12 w-12 text-muted-foreground-dim" />
        <div className="text-center">
          <h3 className="text-sm font-semibold text-foreground mb-1">
            Authentication Required
          </h3>
          <p className="text-xs text-muted-foreground max-w-sm">
            Set your Athena P12 API key in Settings to access client statistics.
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-1 flex-col min-h-0">
      {/* Header */}
      <div className="flex items-center gap-3 border-b border-border px-6 py-3">
        {selectedClient && (
          <Button
            variant="ghost"
            size="sm"
            onClick={handleBack}
            className="h-7 w-7 p-0"
          >
            <ArrowLeft className="h-3.5 w-3.5" />
          </Button>
        )}
        <BarChart3 className="h-4 w-4 text-primary" />
        <h2 className="text-sm font-semibold text-foreground">
          {selectedClient
            ? `${selectedClient} Statistics`
            : "Client Statistics"}
        </h2>
        {!selectedClient && (
          <Badge variant="secondary" className="text-caption">
            {allStats.length} client{allStats.length !== 1 ? "s" : ""}
          </Badge>
        )}
        <div className="flex-1" />
        {lastRefresh && (
          <span className="text-caption text-muted-foreground">
            Updated: {lastRefresh.toLocaleTimeString()}
          </span>
        )}
        {!selectedClient && (
          <>
            <Button
              variant="outline"
              size="sm"
              onClick={handleRefresh}
              disabled={refreshing || loading}
              title="Rebuild statistics from gateway logs"
            >
              {refreshing ? (
                <Loader2 className="h-3 w-3 animate-spin" />
              ) : (
                <Zap className="h-3 w-3" />
              )}
              Rebuild
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={loadAll}
              disabled={loading}
            >
              {loading ? (
                <Loader2 className="h-3 w-3 animate-spin" />
              ) : (
                <RefreshCw className="h-3 w-3" />
              )}
              Refresh
            </Button>
          </>
        )}
      </div>

      {/* Error */}
      {error && !loading && (
        <div className="flex items-center gap-2 border-b border-destructive-border bg-destructive-subtle px-6 py-3 text-xs text-destructive">
          <AlertCircle className="h-3.5 w-3.5" />
          {error}
          <Button
            variant="outline"
            size="sm"
            onClick={loadAll}
            className="ml-auto h-6 text-caption"
          >
            Retry
          </Button>
        </div>
      )}

      {/* Loading */}
      {loading && allStats.length === 0 && (
        <div className="flex flex-1 items-center justify-center">
          <div className="flex flex-col items-center gap-3">
            <Loader2 className="h-8 w-8 animate-spin text-primary" />
            <p className="text-xs text-muted-foreground">
              Loading client statistics…
            </p>
          </div>
        </div>
      )}

      {/* Detail view */}
      {selectedClient && (
        <ScrollArea className="flex-1">
          <div className="mx-auto max-w-5xl space-y-6 p-6">
            {detailLoading ? (
              <div className="flex items-center justify-center py-12">
                <Loader2 className="h-6 w-6 animate-spin text-primary" />
              </div>
            ) : clientDetail ? (
              <>
                {/* Detail summary cards */}
                <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-5">
                  <StatCard
                    icon={Activity}
                    label="Requests"
                    value={clientDetail.total_requests}
                  />
                  <StatCard
                    icon={CheckCircle2}
                    label="Successful"
                    value={clientDetail.successful_requests}
                    color="text-success"
                  />
                  <StatCard
                    icon={XCircle}
                    label="Failed"
                    value={clientDetail.failed_requests}
                    color="text-destructive"
                  />
                  <StatCard
                    icon={Database}
                    label="Cached"
                    value={clientDetail.total_cached_requests}
                    color="text-warning"
                  />
                  <StatCard
                    icon={Hash}
                    label="Operations"
                    value={clientDetail.total_operations}
                  />
                </div>

                {/* Last activity */}
                <div className="flex items-center gap-4 rounded-lg border border-border bg-card px-5 py-3">
                  <Clock className="h-4 w-4 text-muted-foreground" />
                  <span className="text-xs text-muted-foreground">
                    Last request
                  </span>
                  <span className="text-xs font-medium">
                    {formatDate(clientDetail.last_request_at)}
                  </span>
                  <span className="text-border">|</span>
                  <span className="text-xs text-muted-foreground">
                    Last operation
                  </span>
                  <span className="text-xs font-medium">
                    {formatDate(clientDetail.last_operation_at)}
                  </span>
                  <span className="text-border">|</span>
                  <span className="text-xs text-muted-foreground">Updated</span>
                  <span className="text-xs font-medium">
                    {formatDate(clientDetail.updated_at)}
                  </span>
                </div>

                {/* Table statistics */}
                <section>
                  <div className="flex items-center gap-2 mb-3">
                    <h3 className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
                      Table Operations
                    </h3>
                    <Badge variant="secondary" className="text-caption">
                      {tableStats.length}
                    </Badge>
                  </div>

                  {tableStats.length === 0 ? (
                    <div className="rounded-lg border border-border bg-card px-6 py-8 text-center">
                      <Database className="mx-auto h-8 w-8 text-muted-foreground-dim mb-2" />
                      <p className="text-xs text-muted-foreground">
                        No per-table statistics recorded yet.
                      </p>
                    </div>
                  ) : (
                    <div className="rounded-lg border border-border overflow-hidden">
                      <table className="w-full text-sm">
                        <thead>
                          <tr className="border-b border-border bg-muted/30">
                            <th className="px-4 py-2.5 text-left text-body-sm font-medium text-muted-foreground">
                              Table
                            </th>
                            <th className="px-4 py-2.5 text-left text-body-sm font-medium text-muted-foreground">
                              Operation
                            </th>
                            <th className="px-4 py-2.5 text-right text-body-sm font-medium text-muted-foreground">
                              Total
                            </th>
                            <th className="px-4 py-2.5 text-right text-body-sm font-medium text-muted-foreground">
                              Errors
                            </th>
                            <th className="px-4 py-2.5 text-right text-body-sm font-medium text-muted-foreground">
                              Error Rate
                            </th>
                            <th className="px-4 py-2.5 text-right text-body-sm font-medium text-muted-foreground">
                              Last Operation
                            </th>
                          </tr>
                        </thead>
                        <tbody className="divide-y divide-border-muted">
                          {tableStats.map((row, i) => {
                            const errorRate =
                              row.total_operations > 0
                                ? (
                                    (row.error_operations /
                                      row.total_operations) *
                                    100
                                  )?.toFixed(1)
                                : "0.0";
                            return (
                              <tr
                                key={`${row.table_name}-${row.operation}-${row.updated_at ?? `idx-${i}`}`}
                                className="hover:bg-accent-muted transition-colors"
                              >
                                <td className="px-4 py-3">
                                  <span className="text-xs font-mono text-foreground">
                                    {row?.table_name}
                                  </span>
                                </td>
                                <td className="px-4 py-3">
                                  <Badge
                                    variant={operationBadgeVariant(
                                      row?.operation,
                                    )}
                                    className="text-caption"
                                  >
                                    {row?.operation}
                                  </Badge>
                                </td>
                                <td className="px-4 py-3 text-right">
                                  <span className="text-xs font-mono tabular-nums">
                                    {formatNumber(row?.total_operations)}
                                  </span>
                                </td>
                                <td className="px-4 py-3 text-right">
                                  <span
                                    className={cn(
                                      "text-xs font-mono tabular-nums",
                                      row?.error_operations > 0
                                        ? "text-destructive"
                                        : "text-muted-foreground",
                                    )}
                                  >
                                    {formatNumber(row?.error_operations)}
                                  </span>
                                </td>
                                <td className="px-4 py-3 text-right">
                                  <span
                                    className={cn(
                                      "text-xs font-mono tabular-nums",
                                      parseFloat(errorRate) > 5
                                        ? "text-destructive"
                                        : parseFloat(errorRate) > 0
                                          ? "text-warning"
                                          : "text-muted-foreground",
                                    )}
                                  >
                                    {errorRate}%
                                  </span>
                                </td>
                                <td className="px-4 py-3 text-right">
                                  <span className="text-xs text-muted-foreground">
                                    {formatDate(row?.last_operation_at)}
                                  </span>
                                </td>
                              </tr>
                            );
                          })}
                        </tbody>
                      </table>
                    </div>
                  )}
                </section>
              </>
            ) : (
              <div className="rounded-lg border border-border bg-card px-6 py-8 text-center">
                <AlertCircle className="mx-auto h-8 w-8 text-muted-foreground-dim mb-2" />
                <p className="text-xs text-muted-foreground">
                  No statistics available for this client.
                </p>
              </div>
            )}
          </div>
        </ScrollArea>
      )}

      {/* List view */}
      {!selectedClient && !loading && allStats.length > 0 && (
        <ScrollArea className="flex-1">
          <div className="mx-auto max-w-5xl space-y-6 p-6">
            {/* Aggregate cards */}
            <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-5">
              <StatCard
                icon={Server}
                label="Clients"
                value={allStats?.length}
              />
              <StatCard
                icon={Activity}
                label="Total Requests"
                value={totals?.requests}
              />
              <StatCard
                icon={Hash}
                label="Total Operations"
                value={totals?.operations}
              />
              <StatCard
                icon={Database}
                label="Cached Requests"
                value={totals?.cached}
                color="text-warning"
              />
              <StatCard
                icon={XCircle}
                label="Failed Requests"
                value={totals?.failed}
                color={
                  totals?.failed > 0
                    ? "text-destructive"
                    : "text-muted-foreground"
                }
              />
            </div>

            {/* Client table */}
            <section>
              <h3 className="mb-3 text-xs font-medium uppercase tracking-wider text-muted-foreground">
                Per-Client Statistics
              </h3>
              <div className="rounded-lg border border-border overflow-hidden">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b border-border bg-muted/30">
                      <th className="px-4 py-2.5 text-left text-body-sm font-medium text-muted-foreground">
                        Client
                      </th>
                      <th className="px-4 py-2.5 text-right text-body-sm font-medium text-muted-foreground">
                        Requests
                      </th>
                      <th className="px-4 py-2.5 text-right text-body-sm font-medium text-muted-foreground">
                        Successful
                      </th>
                      <th className="px-4 py-2.5 text-right text-body-sm font-medium text-muted-foreground">
                        Failed
                      </th>
                      <th className="px-4 py-2.5 text-right text-body-sm font-medium text-muted-foreground">
                        Cached
                      </th>
                      <th className="px-4 py-2.5 text-right text-body-sm font-medium text-muted-foreground">
                        Operations
                      </th>
                      <th className="px-4 py-2.5 text-right text-body-sm font-medium text-muted-foreground">
                        Last Activity
                      </th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border-muted">
                    {allStats.map((stat) => (
                      <tr
                        key={stat?.client_name}
                        onClick={() => handleSelectClient(stat?.client_name)}
                        className="hover:bg-accent-muted transition-colors cursor-pointer"
                      >
                        <td className="px-4 py-3">
                          <div className="flex items-center gap-2">
                            <Server className="h-3.5 w-3.5 text-muted-foreground" />
                            <span className="text-xs font-medium text-foreground">
                              {stat?.client_name}
                            </span>
                          </div>
                        </td>
                        <td className="px-4 py-3 text-right">
                          <span className="text-xs font-mono tabular-nums">
                            {formatNumber(stat?.total_requests)}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-right">
                          <span className="text-xs font-mono tabular-nums text-success">
                            {formatNumber(stat?.successful_requests)}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-right">
                          <span
                            className={cn(
                              "text-xs font-mono tabular-nums",
                              stat?.failed_requests > 0
                                ? "text-destructive"
                                : "text-muted-foreground",
                            )}
                          >
                            {formatNumber(stat?.failed_requests)}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-right">
                          <span className="text-xs font-mono tabular-nums text-warning">
                            {formatNumber(stat?.total_cached_requests)}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-right">
                          <span className="text-xs font-mono tabular-nums">
                            {formatNumber(stat?.total_operations)}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-right">
                          <span className="text-xs text-muted-foreground">
                            {formatDate(
                              stat?.last_request_at ?? stat?.last_operation_at,
                            )}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </section>
          </div>
        </ScrollArea>
      )}

      {/* Empty state */}
      {!selectedClient && !loading && !error && allStats?.length === 0 && (
        <div className="flex flex-1 items-center justify-center">
          <div className="text-center">
            <BarChart3 className="mx-auto h-10 w-10 text-muted-foreground-dim mb-3" />
            <h3 className="text-sm font-semibold text-foreground mb-1">
              No Statistics Yet
            </h3>
            <p className="text-xs text-muted-foreground max-w-sm mb-4">
              Client statistics are collected from gateway request logs. Try
              rebuilding from logs.
            </p>
            <Button
              variant="outline"
              size="sm"
              onClick={handleRefresh}
              disabled={refreshing}
            >
              {refreshing ? (
                <Loader2 className="h-3 w-3 animate-spin" />
              ) : (
                <Zap className="h-3 w-3" />
              )}
              Rebuild from Logs
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
