"use client";

import React, { useRef, useEffect, useState } from "react";
import Link from "next/link";
import { 
  Terminal, 
  Code2, 
  Smartphone, 
  TrendingUp, 
  Layers, 
  Cpu, 
  ArrowRight, 
  Boxes,
  CheckCircle2,
  Sparkles
} from "lucide-react";
import { useAppStore } from "@/lib/store";

interface SquaresTerminalProps {
  direction?: "diagonal" | "up" | "right" | "down" | "left";
  speed?: number;
  borderColor?: string;
  squareSize?: number;
  hoverFillColor?: string;
  className?: string;
}

const CORE_SERVICES = [
  {
    id: "web-dev",
    name: "Web Development",
    tagline: "Next.js 14, React, Supabase & Node.js",
    href: "/packages",
    icon: Code2,
    badge: "Sub-35ms Speed",
  },
  {
    id: "mobile-app",
    name: "Mobile App Development",
    tagline: "Flutter & React Native (iOS + Android)",
    href: "/packages",
    icon: Smartphone,
    badge: "Cross-Platform",
  },
  {
    id: "seo-marketing",
    name: "SEO & Digital Marketing",
    tagline: "Technical SEO, Core Web Vitals & Growth",
    href: "/packages",
    icon: TrendingUp,
    badge: "Rank #1 Focus",
  },
  {
    id: "ui-ux",
    name: "UI/UX Design Systems",
    tagline: "Interactive Wireframes, Figma & Prototypes",
    href: "/services",
    icon: Layers,
    badge: "Pixel-Perfect",
  },
  {
    id: "erp-saas",
    name: "Custom ERP & SaaS Solutions",
    tagline: "Enterprise Systems, POS & FBR Fiscal APIs",
    href: "/products",
    icon: Cpu,
    badge: "Tier-1 Ready",
  },
];

