"use client";
import React, { useState } from "react";
import { motion } from "framer-motion";
import { SpotlightCard } from "@/components/SpotlightCard";
import { Settings, ShieldAlert, Cpu, Activity, Play, RefreshCw, AlertTriangle } from "lucide-react";

export default function PredictiveMaintenancePage() {
  const [isScanning, setIsScanning] = useState(false);
  const [scanLogs, setScanLogs] = useState<string[]>([
    "SYS_READY: Ready for operational asset scan.",
  ]);
  const [anomalyFound, setAnomalyFound] = useState(false);

  const runDiagnosticScan = () => {
    setIsScanning(true);
    setAnomalyFound(false);
    setScanLogs(["SYS_SCAN: Connecting to physical edge sensor networks..."]);

    const events = [
      { t: 600, log: "SYS_FFT: Fetching vibration frequency spectra (Node-8)..." },
      { t: 1200, log: "SYS_THERMAL: Sampling bearings temperature matrix..." },
      { t: 1800, log: "WARNING: Vibration spike detected on Axis-Y (4.8 mm/s RMS)." },
      { t: 2400, log: "SYS_DIAGNOSIS: Bearing structural fatigue identified on Compressor Turbine ST-12." },
    ];

    events.forEach((ev) => {
      setTimeout(() => {
        setScanLogs((prev) => [...prev, ev.log]);
      }, ev.t);
    });

    setTimeout(() => {
      setIsScanning(false);
      setAnomalyFound(true);
    }, 2800);
  };

  return (
    <div className="relative min-h-screen pt-20 pb-16 overflow-hidden">
      {/* Background grids */}
      <div className="pointer-events-none absolute inset-0 orbit-grid-mesh opacity-80" />
      <div className="pointer-events-none absolute inset-0 orbit-radial-glow" />

      <div className="mx-auto max-w-7xl px-6 lg:px-8 relative z-10 space-y-16">
        
        {/* Cinematic Hero */}
        <div className="max-w-3xl space-y-6">
          <div className="inline-flex items-center gap-1.5 rounded-full border border-orbit-purple/20 bg-orbit-purple/5 px-4 py-1.5 font-mono text-xs font-bold text-orbit-purple">
            <Settings className="h-4.5 w-4.5 animate-pulse" />
            Orbit Maintenance Module
          </div>
          <h1 className="text-4xl font-extrabold tracking-tight sm:text-6xl text-slate-900 dark:text-slate-100 leading-tight">
            AI Anomaly & <br />
            <span className="bg-gradient-to-r from-orbit-purple via-orbit-blue to-orbit-cyan bg-clip-text text-transparent">Predictive Analytics.</span>
          </h1>
          <p className="text-base md:text-lg leading-relaxed text-slate-600 dark:text-slate-400">
            Pre-empt unplanned shutdowns. Orbit AI maps multi-dimensional vibration patterns, identifies mechanical wear precursors, and schedules autonomous maintenance workflows 7–21 days in advance.
          </p>
        </div>

        {/* Global Asset Stats Grid */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
          <SpotlightCard glowColor="rgba(168, 85, 247, 0.15)">
            <div className="text-center space-y-2">
              <span className="font-mono text-[9px] text-slate-500 uppercase tracking-widest block">Mean Time Between Failures</span>
              <span className="font-mono text-3xl font-extrabold text-slate-900 dark:text-white">4,280 Hrs</span>
              <p className="text-[10px] text-slate-500 font-mono">+12.4% vs industry baseline</p>
            </div>
          </SpotlightCard>
          <SpotlightCard glowColor="rgba(168, 85, 247, 0.15)">
            <div className="text-center space-y-2">
              <span className="font-mono text-[9px] text-slate-500 uppercase tracking-widest block">Mean Time To Repair</span>
              <span className="font-mono text-3xl font-extrabold text-slate-900 dark:text-white">1.8 Hrs</span>
              <p className="text-[10px] text-slate-500 font-mono">-38.2% downtime optimization</p>
            </div>
          </SpotlightCard>
          <SpotlightCard glowColor="rgba(168, 85, 247, 0.15)">
            <div className="text-center space-y-2">
              <span className="font-mono text-[9px] text-slate-500 uppercase tracking-widest block">Active Telemetry Sensors</span>
              <span className="font-mono text-3xl font-extrabold text-slate-900 dark:text-white">1,842</span>
              <p className="text-[10px] text-slate-500 font-mono">100% nominal connection status</p>
            </div>
          </SpotlightCard>
          <SpotlightCard glowColor="rgba(168, 85, 247, 0.15)">
            <div className="text-center space-y-2">
              <span className="font-mono text-[9px] text-slate-500 uppercase tracking-widest block">Mitigated Cascade Failures</span>
              <span className="font-mono text-3xl font-extrabold text-orbit-purple">48</span>
              <p className="text-[10px] text-slate-500 font-mono">Critical downtime avoided YTD</p>
            </div>
          </SpotlightCard>
        </div>

        {/* Interactive Anomaly Simulator Console */}
        <div className="rounded-3xl border border-orbit-border bg-orbit-bg-primary overflow-hidden shadow-2xl">
          <div className="border-b border-orbit-border/60 bg-orbit-bg-deep px-6 py-4 flex justify-between items-center">
            <span className="font-mono text-xs font-bold text-slate-600 dark:text-slate-400">OPERATIONAL ANOMALY SCANNER CONSOLE</span>
            <button
              onClick={runDiagnosticScan}
              disabled={isScanning}
              className="flex items-center gap-1.5 rounded-full bg-gradient-to-r from-orbit-purple to-orbit-cyan px-4 py-1.5 font-mono text-[10px] font-bold text-white shadow-md active:scale-95 disabled:opacity-50"
            >
              {isScanning ? (
                <RefreshCw className="h-3 w-3 animate-spin" />
              ) : (
                <Activity className="h-3 w-3 animate-pulse" />
              )}
              Execute Diagnostic Scan
            </button>
          </div>

          <div className="p-6 bg-orbit-bg-primary/95 grid grid-cols-1 lg:grid-cols-12 gap-8 items-stretch">
            {/* Terminal output (7 cols) */}
            <div className="lg:col-span-7 rounded-2xl border border-orbit-border bg-orbit-bg-deep p-5 min-h-[220px] font-mono text-xs text-emerald-400 space-y-2.5 flex flex-col justify-start">
              {scanLogs.map((log, index) => (
                <div key={index} className="flex gap-2 items-start">
                  <span className="text-slate-600 select-none">&gt;&gt;</span>
                  <span className={log.includes("WARNING") ? "text-orange-400" : ""}>{log}</span>
                </div>
              ))}
              {isScanning && (
                <div className="flex gap-2 items-center text-orbit-cyan animate-pulse mt-2">
                  <RefreshCw className="h-3.5 w-3.5 animate-spin" />
                  <span>Processing diagnostic FFT streams...</span>
                </div>
              )}
            </div>

            {/* AI Insights & Actions (5 cols) */}
            <div className="lg:col-span-5 flex flex-col justify-between p-2">
              <div className="space-y-4">
                <h3 className="font-mono text-xs font-bold text-slate-700 dark:text-slate-300 uppercase tracking-widest">DIAGNOSTIC STATUS</h3>
                
                {anomalyFound ? (
                  <div className="rounded-2xl border border-orange-500/20 bg-orange-950/15 p-4 space-y-3">
                    <div className="flex items-center gap-2 text-orange-400 font-mono text-xs font-bold">
                      <AlertTriangle className="h-4.5 w-4.5 shrink-0" />
                      <span>BEARING STRUCTURE FAULT REPORTED</span>
                    </div>
                    <p className="text-xs leading-relaxed text-slate-600 dark:text-slate-400">
                      Spike of 4.8 mm/s vibration frequency is classified as structural bearing degradation. Expected operational timeframe to failure: 11 to 15 days.
                    </p>
                    <div className="rounded-lg bg-orange-950/20 border border-orange-500/10 p-2 font-mono text-[9px] text-orange-300">
                      Recommendation: Autocreate work ticket for Compressor Bearing replacements on Turbine ST-12.
                    </div>
                  </div>
                ) : (
                  <div className="rounded-2xl border border-slate-800 bg-slate-900/40 p-4 text-xs leading-relaxed text-slate-600 dark:text-slate-400">
                    Press the diagnostic trigger to initiate multi-sensor vibration scans. Orbit AI models will sample FFT metrics from all active machinery axes.
                  </div>
                )}
              </div>

              <div className="pt-6">
                <button
                  disabled={!anomalyFound}
                  onClick={() => {
                    setScanLogs((prev) => [...prev, "SYS_ACTION: Autonomous work order #4829 dispatch successful. Maintenance node updated."]);
                  }}
                  className="w-full flex h-10 items-center justify-center rounded-full bg-orbit-bg-deep border border-orbit-border font-mono text-xs font-bold text-slate-700 dark:text-slate-300 hover:text-white disabled:opacity-50 transition-all duration-300"
                >
                  Dispatch Maintenance Node
                </button>
              </div>
            </div>
          </div>
        </div>

        {/* Detailed Solutions grids */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-8 pt-8">
          <div className="space-y-4">
            <h2 className="text-2xl font-bold font-mono text-slate-800 dark:text-slate-200">FFT Vibration Spectrograms</h2>
            <p className="text-sm leading-relaxed text-slate-600 dark:text-slate-400">
              Samples physical sound and vibration harmonics up to 10kHz. Fast Fourier Transform mathematical matrices isolate sub-millimeter motor misalignments or bearing pitting before physical defects damage rotors.
            </p>
          </div>
          <div className="space-y-4">
            <h2 className="text-2xl font-bold font-mono text-slate-800 dark:text-slate-200">Infrared Temperature Anomaly</h2>
            <p className="text-sm leading-relaxed text-slate-600 dark:text-slate-400">
              Integrates with infrared imaging cameras, monitoring turbine thermal boundaries. Multi-layer AI models spot thermal anomalies, differentiating standard motor workloads from cooling line fluid blockages.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
