"use client";

import React, { useMemo } from "react";
import { Alert, Box, Typography } from "@mui/material";
import type { ApexOptions } from "apexcharts";
import SafeApexCharts from "@/components/charts/SafeApexCharts";
import {
  buildConnectivityChartBuckets,
  type ConnectivityHistoryEvent,
} from "@/components/ClientMonitor/deviceConnectivityChartData";

type Props = {
  events: ConnectivityHistoryEvent[];
  fromLocal: string;
  toLocal: string;
  title?: string;
  subtitle?: string;
  /** printer: only offline events; area chart label for distinct printers */
  variant?: "device" | "printer";
  /** When false, prompt user to run a query first. */
  queried?: boolean;
};

export default function DeviceConnectivityHistoryChart({
  events,
  fromLocal,
  toLocal,
  title = "連線狀況圖",
  subtitle,
  variant = "device",
  queried = true,
}: Props) {
  const buckets = useMemo(
    () => buildConnectivityChartBuckets(events, fromLocal, toLocal),
    [events, fromLocal, toLocal]
  );

  const chartRevision = useMemo(
    () =>
      buckets
        ? `${buckets.categories.length}|${buckets.offlineCounts.join(",")}|${buckets.poorCounts.join(",")}`
        : "empty",
    [buckets]
  );

  const barSeries = useMemo(() => {
    if (variant === "printer") {
      return [{ name: "離線", data: buckets?.offlineCounts ?? [] }];
    }
    return [
      { name: "離線", data: buckets?.offlineCounts ?? [] },
      { name: "連線差", data: buckets?.poorCounts ?? [] },
    ];
  }, [variant, buckets]);

  const options: ApexOptions = useMemo(
    () => ({
      chart: {
        type: "bar",
        stacked: true,
        toolbar: { show: true },
        zoom: { enabled: true },
      },
      plotOptions: {
        bar: {
          columnWidth: "75%",
          borderRadius: 2,
        },
      },
      colors: variant === "printer" ? ["#dc2626"] : ["#dc2626", "#f59e0b"],
      dataLabels: { enabled: false },
      stroke: { width: 0 },
      xaxis: {
        categories: buckets?.categories ?? [],
        labels: {
          rotate: -45,
          rotateAlways: buckets ? buckets.categories.length > 12 : false,
          hideOverlappingLabels: true,
        },
        title: { text: "時間" },
      },
      yaxis: {
        min: 0,
        forceNiceScale: true,
        title: { text: "事件次數" },
        labels: {
          formatter: (v: number) => String(Math.round(v)),
        },
      },
      legend: {
        position: "top",
        horizontalAlign: "right",
      },
      tooltip: {
        shared: true,
        intersect: false,
      },
      fill: { opacity: 0.92 },
    }),
    [buckets, variant]
  );

  const lineOptions: ApexOptions = useMemo(
    () => ({
      chart: {
        type: "area",
        toolbar: { show: false },
        sparkline: { enabled: false },
      },
      colors: ["#2563eb"],
      stroke: { curve: "smooth", width: 2 },
      fill: {
        type: "gradient",
        gradient: {
          shadeIntensity: 0.4,
          opacityFrom: 0.45,
          opacityTo: 0.05,
        },
      },
      dataLabels: { enabled: false },
      xaxis: {
        categories: buckets?.categories ?? [],
        labels: { show: false },
      },
      yaxis: {
        min: 0,
        forceNiceScale: true,
        title: {
          text: variant === "printer" ? "異常印表機數" : "異常裝置數",
        },
        labels: {
          formatter: (v: number) => String(Math.round(v)),
        },
      },
      tooltip: {
        y: {
          formatter: (v: number) => `${Math.round(v)} 台`,
        },
      },
    }),
    [buckets, variant]
  );

  const defaultSubtitle =
    variant === "printer"
      ? "每段時間內印表機 TCP 連線失敗次數（約每 2 分鐘掃描一次）。"
      : "每段時間內離線／連線差事件次數。柱狀愈低愈好；藍線為該時段有異常的裝置數。";

  if (!queried) {
    return (
      <Typography color="text.secondary" sx={{ py: 2 }}>
        選擇時間範圍後按「查詢」，或切換到此分頁時會自動載入。
      </Typography>
    );
  }

  if (!buckets || buckets.categories.length === 0) {
    return (
      <Typography color="text.secondary" sx={{ py: 2 }}>
        無法建立圖表：請確認開始時間早於結束時間。
      </Typography>
    );
  }

  const totalOffline = buckets.offlineCounts.reduce((a, b) => a + b, 0);
  const totalPoor = buckets.poorCounts.reduce((a, b) => a + b, 0);
  const totalEvents = totalOffline + totalPoor;
  const maxAffected = Math.max(...buckets.affectedDeviceCounts, 0);
  const quietBuckets = buckets.affectedDeviceCounts.filter((n) => n === 0).length;
  const healthPct = Math.round(
    (quietBuckets / buckets.affectedDeviceCounts.length) * 100
  );
  const noIncidents = totalEvents === 0;

  return (
    <Box className="space-y-4 rounded-lg border border-slate-200 bg-white p-4 dark:border-slate-700 dark:bg-slate-800">
      <Box className="flex flex-wrap items-end justify-between gap-2">
        <div>
          <Typography variant="subtitle1" fontWeight={600}>
            {title}
          </Typography>
          <Typography variant="body2" color="text.secondary">
            {subtitle ?? `每 ${buckets.bucketMinutes} 分鐘統計一次。${defaultSubtitle}`}
          </Typography>
        </div>
        <Typography
          variant="h6"
          fontWeight={700}
          color={
            noIncidents
              ? "success.main"
              : healthPct >= 80
                ? "success.main"
                : healthPct >= 50
                  ? "warning.main"
                  : "error.main"
          }
        >
          {noIncidents ? "此區間無異常" : `穩定時段 ${healthPct}%`}
        </Typography>
      </Box>

      {noIncidents && (
        <Alert severity="success" sx={{ py: 0.5 }}>
          {variant === "printer"
            ? "此時間範圍內沒有印表機離線記錄。"
            : "此時間範圍內沒有裝置離線或連線差記錄（閒置／在線不會寫入歷史）。"}
        </Alert>
      )}

      <SafeApexCharts
        type="bar"
        height={280}
        series={barSeries}
        options={options}
        chartRevision={`bar-${chartRevision}-${variant}`}
        allowZeroSeries
      />

      <SafeApexCharts
        type="area"
        height={200}
        series={[{ name: "異常裝置數", data: buckets.affectedDeviceCounts }]}
        options={lineOptions}
        chartRevision={`area-${chartRevision}-${variant}`}
        allowZeroSeries
      />

      <Typography variant="caption" color="text.secondary">
        {variant === "printer" ? (
          <>
            區間內：離線記錄 {totalOffline} 次；單段最多 {maxAffected} 台印表機同時無法連線。
          </>
        ) : (
          <>
            區間內：離線事件 {totalOffline} 次、連線差 {totalPoor} 次；單段最多 {maxAffected}{" "}
            台裝置同時異常。
          </>
        )}
      </Typography>
    </Box>
  );
}
