import React, { useEffect, useMemo, useState } from "react";

import {
  Alert,
  Box,
  Button,
  Chip,
  Paper,
  Stack,
  Typography,
} from "@mui/material";

import { api } from "../api";

type SummarizerMetrics = {
  healthy: boolean;
  model?: string | null;
  device?: string | null;
  gpuAvailable?: boolean;
  gpuName?: string | null;
  healthLatencyMs?: number | null;
  probeLatencyMs?: number | null;
  lastProbeAt?: string | null;
  lastProbeSuccessAt?: string | null;
  lastProbeFailureAt?: string | null;
  probeFailures: number;
  requests: number;
  cacheHits: number;
  cacheMisses: number;
  failures: number;
  averageLatencyMs?: number | null;
  lastSuccessAt?: string | null;
  lastFailureAt?: string | null;
  lastError?: string | null;
};

type SystemStatus = {
  environment: string;
  contentRoot: string;
  version: string;
  commitSha?: string | null;
  buildStamp?: string | null;
  storage: {
    dataRoot: string;
    dbPath: string;
    dbExists: boolean;
    dbSizeBytes?: number | null;
    companyCount: number;
    jobCount: number;
    deletedCount: number;
  };
  email: {
    enabled: boolean;
    host?: string | null;
    port: number;
    enableSsl: boolean;
    from?: string | null;
    fromName?: string | null;
  };
  database: {
    provider: string;
    looksConfigured: boolean;
    canConnect: boolean;
    target?: string | null;
    usesFileStorage: boolean;
    warning?: string | null;
  };
  runtime: {
    framework: string;
    osDescription: string;
    processArchitecture: string;
    machineName?: string | null;
  };
  auth: {
    required: boolean;
    hasJwtKey: boolean;
    googleConfigured: boolean;
    gmailConfigured: boolean;
  };
  summarizer: SummarizerMetrics;
};

