"use client";

import { useEffect, useState, useCallback } from "react";
import { useLanguage } from "@/contexts/LanguageContext";
import { localizedPath } from "@/lib/localized-path";

// ─── Types ────────────────────────────────────────────────────────────────────

type ServiceStatus = "operational" | "degraded" | "outage" | "maintenance" | "unknown";
type DayStatus     = "operational" | "degraded"  | "outage" | "unknown";

interface LiveCheck {
  overall: ServiceStatus;
  checkedAt: string;
  services: {
    api:     { name: string; status: ServiceStatus; latencyMs: number };
    website: { name: string; status: ServiceStatus; latencyMs: number };
  };
}

interface DayEntry  { date: string; status: DayStatus }
interface HistoryData {
  services: {
    api:     DayEntry[];
    website: DayEntry[];
  };
}

interface Incident {
  id: number;
  title: string;
  title_ar: string | null;
  body: string;
  body_ar: string | null;
  service: string;
  status: "investigating" | "identified" | "monitoring" | "resolved";
  started_at: string;
  resolved_at: string | null;
}

// ─── Constants ────────────────────────────────────────────────────────────────

const STATUS_COLOR: Record<string, string> = {
  operational: "#10B981",
  degraded:    "#F59E0B",
  outage:      "#EF4444",
  maintenance: "#6366F1",
  unknown:     "#334155",
};

const BAR_COLOR: Record<DayStatus, string> = {
  operational: "#10B981",
  degraded:    "#F59E0B",
  outage:      "#EF4444",
  unknown:     "#1e293b",
};

const INCIDENT_STATUS_COLOR: Record<string, string> = {
  investigating: "#EF4444",
  identified:    "#F59E0B",
  monitoring:    "#6366F1",
  resolved:      "#10B981",
};

// ─── Sub-components ───────────────────────────────────────────────────────────

function UptimeBar({ history, isRTL }: { history: DayEntry[]; isRTL: boolean }) {
  const display = isRTL ? [...history].reverse() : history;
  const known   = history.filter((d) => d.status !== "unknown");
  const upCount = known.filter((d) => d.status === "operational").length;
  const pct     = known.length > 0 ? Math.round((upCount / known.length) * 1000) / 10 : null;

  return (
    <div>
      <div style={{ display: "flex", gap: 2, alignItems: "center" }}>
        {display.map((entry, i) => (
          <div
            key={i}
            title={`${entry.date} — ${entry.status}`}
            style={{
              flex: 1,
              height: 28,
              borderRadius: 3,
              background: BAR_COLOR[entry.status],
              minWidth: 2,
              cursor: "default",
              transition: "opacity 0.15s",
            }}
            onMouseEnter={(e) => { (e.currentTarget as HTMLDivElement).style.opacity = "0.65"; }}
            onMouseLeave={(e) => { (e.currentTarget as HTMLDivElement).style.opacity = "1"; }}
          />
        ))}
      </div>
      <div style={{
        display: "flex",
        justifyContent: "space-between",
        marginTop: 6,
        fontSize: 11,
        color: "#475569",
        flexDirection: isRTL ? "row-reverse" : "row",
      }}>
        <span>{isRTL ? "منذ 90 يوماً" : "90 days ago"}</span>
        {pct !== null ? (
          <span style={{ color: pct >= 99 ? "#10B981" : pct >= 95 ? "#F59E0B" : "#EF4444", fontWeight: 700 }}>
            {pct}% uptime
          </span>
        ) : (
          <span style={{ color: "#334155" }}>{isRTL ? "لا توجد بيانات بعد" : "No data yet"}</span>
        )}
        <span>{isRTL ? "اليوم" : "Today"}</span>
      </div>
    </div>
  );
}