export function SquaresTerminal({
  direction = "diagonal",
  speed = 0.5,
  borderColor = "rgba(2, 77, 55, 0.2)",
  squareSize = 36,
  hoverFillColor = "rgba(2, 77, 55, 0.6)",
  className = "",
}: SquaresTerminalProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const [hoveredSquare, setHoveredSquare] = useState<{ x: number; y: number } | null>(null);
  const [activeServiceIdx, setActiveServiceIdx] = useState(0);

  // Auto-cycle highlighted service every 3.2s
  useEffect(() => {
    const interval = setInterval(() => {
      setActiveServiceIdx((prev) => (prev + 1) % CORE_SERVICES.length);
    }, 3200);
    return () => clearInterval(interval);
  }, []);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    let animationFrameId: number;
    let gridOffset = { x: 0, y: 0 };

    interface FlickeringSquare {
      col: number;
      row: number;
      opacity: number;
      speed: number;
      color: string;
    }
    const flickeringSquares: FlickeringSquare[] = [];

    const resizeCanvas = () => {
      if (containerRef.current && canvas) {
        const rect = containerRef.current.getBoundingClientRect();
        canvas.width = rect.width * window.devicePixelRatio;
        canvas.height = rect.height * window.devicePixelRatio;
        ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
      }
    };

    resizeCanvas();
    window.addEventListener("resize", resizeCanvas);

    const colors = [
      "rgba(2, 77, 55, 0.45)",
      "rgba(3, 101, 73, 0.6)",
      "rgba(5, 150, 105, 0.75)",
      "rgba(16, 185, 129, 0.85)",
    ];

    const render = () => {
      if (!canvas || !containerRef.current) return;
      const rect = containerRef.current.getBoundingClientRect();
      const width = rect.width;
      const height = rect.height;

      ctx.clearRect(0, 0, width, height);

      if (direction === "right") gridOffset.x += speed;
      else if (direction === "left") gridOffset.x -= speed;
      else if (direction === "up") gridOffset.y -= speed;
      else if (direction === "down") gridOffset.y += speed;
      else if (direction === "diagonal") {
        gridOffset.x += speed * 0.5;
        gridOffset.y += speed * 0.5;
      }

      gridOffset.x %= squareSize;
      gridOffset.y %= squareSize;

      const numCols = Math.ceil(width / squareSize) + 2;
      const numRows = Math.ceil(height / squareSize) + 2;

      if (Math.random() < 0.25 && flickeringSquares.length < 28) {
        flickeringSquares.push({
          col: Math.floor(Math.random() * numCols),
          row: Math.floor(Math.random() * numRows),
          opacity: 0.1,
          speed: Math.random() * 0.04 + 0.015,
          color: colors[Math.floor(Math.random() * colors.length)],
        });
      }

      for (let i = flickeringSquares.length - 1; i >= 0; i--) {
        const sq = flickeringSquares[i];
        sq.opacity += sq.speed;
        if (sq.opacity > 0.9) {
          sq.speed = -sq.speed;
        } else if (sq.opacity <= 0) {
          flickeringSquares.splice(i, 1);
          continue;
        }

        const startX = sq.col * squareSize + (gridOffset.x % squareSize) - squareSize;
        const startY = sq.row * squareSize + (gridOffset.y % squareSize) - squareSize;

        ctx.fillStyle = sq.color;
        ctx.globalAlpha = Math.max(0, Math.min(1, sq.opacity));
        ctx.fillRect(startX + 1, startY + 1, squareSize - 2, squareSize - 2);
        ctx.globalAlpha = 1.0;
      }

      ctx.strokeStyle = borderColor;
      ctx.lineWidth = 1;

      for (let x = gridOffset.x % squareSize; x < width + squareSize; x += squareSize) {
        ctx.beginPath();
        ctx.moveTo(x - squareSize, 0);
        ctx.lineTo(x - squareSize, height);
        ctx.stroke();
      }

      for (let y = gridOffset.y % squareSize; y < height + squareSize; y += squareSize) {
        ctx.beginPath();
        ctx.moveTo(0, y - squareSize);
        ctx.lineTo(width, y - squareSize);
        ctx.stroke();
      }

      if (hoveredSquare) {
        const hx = Math.floor((hoveredSquare.x - (gridOffset.x % squareSize)) / squareSize) * squareSize + (gridOffset.x % squareSize);
        const hy = Math.floor((hoveredSquare.y - (gridOffset.y % squareSize)) / squareSize) * squareSize + (gridOffset.y % squareSize);

        ctx.fillStyle = hoverFillColor;
        ctx.shadowColor = "#024d37";
        ctx.shadowBlur = 12;
        ctx.fillRect(hx + 1, hy + 1, squareSize - 2, squareSize - 2);
        ctx.shadowBlur = 0;
      }

      animationFrameId = requestAnimationFrame(render);
    };

    render();

    return () => {
      cancelAnimationFrame(animationFrameId);
      window.removeEventListener("resize", resizeCanvas);
    };
  }, [direction, speed, borderColor, squareSize, hoverFillColor, hoveredSquare]);

  const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
    if (!containerRef.current) return;
    const rect = containerRef.current.getBoundingClientRect();
    setHoveredSquare({
      x: e.clientX - rect.left,
      y: e.clientY - rect.top,
    });
  };

  const handleMouseLeave = () => {
    setHoveredSquare(null);
  };

  return (
    <div
      ref={containerRef}
      onMouseMove={handleMouseMove}
      onMouseLeave={handleMouseLeave}
      className={`relative min-h-[480px] lg:min-h-[580px] w-full overflow-hidden bg-card/60 flex flex-col justify-between p-5 sm:p-8 font-mono text-xs ${className}`}
    >
      {/* Background Interactive Squares Canvas */}
      <canvas
        ref={canvasRef}
        className="absolute inset-0 h-full w-full pointer-events-none"
      />

      {/* Top Terminal Header */}
      <div className="relative z-10 flex items-center justify-between border-b border-border/80 bg-background/85 backdrop-blur-md px-4 py-3 rounded-xl shadow-xs">
        <div className="flex items-center gap-2">
          <Terminal className="h-4 w-4 text-[#024d37]" />
          <span className="font-bold text-foreground">// AETHERSOFT // CORE SERVICES</span>
        </div>
        <div className="flex items-center gap-2 font-semibold text-[11px]">
          <span className="h-2 w-2 rounded-full bg-[#024d37] animate-pulse" />
          <span className="text-foreground">5 ACTIVE CAPABILITIES</span>
        </div>
      </div>

      {/* Middle Interactive Floating Services List */}
      <div className="relative z-10 my-auto space-y-2 py-4 pointer-events-auto">
        <div className="rounded-2xl border border-border bg-background/85 backdrop-blur-md p-4 sm:p-5 space-y-2.5 shadow-lg hover:border-[#024d37]/60 transition-all">
          <div className="flex items-center justify-between border-b border-border/70 pb-2.5">
            <div className="flex items-center gap-2 text-foreground font-bold">
              <Boxes className="h-4 w-4 text-[#024d37]" />
              <span>SOFTWARE & DIGITAL SOLUTIONS</span>
            </div>
            <span className="rounded-full bg-[#024d37]/15 border border-[#024d37]/40 px-2 py-0.5 text-[10px] text-[#024d37] font-bold">
              SPRINT 01 READY
            </span>
          </div>

          <div className="space-y-1.5 font-sans">
            {CORE_SERVICES.map((service, idx) => {
              const Icon = service.icon;
              const isSelected = activeServiceIdx === idx;

              return (
                <Link
                  key={service.id}
                  href={service.href}
                  onMouseEnter={() => setActiveServiceIdx(idx)}
                  className={`flex items-center justify-between rounded-xl px-3.5 py-2.5 transition-all cursor-pointer ${
                    isSelected
                      ? "bg-[#024d37] text-white font-medium shadow-md shadow-[#024d37]/25 translate-x-1"
                      : "bg-muted/50 text-muted-foreground hover:bg-muted hover:text-foreground"
                  }`}
                >
                  <div className="flex items-center gap-3">
                    <div className={`p-1.5 rounded-lg ${isSelected ? "bg-white/20 text-white" : "bg-card text-[#024d37] border border-border"}`}>
                      <Icon className="h-4 w-4" />
                    </div>
                    <div>
                      <div className={`text-xs font-bold ${isSelected ? "text-white" : "text-foreground"}`}>
                        {service.name}
                      </div>
                      <div className={`text-[10px] font-mono line-clamp-1 ${isSelected ? "text-emerald-100" : "text-muted-foreground"}`}>
                        {service.tagline}
                      </div>
                    </div>
                  </div>

                  <div className="flex items-center gap-2 font-mono text-[10px]">
                    <span className={`hidden sm:inline-block rounded px-1.5 py-0.5 ${isSelected ? "bg-white/20 text-white" : "bg-card border border-border text-foreground"}`}>
                      {service.badge}
                    </span>
                    <ArrowRight className={`h-3.5 w-3.5 transition-transform ${isSelected ? "translate-x-0.5 text-white" : "text-muted-foreground"}`} />
                  </div>
                </Link>
              );
            })}
          </div>
        </div>
      </div>

      {/* Bottom Terminal Live Status Bar */}
      <div className="relative z-10 flex items-center justify-between border-t border-border/80 bg-background/85 backdrop-blur-md px-4 py-2.5 rounded-xl text-muted-foreground text-[11px] shadow-xs">
        <div className="flex items-center gap-2">
          <span className="h-2 w-2 rounded-full bg-[#024d37] animate-ping" />
          <span>SCOPING STATUS: <strong className="text-foreground">ACCEPTING NEW PROJECTS</strong></span>
        </div>
        <Link href="/packages" className="text-[#024d37] font-semibold hover:underline flex items-center gap-1">
          Explore Packages →
        </Link>
      </div>
    </div>
  );
}