function formatBytes(bytes?: number | null) {
  if (bytes == null) return "-";
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

function displayMetadata(value?: string | null) {
  return value && value.trim().length > 0 ? value : "-";
}

function formatDate(value?: string | null) {
  return value ? new Date(value).toLocaleString() : "-";
}

function SummaryCard({ title, value, subtitle, tone = "default" }: { title: string; value: string; subtitle?: string; tone?: "default" | "success" | "warning" | "error" }) {
  const color = tone === "success" ? "success.main" : tone === "warning" ? "warning.main" : tone === "error" ? "error.main" : "text.primary";
  return (
    <Paper sx={{ p: 2, borderRadius: 3 }}>
      <Typography variant="overline" sx={{ color: "text.secondary" }}>{title}</Typography>
      <Typography variant="h5" sx={{ fontWeight: 950, color }}>{value}</Typography>
      <Typography variant="body2" sx={{ color: "text.secondary", mt: 1 }}>{subtitle || "-"}</Typography>
    </Paper>
  );
}

function DetailRow({ label, value }: { label: string; value: React.ReactNode }) {
  return <Typography variant="body2"><strong>{label}:</strong> {value}</Typography>;
}

export default function AdminSystemPage() {
  const [status, setStatus] = useState<SystemStatus | null>(null);
  const [loading, setLoading] = useState(false);
  const [runningProbe, setRunningProbe] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const load = async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await api.get<SystemStatus>("/admin/system");
      setStatus(res.data);
    } catch (e: any) {
      setError(e?.response?.data || e?.message || "Failed to load system status.");
      setStatus(null);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    void load();
  }, []);

  const dbTone = useMemo(() => {
    if (!status) return "default" as const;
    if (!status.database.looksConfigured || !status.database.canConnect) return "error" as const;
    if (status.database.warning) return "warning" as const;
    return "success" as const;
  }, [status]);

  const summarizerTone = useMemo(() => {
    if (!status) return "default" as const;
    if (!status.summarizer.healthy) return "error" as const;
    if (status.summarizer.probeFailures > 0 || status.summarizer.failures > 0) return "warning" as const;
    return "success" as const;
  }, [status]);

  return (
    <Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
      <Box sx={{ display: "flex", justifyContent: "space-between", gap: 2, alignItems: "center", flexWrap: "wrap" }}>
        <Box>
          <Typography variant="h5" sx={{ fontWeight: 950 }}>System status</Typography>
          <Typography sx={{ color: "text.secondary" }}>Production diagnostics for runtime, database, auth, email, and summarizer health.</Typography>
        </Box>
        <Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
          <Button
            variant="outlined"
            onClick={async () => {
              setRunningProbe(true);
              setError(null);
              try {
                await api.post("/admin/system/summarizer/probe");
                await load();
              } catch (e: any) {
                setError(e?.response?.data || e?.message || "Failed to run summarizer probe.");
              } finally {
                setRunningProbe(false);
              }
            }}
            disabled={loading || runningProbe}
          >
            {runningProbe ? "Running probe..." : "Run probe now"}
          </Button>
          <Button variant="contained" onClick={() => void load()} disabled={loading}>
            {loading ? "Refreshing..." : "Refresh"}
          </Button>
        </Box>
      </Box>

      {error ? <Alert severity="error">{error}</Alert> : null}
      {status?.database.warning ? <Alert severity={status.database.canConnect ? "warning" : "error"}>{status.database.warning}</Alert> : null}
      {status?.summarizer.lastError ? <Alert severity={status.summarizer.healthy ? "warning" : "error"}>{status.summarizer.lastError}</Alert> : null}

      <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "repeat(4, 1fr)" }, gap: 2 }}>
        <SummaryCard
          title="Environment"
          value={status?.environment ?? "-"}
          subtitle={`Version ${displayMetadata(status?.version)} · Commit ${displayMetadata(status?.commitSha)}`}
        />
        <SummaryCard
          title="Database"
          value={status ? (status.database.canConnect ? "Connected" : "Offline") : "-"}
          subtitle={status ? `${status.database.provider} · ${status.database.target || "No target"}` : "-"}
          tone={dbTone}
        />
        <SummaryCard
          title="SMTP"
          value={status?.email.enabled ? "Enabled" : "Disabled"}
          subtitle={status?.email.host || "No SMTP host configured"}
          tone={status?.email.enabled ? "success" : "default"}
        />
        <SummaryCard
          title="Summarizer"
          value={status?.summarizer.healthy ? "Healthy" : "Offline"}
          subtitle={status?.summarizer.probeLatencyMs != null
            ? `${status.summarizer.probeLatencyMs} ms probe · ${status.summarizer.device || "unknown device"}`
            : status?.summarizer.healthLatencyMs != null
              ? `${status.summarizer.healthLatencyMs} ms health · ${status.summarizer.device || "unknown device"}`
              : "No latency data"}
          tone={summarizerTone}
        />
      </Box>

      <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", lg: "1.2fr 1fr" }, gap: 2 }}>
        <Paper sx={{ p: 2, borderRadius: 3 }}>
          <Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>Database and storage</Typography>
          <Stack spacing={0.75}>
            <DetailRow label="Provider" value={status?.database.provider || "-"} />
            <DetailRow label="Target" value={status?.database.target || "-"} />
            <DetailRow label="Configured" value={status?.database.looksConfigured ? "Yes" : "No"} />
            <DetailRow label="Can connect" value={status?.database.canConnect ? "Yes" : "No"} />
            <DetailRow label="Uses file storage" value={status?.database.usesFileStorage ? "Yes" : "No"} />
            <DetailRow label="Data root" value={status?.storage.dataRoot || "-"} />
            <DetailRow label="DB path" value={status?.storage.dbPath || "-"} />
            <DetailRow label="DB file exists" value={status?.storage.dbExists ? "Yes" : "No"} />
            <DetailRow label="DB size" value={formatBytes(status?.storage.dbSizeBytes)} />
            <DetailRow label="Companies" value={status?.storage.companyCount ?? 0} />
            <DetailRow label="Jobs" value={status?.storage.jobCount ?? 0} />
            <DetailRow label="Deleted jobs" value={status?.storage.deletedCount ?? 0} />
          </Stack>
        </Paper>

        <Paper sx={{ p: 2, borderRadius: 3 }}>
          <Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>Runtime and auth</Typography>
          <Stack spacing={0.75}>
            <DetailRow label="Framework" value={status?.runtime.framework || "-"} />
            <DetailRow label="OS" value={status?.runtime.osDescription || "-"} />
            <DetailRow label="Architecture" value={status?.runtime.processArchitecture || "-"} />
            <DetailRow label="Machine" value={status?.runtime.machineName || "-"} />
            <DetailRow label="Content root" value={status?.contentRoot || "-"} />
            <DetailRow label="Build stamp" value={displayMetadata(status?.buildStamp)} />
            <DetailRow label="Auth required" value={status?.auth.required ? "Yes" : "No"} />
            <DetailRow label="JWT key configured" value={status?.auth.hasJwtKey ? "Yes" : "No"} />
            <DetailRow label="Google login configured" value={status?.auth.googleConfigured ? "Yes" : "No"} />
            <DetailRow label="Gmail integration configured" value={status?.auth.gmailConfigured ? "Yes" : "No"} />
          </Stack>
        </Paper>
      </Box>

      <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", lg: "1fr 1fr" }, gap: 2 }}>
        <Paper sx={{ p: 2, borderRadius: 3 }}>
          <Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>Email configuration</Typography>
          <Stack spacing={0.75}>
            <DetailRow label="Enabled" value={status?.email.enabled ? "Yes" : "No"} />
            <DetailRow label="From" value={status?.email.from || "-"} />
            <DetailRow label="From name" value={status?.email.fromName || "-"} />
            <DetailRow label="Host" value={status?.email.host || "-"} />
            <DetailRow label="Port" value={status?.email.port ?? "-"} />
            <DetailRow label="SSL" value={status?.email.enableSsl ? "Yes" : "No"} />
          </Stack>
        </Paper>

        <Paper sx={{ p: 2, borderRadius: 3 }}>
          <Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>Summarizer runtime</Typography>
          <Stack spacing={0.75}>
            <DetailRow label="Model" value={status?.summarizer.model || "-"} />
            <DetailRow label="Device" value={status?.summarizer.device || "-"} />
            <DetailRow label="GPU available" value={status?.summarizer.gpuAvailable ? "Yes" : "No"} />
            <DetailRow label="GPU name" value={status?.summarizer.gpuName || "-"} />
            <DetailRow label="Health latency" value={status?.summarizer.healthLatencyMs != null ? `${status.summarizer.healthLatencyMs} ms` : "-"} />
            <DetailRow label="Probe latency" value={status?.summarizer.probeLatencyMs != null ? `${status.summarizer.probeLatencyMs} ms` : "-"} />
            <DetailRow label="Last probe" value={formatDate(status?.summarizer.lastProbeAt)} />
            <DetailRow label="Last successful probe" value={formatDate(status?.summarizer.lastProbeSuccessAt)} />
            <DetailRow label="Last summarization success" value={formatDate(status?.summarizer.lastSuccessAt)} />
          </Stack>
        </Paper>
      </Box>

      <Paper sx={{ p: 2, borderRadius: 3 }}>
        <Typography variant="h6" sx={{ fontWeight: 900, mb: 1 }}>Summarizer telemetry</Typography>
        <Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr 1fr", md: "repeat(6, 1fr)" }, gap: 2 }}>
          <Box><Typography variant="overline" sx={{ color: "text.secondary" }}>Requests</Typography><Typography variant="h6" sx={{ fontWeight: 900 }}>{status?.summarizer.requests ?? 0}</Typography></Box>
          <Box><Typography variant="overline" sx={{ color: "text.secondary" }}>Cache hits</Typography><Typography variant="h6" sx={{ fontWeight: 900 }}>{status?.summarizer.cacheHits ?? 0}</Typography></Box>
          <Box><Typography variant="overline" sx={{ color: "text.secondary" }}>Cache misses</Typography><Typography variant="h6" sx={{ fontWeight: 900 }}>{status?.summarizer.cacheMisses ?? 0}</Typography></Box>
          <Box><Typography variant="overline" sx={{ color: "text.secondary" }}>Failures</Typography><Typography variant="h6" sx={{ fontWeight: 900 }}>{status?.summarizer.failures ?? 0}</Typography></Box>
          <Box><Typography variant="overline" sx={{ color: "text.secondary" }}>Probe failures</Typography><Typography variant="h6" sx={{ fontWeight: 900 }}>{status?.summarizer.probeFailures ?? 0}</Typography></Box>
          <Box><Typography variant="overline" sx={{ color: "text.secondary" }}>Avg latency</Typography><Typography variant="h6" sx={{ fontWeight: 900 }}>{status?.summarizer.averageLatencyMs != null ? `${status.summarizer.averageLatencyMs} ms` : "-"}</Typography></Box>
        </Box>
        <Box sx={{ display: "flex", gap: 1, flexWrap: "wrap", mt: 2 }}>
          <Chip label={status?.database.canConnect ? "Database connected" : "Database issue"} color={status?.database.canConnect ? "success" : "error"} size="small" />
          <Chip label={status?.auth.required ? "Auth enforced" : "Auth optional"} color={status?.auth.required ? "success" : "warning"} size="small" />
          <Chip label={status?.auth.googleConfigured ? "Google sign-in ready" : "Google sign-in off"} variant="outlined" size="small" />
          <Chip label={status?.auth.gmailConfigured ? "Gmail ready" : "Gmail incomplete"} variant="outlined" size="small" />
          <Chip label={status?.summarizer.gpuAvailable ? "GPU visible" : "CPU mode"} color={status?.summarizer.gpuAvailable ? "success" : "default"} size="small" />
        </Box>
      </Paper>
    </Box>
  );
}