function StatusPill({ status }: { status: ServiceStatus }) {
  const { t } = useLanguage();
  const color = STATUS_COLOR[status] ?? STATUS_COLOR.unknown;
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6,
      padding: "3px 10px", borderRadius: 20,
      background: `${color}18`, border: `1px solid ${color}35`,
      fontSize: 12, fontWeight: 600, color,
    }}>
      <span style={{
        width: 7, height: 7, borderRadius: "50%", background: color, display: "inline-block",
        animation: status === "operational" ? "pulse-dot 2s ease-in-out infinite" : "none",
      }} />
      {t(`status.badge.${status}`)}
    </span>
  );
}

// ─── Main component ───────────────────────────────────────────────────────────

export default function StatusArea() {
  const { t, language } = useLanguage();
  const isRTL = language === "ar";

  const [live,      setLive]      = useState<LiveCheck | null>(null);
  const [history,   setHistory]   = useState<HistoryData | null>(null);
  const [incidents, setIncidents] = useState<Incident[]>([]);
  const [loading,   setLoading]   = useState(true);
  const [lastChecked, setLastChecked] = useState("");

  const fetchAll = useCallback(async () => {
    try {
      const [liveRes, histRes, incRes] = await Promise.all([
        fetch("/api/status",           { cache: "no-store" }),
        fetch("/api/status/history",   { cache: "no-store" }),
        fetch("/api/status/incidents", { cache: "no-store" }),
      ]);

      if (liveRes.ok)  setLive(await liveRes.json());
      if (histRes.ok)  setHistory(await histRes.json());
      if (incRes.ok)   setIncidents((await incRes.json()).incidents ?? []);

      setLastChecked(new Date().toLocaleTimeString(isRTL ? "ar-SA" : "en-US", {
        hour: "2-digit", minute: "2-digit", second: "2-digit",
      }));
    } catch {
      // silently ignore — keep showing stale data
    } finally {
      setLoading(false);
    }
  }, [isRTL]);

  useEffect(() => {
    fetchAll();
    const interval = setInterval(fetchAll, 60_000);
    return () => clearInterval(interval);
  }, [fetchAll]);

  const overall: ServiceStatus = live?.overall ?? "unknown";
  const allOp = overall === "operational";

  const SERVICES = [
    {
      key:     "api"     as const,
      label:   t("status.service.api"),
      history: history?.services.api     ?? [],
      live:    live?.services.api,
    },
    {
      key:     "website" as const,
      label:   t("status.service.website"),
      history: history?.services.website ?? [],
      live:    live?.services.website,
    },
  ];

  // Incidents: show open ones first, then resolved (newest first)
  const openIncidents     = incidents.filter((i) => i.status !== "resolved");
  const resolvedIncidents = incidents.filter((i) => i.status === "resolved");

  return (
    <section dir={isRTL ? "rtl" : "ltr"} style={{
      background: "#000000", minHeight: "100vh",
      padding: "120px 0 100px", color: "#fff",
    }}>

      <style>{`
        @keyframes pulse-dot {
          0%, 100% { opacity: 1; transform: scale(1); }
          50%       { opacity: .5; transform: scale(1.45); }
        }
        @keyframes fade-in {
          from { opacity: 0; transform: translateY(10px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        .sc { animation: fade-in 0.35s ease both; }
        .rbtn { transition: opacity 0.2s; cursor: pointer; }
        .rbtn:hover { opacity: .7 !important; }
      `}</style>

      <div className="container" style={{ maxWidth: 820 }}>

        {/* ── Page header ── */}
        <div style={{ textAlign: "center", marginBottom: 52 }}>
          <span style={{
            display: "inline-block", padding: "6px 16px",
            background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.08)",
            borderRadius: 20, fontSize: 12, fontWeight: 600, color: "#94a3b8",
            textTransform: "uppercase", letterSpacing: "0.8px", marginBottom: 20,
          }}>
            {t("status.badge.label")}
          </span>
          <h1 style={{ fontSize: "clamp(30px,4vw,46px)", fontWeight: 800, letterSpacing: "-1px", color: "#fff", marginBottom: 12 }}>
            {t("status.title")}
          </h1>
          <p style={{ fontSize: 15, color: "#64748b", maxWidth: 460, margin: "0 auto" }}>
            {t("status.subtitle")}
          </p>
        </div>

        {/* ── Overall banner ── */}
        <div className="sc" style={{
          padding: "20px 26px", borderRadius: 14, marginBottom: 28,
          background: loading ? "rgba(100,116,139,0.06)" : allOp ? "rgba(16,185,129,0.07)" : "rgba(245,158,11,0.07)",
          border: `1px solid ${loading ? "rgba(100,116,139,0.2)" : allOp ? "rgba(16,185,129,0.25)" : "rgba(245,158,11,0.25)"}`,
          display: "flex", alignItems: "center", justifyContent: "space-between",
          flexWrap: "wrap", gap: 14,
          flexDirection: isRTL ? "row-reverse" : "row",
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12, flexDirection: isRTL ? "row-reverse" : "row" }}>
            {loading ? (
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#6366F1" strokeWidth="2.5">
                <path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"
                  strokeLinecap="round"/>
              </svg>
            ) : allOp ? (
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
                <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" stroke="#10B981" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
                <path d="M22 4L12 14.01l-3-3" stroke="#10B981" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            ) : (
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
                <path d="M12 9v4M12 17h.01" stroke="#F59E0B" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
                <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" stroke="#F59E0B" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            )}
            <div>
              <div style={{ fontWeight: 700, fontSize: 16, color: "#fff" }}>
                {loading ? t("status.checking") : t(`status.overall.${overall}`)}
              </div>
              <div style={{ fontSize: 13, color: "#475569", marginTop: 2 }}>
                {t("status.noIssues")}
              </div>
            </div>
          </div>

          <div style={{ display: "flex", alignItems: "center", gap: 10, flexDirection: isRTL ? "row-reverse" : "row" }}>
            {lastChecked && (
              <span style={{ fontSize: 12, color: "#334155" }}>
                {t("status.lastChecked")}: {lastChecked}
              </span>
            )}
            <button
              className="rbtn"
              onClick={fetchAll}
              style={{
                background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.08)",
                borderRadius: 8, padding: "6px 12px", color: "#94a3b8",
                fontSize: 12, display: "flex", alignItems: "center", gap: 6,
              }}
            >
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M23 4v6h-6"/><path d="M1 20v-6h6"/>
                <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/>
              </svg>
              {t("status.refresh")}
            </button>
          </div>
        </div>

        {/* ── Active incidents (if any) ── */}
        {openIncidents.length > 0 && (
          <div style={{ marginBottom: 28 }}>
            {openIncidents.map((inc, i) => (
              <div key={inc.id} className="sc" style={{
                padding: "16px 20px", borderRadius: 12, marginBottom: 10,
                background: "rgba(239,68,68,0.06)", border: "1px solid rgba(239,68,68,0.2)",
                animationDelay: `${i * 0.05}s`,
              }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6,
                  flexDirection: isRTL ? "row-reverse" : "row" }}>
                  <span style={{
                    padding: "2px 8px", borderRadius: 6, fontSize: 11, fontWeight: 700,
                    color: INCIDENT_STATUS_COLOR[inc.status],
                    background: `${INCIDENT_STATUS_COLOR[inc.status]}18`,
                    border: `1px solid ${INCIDENT_STATUS_COLOR[inc.status]}35`,
                    textTransform: "uppercase",
                  }}>
                    {t(`status.incidentStatus.${inc.status}`)}
                  </span>
                  <span style={{ fontWeight: 600, fontSize: 14, color: "#f1f5f9" }}>
                    {isRTL && inc.title_ar ? inc.title_ar : inc.title}
                  </span>
                  <span style={{ fontSize: 11, color: "#475569", marginInlineStart: "auto" }}>
                    {inc.service}
                  </span>
                </div>
                <p style={{ fontSize: 13, color: "#64748b", margin: 0, lineHeight: 1.65 }}>
                  {isRTL && inc.body_ar ? inc.body_ar : inc.body}
                </p>
              </div>
            ))}
          </div>
        )}

        {/* ── Service uptime cards ── */}
        <div className="sc" style={{
          background: "rgba(255,255,255,0.025)", border: "1px solid rgba(255,255,255,0.06)",
          borderRadius: 16, overflow: "hidden", marginBottom: 32,
        }}>
          <div style={{ padding: "14px 22px", borderBottom: "1px solid rgba(255,255,255,0.06)" }}>
            <span style={{ fontSize: 12, fontWeight: 700, color: "#475569",
              textTransform: "uppercase", letterSpacing: "1px" }}>
              {t("status.systemStatus")} · {t("status.last90")}
            </span>
          </div>

          {SERVICES.map((svc, idx) => {
            const svcStatus: ServiceStatus = svc.live?.status ?? "unknown";
            return (
              <div key={svc.key} className="sc" style={{
                padding: "20px 22px",
                borderBottom: idx < SERVICES.length - 1 ? "1px solid rgba(255,255,255,0.05)" : "none",
                animationDelay: `${0.05 + idx * 0.08}s`,
              }}>
                <div style={{
                  display: "flex", alignItems: "center", justifyContent: "space-between",
                  marginBottom: 14, flexDirection: isRTL ? "row-reverse" : "row",
                }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10,
                    flexDirection: isRTL ? "row-reverse" : "row" }}>
                    <div style={{
                      width: 10, height: 10, borderRadius: "50%",
                      background: STATUS_COLOR[svcStatus],
                      boxShadow: `0 0 0 3px ${STATUS_COLOR[svcStatus]}22`,
                      flexShrink: 0,
                    }} />
                    <span style={{ fontWeight: 600, fontSize: 15, color: "#e2e8f0" }}>{svc.label}</span>
                    {svc.live?.latencyMs != null && (
                      <span style={{ fontSize: 12, color: "#334155" }}>{svc.live.latencyMs}ms</span>
                    )}
                  </div>
                  <StatusPill status={svcStatus} />
                </div>

                {svc.history.length > 0
                  ? <UptimeBar history={svc.history} isRTL={isRTL} />
                  : (
                    <div style={{ height: 28, background: "#0f172a", borderRadius: 4,
                      display: "flex", alignItems: "center", justifyContent: "center" }}>
                      <span style={{ fontSize: 11, color: "#334155" }}>
                        {loading ? (isRTL ? "جارٍ التحميل…" : "Loading…") : (isRTL ? "لا توجد بيانات تاريخية بعد" : "No history yet — data accumulates from the first check")}
                      </span>
                    </div>
                  )
                }
              </div>
            );
          })}
        </div>

        {/* ── Resolved incident history ── */}
        <div style={{ marginBottom: 48 }}>
          <h2 style={{ fontSize: 18, fontWeight: 700, color: "#fff", marginBottom: 18,
            textAlign: isRTL ? "right" : "left" }}>
            {t("status.incidentHistory")}
          </h2>

          {resolvedIncidents.length === 0 ? (
            <div style={{
              background: "rgba(16,185,129,0.05)", border: "1px solid rgba(16,185,129,0.15)",
              borderRadius: 12, padding: "32px 24px", textAlign: "center",
            }}>
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none" style={{ margin: "0 auto 10px" }}>
                <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" stroke="#10B981" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                <path d="M22 4L12 14.01l-3-3" stroke="#10B981" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
              <div style={{ fontWeight: 600, color: "#10B981", fontSize: 14, marginBottom: 6 }}>
                {isRTL ? "لا توجد أعطال مسجّلة" : "No incidents on record"}
              </div>
              <div style={{ fontSize: 13, color: "#334155" }}>
                {isRTL ? "كل الخدمات تعمل بشكل طبيعي منذ البداية." : "All services have been running smoothly since monitoring began."}
              </div>
            </div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {resolvedIncidents.map((inc, i) => (
                <div key={inc.id} className="sc" style={{
                  background: "rgba(255,255,255,0.025)", border: "1px solid rgba(255,255,255,0.06)",
                  borderRadius: 12, padding: "18px 20px",
                  animationDelay: `${0.15 + i * 0.08}s`,
                }}>
                  <div style={{ display: "flex", alignItems: "flex-start", gap: 12,
                    flexDirection: isRTL ? "row-reverse" : "row" }}>
                    <div style={{
                      flexShrink: 0, width: 28, height: 28, borderRadius: "50%",
                      background: "rgba(16,185,129,0.12)", display: "flex",
                      alignItems: "center", justifyContent: "center", marginTop: 2,
                    }}>
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                        <path d="M20 6L9 17l-5-5" stroke="#10B981" strokeWidth="2.5"
                          strokeLinecap="round" strokeLinejoin="round"/>
                      </svg>
                    </div>
                    <div style={{ flex: 1, textAlign: isRTL ? "right" : "left" }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6,
                        flexWrap: "wrap", flexDirection: isRTL ? "row-reverse" : "row" }}>
                        <span style={{ fontWeight: 600, fontSize: 14, color: "#e2e8f0" }}>
                          {isRTL && inc.title_ar ? inc.title_ar : inc.title}
                        </span>
                        <span style={{
                          padding: "2px 8px", borderRadius: 6, fontSize: 11, fontWeight: 600,
                          color: "#10B981", background: "rgba(16,185,129,0.1)",
                          border: "1px solid rgba(16,185,129,0.25)",
                        }}>
                          {t("status.resolved")}
                        </span>
                        <span style={{
                          padding: "2px 8px", borderRadius: 6, fontSize: 11, color: "#475569",
                          background: "rgba(255,255,255,0.04)", border: "1px solid rgba(255,255,255,0.08)",
                        }}>
                          {inc.service}
                        </span>
                      </div>
                      <p style={{ fontSize: 13, color: "#64748b", margin: "0 0 8px", lineHeight: 1.6 }}>
                        {isRTL && inc.body_ar ? inc.body_ar : inc.body}
                      </p>
                      <div style={{ fontSize: 12, color: "#334155" }}>
                        {new Date(inc.started_at).toLocaleDateString(isRTL ? "ar-SA" : "en-US", {
                          year: "numeric", month: "long", day: "numeric",
                        })}
                        {inc.resolved_at && (
                          <span style={{ marginInlineStart: 6 }}>
                            → {new Date(inc.resolved_at).toLocaleDateString(isRTL ? "ar-SA" : "en-US", {
                              year: "numeric", month: "long", day: "numeric",
                            })}
                          </span>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* ── CTA ── */}
        <div style={{
          textAlign: "center", padding: "30px 24px",
          background: "rgba(99,102,241,0.06)", border: "1px solid rgba(99,102,241,0.18)",
          borderRadius: 14,
        }}>
          <div style={{ fontSize: 15, fontWeight: 600, color: "#e2e8f0", marginBottom: 8 }}>
            {t("status.cta.title")}
          </div>
          <p style={{ fontSize: 13, color: "#64748b", maxWidth: 400, margin: "0 auto 18px" }}>
            {t("status.cta.sub")}
          </p>
          <a href={localizedPath("/contact-us", language)} style={{
            display: "inline-flex", alignItems: "center", gap: 8,
            padding: "10px 24px", background: "rgba(99,102,241,0.15)",
            border: "1px solid rgba(99,102,241,0.35)", borderRadius: 9,
            color: "#a5b4fc", fontSize: 13, fontWeight: 600, textDecoration: "none",
          }}>
            {t("status.cta.btn")}
          </a>
        </div>

      </div>
    </section>
  );
}
