"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import type {
  SystemHealth,
  HealthCheckResult,
  HealthStatus,
} from "@/lib/types/health";
import { UI } from "@/lib/config";
import type { Lang } from "@/lib/config";

interface StatusPageClientProps {
  lang: Lang;
  initialHealth: SystemHealth;
}

export default function StatusPageClient({
  lang,
  initialHealth,
}: StatusPageClientProps) {
  const [health, setHealth] = useState<SystemHealth>(initialHealth);
  const [loading, setLoading] = useState(false);
  const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [mounted, setMounted] = useState(false);

  const isAr = lang === "ar";
  const dir = isAr ? "rtl" : "ltr";

  const fetchStatus = async () => {
    try {
      setLoading(true);
      const response = await fetch("/api/status");

      if (response.status === 429) {
        setError("rateLimitExceeded");
        return;
      }

      if (!response.ok) {
        throw new Error("Failed to fetch status");
      }

      const data = await response.json();
      setHealth(data);
      setLastUpdated(new Date());
      setError(null);
    } catch (err) {
      console.error("Failed to fetch status:", err);
      setError("fetchFailed");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    setMounted(true);
    setLastUpdated(new Date());

    // Auto-refresh every 30 seconds
    const interval = setInterval(fetchStatus, 30000);
    return () => clearInterval(interval);
  }, []);

  const getStatusColor = (status: HealthStatus): string => {
    switch (status) {
      case "operational":
        return "#10B981"; // Mawidi green
      case "degraded":
        return "#F59E0B"; // Amber
      case "down":
        return "#EF4444"; // Red
      default:
        return "#64748B"; // Slate
    }
  };

  const getStatusText = (status: HealthStatus): string => {
    const translations = UI[lang].t.status || {};
    switch (status) {
      case "operational":
        return translations.operational || "Operational";
      case "degraded":
        return translations.degraded || "Degraded";
      case "down":
        return translations.down || "Down";
      default:
        return translations.unknown || "Unknown";
    }
  };

  const getOverallMessage = (status: HealthStatus): string => {
    const translations = UI[lang].t.status || {};
    switch (status) {
      case "operational":
        return translations.allOperational || "All systems are operational";
      case "degraded":
        return (
          translations.someIssues || "Some systems are experiencing issues"
        );
      case "down":
        return translations.majorOutage || "Major service disruption detected";
      default:
        return translations.checking || "Checking system status...";
    }
  };

  // Calculate uptime percentage (mock data for display)
  const uptimePercentage =
    health.overall === "operational"
      ? "99.99"
      : health.overall === "degraded"
        ? "99.5"
        : "95.0";

  return (
    <main className="min-h-screen bg-white" dir={dir}>
      {/* ══════════════════════════════════════════════════════════════════
          HERO SECTION - Editorial Style
      ══════════════════════════════════════════════════════════════════ */}
      <section className="relative py-24 md:py-32 bg-gradient-to-b from-white via-[#FAFAFA] to-white overflow-hidden">
        {/* Subtle grid pattern */}
        <div
          className="pointer-events-none absolute inset-0 opacity-[0.02]"
          aria-hidden="true"
          style={{
            backgroundImage: `
              linear-gradient(to right, #1E293B 1px, transparent 1px),
              linear-gradient(to bottom, #1E293B 1px, transparent 1px)
            `,
            backgroundSize: "80px 80px",
          }}
        />

        <div className="relative z-10 mx-auto max-w-7xl px-6">
          <div className="max-w-4xl">
            {/* Section marker */}
            <div className="flex items-center gap-3 mb-8">
              <span
                className="text-[#10B981] font-mono text-sm tracking-wider"
                dir="ltr"
              >
                STATUS
              </span>
              <div className="w-12 h-px bg-[#10B981]" />
              <span className="text-[#10B981] text-sm font-medium uppercase tracking-wider">
                {isAr ? "مراقبة مباشرة" : "Live Monitoring"}
              </span>
            </div>

            {/* Headline */}
            <h1 className="text-5xl md:text-6xl lg:text-7xl font-bold text-[#1E293B] leading-[1.1] tracking-tight mb-8">
              {UI[lang].t.status?.title || "System Status"}
            </h1>

            {/* Subhead */}
            <p className="text-xl md:text-2xl text-[#64748B] leading-relaxed max-w-3xl mb-8">
              {UI[lang].t.status?.subtitle ||
                "Real-time monitoring of all Mawidi services"}
            </p>

            {/* Last updated */}
            <div className="flex items-center gap-3 text-sm text-[#64748B]">
              <div className="w-1.5 h-1.5 bg-[#10B981]" />
              <span>
                {UI[lang].t.status?.lastUpdated || "Last updated"}:{" "}
                <span className="font-mono">
                  {mounted && lastUpdated
                    ? lastUpdated.toLocaleTimeString(isAr ? "ar-SA" : "en-US")
                    : "..."}
                </span>
              </span>
              {loading && (
                <span className="text-[#10B981]">
                  {isAr ? "جاري التحديث..." : "Updating..."}
                </span>
              )}
            </div>
          </div>
        </div>
      </section>

      {/* ══════════════════════════════════════════════════════════════════
          ERROR ALERT - Editorial Style
      ══════════════════════════════════════════════════════════════════ */}
      {error && (
        <section className="py-4 bg-[#FAFAFA]">
          <div className="mx-auto max-w-7xl px-6">
            <div className="bg-white border-l-4 border-red-500 p-6">
              <div className="flex items-start gap-4">
                <div className="w-1.5 h-1.5 bg-red-500 mt-2 flex-shrink-0" />
                <p className="text-[#64748B]">
                  {error === "rateLimitExceeded"
                    ? UI[lang].t.status?.rateLimitError ||
                      "Too many requests. Please wait a moment before refreshing."
                    : UI[lang].t.status?.fetchError ||
                      "Unable to fetch current status. Showing last known state."}
                </p>
              </div>
            </div>
          </div>
        </section>
      )}

      {/* ══════════════════════════════════════════════════════════════════
          OVERALL STATUS - Editorial Hero Card
      ══════════════════════════════════════════════════════════════════ */}
      <section className="py-16 bg-[#FAFAFA]">
        <div className="mx-auto max-w-7xl px-6">
          <div
            className="p-8 md:p-12 transition-colors duration-300"
            style={{
              backgroundColor:
                health.overall === "operational"
                  ? "#10B981"
                  : health.overall === "degraded"
                    ? "#F59E0B"
                    : "#EF4444",
            }}
          >
            <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-8">
              {/* Status Info */}
              <div>
                <div className="flex items-center gap-3 mb-4">
                  <span
                    className="text-white/70 font-mono text-sm tracking-wider"
                    dir="ltr"
                  >
                    00
                  </span>
                  <div className="w-8 h-px bg-white/30" />
                  <span className="text-white/70 text-sm font-medium uppercase tracking-wider">
                    {isAr ? "الحالة العامة" : "Overall Status"}
                  </span>
                </div>

                <h2 className="text-4xl md:text-5xl font-bold text-white mb-4">
                  {getStatusText(health.overall)}
                </h2>

                <p className="text-xl text-white/80">
                  {getOverallMessage(health.overall)}
                </p>
              </div>

              {/* Stats Grid */}
              <div className="grid grid-cols-2 gap-px bg-white/20">
                <div className="bg-white/10 backdrop-blur-sm p-6 text-center">
                  <div className="text-3xl md:text-4xl font-bold text-white font-mono mb-1">
                    {health.components.length}
                  </div>
                  <div className="text-sm text-white/70 uppercase tracking-wider">
                    {isAr ? "الأنظمة" : "Systems"}
                  </div>
                </div>
                <div className="bg-white/10 backdrop-blur-sm p-6 text-center">
                  <div className="text-3xl md:text-4xl font-bold text-white font-mono mb-1">
                    {uptimePercentage}%
                  </div>
                  <div className="text-sm text-white/70 uppercase tracking-wider">
                    {isAr ? "التشغيل" : "Uptime"}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* ══════════════════════════════════════════════════════════════════
          SYSTEM COMPONENTS - Editorial Grid
      ══════════════════════════════════════════════════════════════════ */}
      <section className="py-16 md:py-24 bg-white">
        <div className="mx-auto max-w-7xl px-6">
          {/* Section Header */}
          <div className="flex items-start gap-4 mb-12">
            <div className="flex items-center gap-3 pt-2">
              <span
                className="text-[#10B981] font-mono text-sm tracking-wider"
                dir="ltr"
              >
                01
              </span>
              <div className="w-12 h-px bg-[#10B981]" />
            </div>
            <div>
              <h2 className="text-3xl md:text-4xl font-bold text-[#1E293B] mb-2">
                {UI[lang].t.status?.components || "System Components"}
              </h2>
              <p className="text-[#64748B]">
                {isAr ? "حالة كل خدمة على حدة" : "Individual service status"}
              </p>
            </div>
          </div>

          {/* Components Grid */}
          {health.components.length === 0 ? (
            <div className="bg-[#FAFAFA] p-12 text-center">
              <div className="flex items-center justify-center gap-3 mb-4">
                <span className="text-[#10B981] font-mono text-sm" dir="ltr">
                  ...
                </span>
                <div className="w-8 h-px bg-slate-200" />
              </div>
              <p className="text-[#64748B]">
                {UI[lang].t.status?.checking || "Checking system status..."}
              </p>
            </div>
          ) : (
            <div className="grid md:grid-cols-2 gap-px bg-slate-200">
              {health.components.map(
                (component: HealthCheckResult, index: number) => (
                  <div
                    key={index}
                    className="group bg-white p-8 hover:bg-[#FAFAFA] transition-colors duration-300"
                  >
                    <div className="flex items-start justify-between gap-6">
                      {/* Component Info */}
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-3 mb-3">
                          <span
                            className="text-[#10B981] font-mono text-xs"
                            dir="ltr"
                          >
                            {String(index + 1).padStart(2, "0")}
                          </span>
                          <h3 className="text-xl font-bold text-[#1E293B]">
                            {component.name}
                          </h3>
                        </div>

                        <p className="text-sm text-[#64748B] mb-4">
                          {component.message}
                        </p>

                        {/* Response Time */}
                        <div className="flex items-center gap-2 text-xs text-[#64748B]">
                          <div className="w-1.5 h-1.5 bg-[#10B981]" />
                          <span className="font-mono">
                            {component.responseTime}ms
                          </span>
                          <span>
                            {isAr ? "وقت الاستجابة" : "response time"}
                          </span>
                        </div>
                      </div>

                      {/* Status Badge */}
                      <div
                        className="flex-shrink-0 px-4 py-2 text-sm font-bold uppercase tracking-wider text-white"
                        style={{
                          backgroundColor: getStatusColor(component.status),
                        }}
                      >
                        {getStatusText(component.status)}
                      </div>
                    </div>

                    {/* Status Bar */}
                    <div className="mt-6 h-1 bg-slate-100 overflow-hidden">
                      <div
                        className="h-full transition-all duration-500"
                        style={{
                          width:
                            component.status === "operational"
                              ? "100%"
                              : component.status === "degraded"
                                ? "60%"
                                : "20%",
                          backgroundColor: getStatusColor(component.status),
                        }}
                      />
                    </div>

                    {/* Hover underline */}
                    <div className="w-0 group-hover:w-12 h-0.5 bg-[#10B981] mt-4 transition-all duration-300" />
                  </div>
                ),
              )}
            </div>
          )}
        </div>
      </section>

      {/* ══════════════════════════════════════════════════════════════════
          UPTIME HISTORY - Editorial Timeline (Mock Data)
      ══════════════════════════════════════════════════════════════════ */}
      <section className="py-16 md:py-24 bg-[#FAFAFA]">
        <div className="mx-auto max-w-7xl px-6">
          {/* Section Header */}
          <div className="flex items-start gap-4 mb-12">
            <div className="flex items-center gap-3 pt-2">
              <span
                className="text-[#10B981] font-mono text-sm tracking-wider"
                dir="ltr"
              >
                02
              </span>
              <div className="w-12 h-px bg-[#10B981]" />
            </div>
            <div>
              <h2 className="text-3xl md:text-4xl font-bold text-[#1E293B] mb-2">
                {isAr ? "سجل التشغيل" : "Uptime History"}
              </h2>
              <p className="text-[#64748B]">
                {isAr ? "آخر 30 يوم" : "Last 30 days"}
              </p>
            </div>
          </div>

          {/* Uptime Bars - Visual representation */}
          <div className="bg-white p-8">
            <div className="flex items-end gap-1 h-16">
              {Array.from({ length: 30 }, (_, i) => {
                // Mock data: mostly operational with occasional degraded
                const isOperational = Math.random() > 0.05;
                const isDegraded = !isOperational && Math.random() > 0.5;
                return (
                  <div
                    key={i}
                    className="flex-1 transition-all duration-300 hover:opacity-80"
                    style={{
                      height: isOperational
                        ? "100%"
                        : isDegraded
                          ? "60%"
                          : "20%",
                      backgroundColor: isOperational
                        ? "#10B981"
                        : isDegraded
                          ? "#F59E0B"
                          : "#EF4444",
                    }}
                    title={`Day ${30 - i}: ${isOperational ? "Operational" : isDegraded ? "Degraded" : "Down"}`}
                  />
                );
              })}
            </div>

            {/* Legend */}
            <div className="flex items-center justify-between mt-6 pt-6 border-t border-slate-100">
              <span className="text-xs text-[#64748B] font-mono">
                {isAr ? "قبل 30 يوم" : "30 days ago"}
              </span>
              <div className="flex items-center gap-6">
                <div className="flex items-center gap-2">
                  <div className="w-3 h-3 bg-[#10B981]" />
                  <span className="text-xs text-[#64748B]">
                    {isAr ? "تشغيل" : "Operational"}
                  </span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-3 h-3 bg-[#F59E0B]" />
                  <span className="text-xs text-[#64748B]">
                    {isAr ? "متدهور" : "Degraded"}
                  </span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-3 h-3 bg-[#EF4444]" />
                  <span className="text-xs text-[#64748B]">
                    {isAr ? "معطل" : "Down"}
                  </span>
                </div>
              </div>
              <span className="text-xs text-[#64748B] font-mono">
                {isAr ? "اليوم" : "Today"}
              </span>
            </div>
          </div>
        </div>
      </section>

      {/* ══════════════════════════════════════════════════════════════════
          INFO FOOTER - Editorial Style
      ══════════════════════════════════════════════════════════════════ */}
      <section className="py-16 bg-white">
        <div className="mx-auto max-w-7xl px-6">
          <div className="grid md:grid-cols-3 gap-px bg-slate-200">
            {/* Auto-refresh info */}
            <div className="group bg-white p-8 hover:bg-[#FAFAFA] transition-colors duration-300">
              <div className="flex items-center gap-3 mb-3">
                <span className="text-[#10B981] font-mono text-xs" dir="ltr">
                  A
                </span>
                <h3 className="font-bold text-[#1E293B]">
                  {isAr ? "تحديث تلقائي" : "Auto Refresh"}
                </h3>
              </div>
              <p className="text-sm text-[#64748B]">
                {UI[lang].t.status?.autoRefresh ||
                  "Status updates automatically every 30 seconds"}
              </p>
              <div className="w-0 group-hover:w-8 h-0.5 bg-[#10B981] mt-4 transition-all duration-300" />
            </div>

            {/* Subscribe to updates */}
            <div className="group bg-white p-8 hover:bg-[#FAFAFA] transition-colors duration-300">
              <div className="flex items-center gap-3 mb-3">
                <span className="text-[#10B981] font-mono text-xs" dir="ltr">
                  B
                </span>
                <h3 className="font-bold text-[#1E293B]">
                  {isAr ? "الإشعارات" : "Notifications"}
                </h3>
              </div>
              <p className="text-sm text-[#64748B]">
                {isAr
                  ? "تابعنا للحصول على تحديثات حول حالة الخدمة"
                  : "Follow us for service status updates"}
              </p>
              <div className="w-0 group-hover:w-8 h-0.5 bg-[#10B981] mt-4 transition-all duration-300" />
            </div>

            {/* Report issue */}
            <div className="group bg-white p-8 hover:bg-[#FAFAFA] transition-colors duration-300">
              <div className="flex items-center gap-3 mb-3">
                <span className="text-[#10B981] font-mono text-xs" dir="ltr">
                  C
                </span>
                <h3 className="font-bold text-[#1E293B]">
                  {isAr ? "الإبلاغ عن مشكلة" : "Report Issue"}
                </h3>
              </div>
              <p className="text-sm text-[#64748B]">
                {UI[lang].t.status?.issues ||
                  "If you experience issues not reflected here, please contact support"}
              </p>
              <div className="w-0 group-hover:w-8 h-0.5 bg-[#10B981] mt-4 transition-all duration-300" />
            </div>
          </div>
        </div>
      </section>

      {/* ══════════════════════════════════════════════════════════════════
          CONTACT CTA - Editorial Style
      ══════════════════════════════════════════════════════════════════ */}
      <section className="py-24 md:py-32 bg-[#FAFAFA]">
        <div className="mx-auto max-w-7xl px-6">
          <div className="bg-[#1E293B] p-12 md:p-20">
            <div className="max-w-3xl mx-auto text-center">
              {/* Section marker */}
              <div className="flex items-center justify-center gap-3 mb-8">
                <span
                  className="text-[#10B981] font-mono text-sm tracking-wider"
                  dir="ltr"
                >
                  SUPPORT
                </span>
                <div className="w-12 h-px bg-[#10B981]" />
              </div>

              <h2 className="text-4xl md:text-5xl font-bold text-white leading-tight mb-6">
                {isAr ? "هل تواجه مشكلة؟" : "Experiencing Issues?"}
              </h2>
              <p className="text-lg md:text-xl text-white/70 mb-10">
                {isAr
                  ? "إذا كنت تواجه مشاكل غير معروضة هنا، فريق الدعم لدينا جاهز للمساعدة"
                  : "If you're experiencing problems not shown here, our support team is ready to help"}
              </p>

              <div className="flex flex-wrap items-center justify-center gap-4">
                <Link
                  href={`/${lang}/contact`}
                  className="group relative inline-flex items-center gap-3 px-8 py-4 bg-[#10B981] text-white font-semibold overflow-hidden transition-all duration-300"
                >
                  <span className="relative z-10">
                    {isAr ? "اتصل بالدعم" : "Contact Support"}
                  </span>
                  <svg
                    className="relative z-10 h-5 w-5 transition-transform duration-300 group-hover:translate-x-1"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d={
                        isAr
                          ? "M19 12H5M12 5l-7 7 7 7"
                          : "M5 12h14M12 5l7 7-7 7"
                      }
                    />
                  </svg>
                  <div className="absolute inset-0 bg-[#059669] transform translate-y-full group-hover:translate-y-0 transition-transform duration-300" />
                </Link>
                <Link
                  href={`/${lang}/help`}
                  className="inline-flex items-center gap-2 px-8 py-4 border-2 border-white/30 text-white font-semibold hover:bg-white/10 transition-colors duration-300"
                >
                  {isAr ? "مركز المساعدة" : "Help Center"}
                </Link>
              </div>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}
