import React, { useState, useEffect } from "react";
import axios from "axios";
import {
  Wrench,
  HardDrive,
  Shield,
  Cpu,
  Settings,
  Smartphone,
} from "lucide-react";
import { Button } from "../components/ui/button";
import { Badge } from "../components/ui/badge";
import ServiceCard from "../components/cards/ServiceCard";
import { getCached, setCache } from "../utils/apiCache";

const API = `${process.env.REACT_APP_BACKEND_URL}/api`;

const Services = () => {
  const [services, setServices] = useState([]);
  const [loading, setLoading] = useState(true);
  const [activeCategory, setActiveCategory] = useState("all");

  const categories = [
    { value: "all", label: "All Services", icon: Settings },
    { value: "repair", label: "Repairs", icon: Wrench },
    { value: "data", label: "Data Recovery", icon: HardDrive },
    { value: "software", label: "Software", icon: Shield },
    { value: "upgrade", label: "Upgrades", icon: Cpu },
    { value: "setup", label: "Setup", icon: Smartphone },
  ];

  useEffect(() => {
    // Scroll to top when component mounts
    window.scrollTo(0, 0);
  }, []);

  useEffect(() => {
    fetchServices();
  }, [activeCategory]);

  // Auto-refresh every 5 seconds for real-time updates
  useEffect(() => {
    const interval = setInterval(() => {
      fetchServices(true);
    }, 5000);

    return () => clearInterval(interval);
  }, [activeCategory]);

  // Refresh when user returns to the tab
  useEffect(() => {
    const handleVisibilityChange = () => {
      if (!document.hidden) {
        fetchServices();
      }
    };

    document.addEventListener("visibilitychange", handleVisibilityChange);
    return () =>
      document.removeEventListener("visibilitychange", handleVisibilityChange);
  }, [activeCategory]);

  const fetchServices = async (silent = false) => {
    if (!silent) setLoading(true);
    try {
      const params =
        activeCategory !== "all" ? `?category=${activeCategory}` : "";

      const response = await axios.get(`${API}/services${params}`);
      setServices(response.data);
    } catch (error) {
      console.error("Failed to fetch services:", error);
    } finally {
      setLoading(false);
    }
  };

  const stats = [
    { value: "98%", label: "Success Rate" },
    { value: "24h", label: "Avg Turnaround" },
    { value: "5 Star", label: "Customer Rating" },
  ];

  return (
    <div className="min-h-screen">
      {/* Hero Section */}
      <section className="relative py-16 md:py-24 bg-muted/30">
        <div className="max-w-7xl mx-auto px-4 md:px-8">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 items-center">
            <div className="space-y-6">
              <Badge variant="secondary" className="rounded-full px-4 py-1">
                Professional Tech Services
              </Badge>
              <h1 className="text-4xl sm:text-5xl font-bold font-['Outfit'] leading-tight">
                Expert Repair &
                <br />
                <span className="text-muted-foreground">Tech Solutions</span>
              </h1>
              <p className="text-lg text-muted-foreground max-w-lg">
                From screen repairs to advanced data recovery, we provide
                reliable and professional solutions for all your technology
                needs. Our services cover both hardware and software, ensuring
                your devices run smoothly, securely, and efficiently.
              </p>

              {/* Stats */}
              <div className="grid grid-cols-3 gap-4 pt-4">
                {stats.map((stat, idx) => (
                  <div
                    key={idx}
                    className="text-center p-4 rounded-xl bg-card border border-border"
                  >
                    <p className="text-2xl font-bold font-['Outfit']">
                      {stat.value}
                    </p>
                    <p className="text-xs text-muted-foreground">
                      {stat.label}
                    </p>
                  </div>
                ))}
              </div>
            </div>

            <div className="relative">
              <img
                src="https://images.unsplash.com/photo-1676630444903-163fe485c5d1?w=800"
                alt="Tech Repair Service"
                className="rounded-2xl shadow-2xl"
                data-testid="services-hero-image"
              />
            </div>
          </div>
        </div>
      </section>

      {/* Specializations Section */}
      <section className="py-16 bg-card border-b border-border">
        <div className="max-w-7xl mx-auto px-4 md:px-8">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
            <div>
              <h2 className="text-2xl md:text-3xl font-bold font-['Outfit'] mb-6">
                We Specialize In
              </h2>
              <ul className="space-y-3">
                {[
                  "Computer and laptop repairs",
                  "Screen replacements and hardware troubleshooting",
                  "Software installation and system configuration",
                  "Windows 10 and Windows 11 repair, recovery, and optimization",
                  "Operating system reinstallation and OS-level repairs",
                ].map((item, idx) => (
                  <li key={idx} className="flex items-start gap-3">
                    <div className="w-2 h-2 rounded-full bg-primary mt-2 flex-shrink-0" />
                    <span className="text-muted-foreground">{item}</span>
                  </li>
                ))}
              </ul>
            </div>
            <div>
              <h2 className="text-2xl md:text-3xl font-bold font-['Outfit'] mb-6 lg:invisible">
                &nbsp;
              </h2>
              <ul className="space-y-3">
                {[
                  "Microsoft Office installation, activation, and setup",
                  "Adobe software installation and configuration",
                  "QuickBooks POS 2019 installation, setup, and troubleshooting",
                  "Server management and system synchronization across multiple devices",
                  "Data backup, recovery, and system cleanup",
                ].map((item, idx) => (
                  <li key={idx} className="flex items-start gap-3">
                    <div className="w-2 h-2 rounded-full bg-primary mt-2 flex-shrink-0" />
                    <span className="text-muted-foreground">{item}</span>
                  </li>
                ))}
              </ul>
            </div>
          </div>
          <p className="text-center text-muted-foreground mt-8 max-w-3xl mx-auto">
            Our certified technicians provide professional solutions for all
            your tech needs—whether it's a single device repair or managing
            systems across your entire business.
          </p>
        </div>
      </section>

      {/* Categories */}
      <section className="py-8 border-b border-border sticky top-16 bg-background/95 backdrop-blur-sm z-40">
        <div className="max-w-7xl mx-auto px-4 md:px-8">
          <div className="flex gap-2 overflow-x-auto pb-2 scrollbar-hide">
            {categories.map((cat) => {
              const Icon = cat.icon;
              return (
                <Button
                  key={cat.value}
                  variant={activeCategory === cat.value ? "default" : "outline"}
                  className="rounded-full gap-2 flex-shrink-0"
                  onClick={() => setActiveCategory(cat.value)}
                  data-testid={`service-category-${cat.value}`}
                >
                  <Icon className="h-4 w-4" />
                  {cat.label}
                </Button>
              );
            })}
          </div>
        </div>
      </section>

      {/* Services Grid */}
      <section className="py-12 md:py-16">
        <div className="max-w-7xl mx-auto px-4 md:px-8">
          <div className="mb-8">
            <h2 className="text-2xl md:text-3xl font-bold font-['Outfit'] mb-2">
              {categories.find((c) => c.value === activeCategory)?.label ||
                "All Services"}
            </h2>
            <p className="text-muted-foreground">
              Professional solutions for all your tech needs
            </p>
          </div>

          {loading ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {[...Array(6)].map((_, i) => (
                <div
                  key={i}
                  className="rounded-xl border border-border bg-card p-6 animate-pulse"
                >
                  <div className="aspect-video bg-muted rounded-lg mb-4" />
                  <div className="h-5 bg-muted rounded w-2/3 mb-2" />
                  <div className="h-4 bg-muted rounded w-full mb-4" />
                  <div className="h-8 bg-muted rounded w-1/3" />
                </div>
              ))}
            </div>
          ) : services.length === 0 ? (
            <div className="text-center py-16">
              <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-muted flex items-center justify-center">
                <Wrench className="h-8 w-8 text-muted-foreground" />
              </div>
              <h3 className="text-lg font-semibold mb-2 font-['Outfit']">
                No services found
              </h3>
              <p className="text-muted-foreground mb-4">
                Try selecting a different category
              </p>
              <Button
                variant="outline"
                onClick={() => setActiveCategory("all")}
                className="rounded-full"
              >
                View All Services
              </Button>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {services.map((service) => (
                <ServiceCard key={service.id} service={service} />
              ))}
            </div>
          )}
        </div>
      </section>

      {/* Why Choose Us */}
      <section className="py-16 md:py-24 bg-muted/30">
        <div className="max-w-7xl mx-auto px-4 md:px-8">
          <div className="text-center mb-12">
            <h2 className="text-3xl md:text-4xl font-bold font-['Outfit'] mb-4">
              Why Choose Us?
            </h2>
            <p className="text-muted-foreground max-w-2xl mx-auto">
              We're committed to providing the best service experience
            </p>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
            {[
              {
                icon: Shield,
                title: "Certified Technicians",
                desc: "All our technicians are professionally certified and trained to handle any device.",
              },
              {
                icon: Wrench,
                title: "Genuine Parts",
                desc: "We use only genuine manufacturer parts to ensure quality and longevity.",
              },
              {
                icon: HardDrive,
                title: "Data Safety",
                desc: "Your data privacy is our priority. We follow strict security protocols.",
              },
            ].map((item, idx) => {
              const Icon = item.icon;
              return (
                <div
                  key={idx}
                  className="text-center p-8 rounded-2xl bg-card border border-border hover-lift"
                  data-testid={`why-choose-${idx}`}
                >
                  <div className="w-14 h-14 mx-auto mb-4 rounded-full bg-primary/10 flex items-center justify-center">
                    <Icon className="h-7 w-7 text-primary" />
                  </div>
                  <h3 className="text-lg font-semibold mb-2 font-['Outfit']">
                    {item.title}
                  </h3>
                  <p className="text-sm text-muted-foreground">{item.desc}</p>
                </div>
              );
            })}
          </div>
        </div>
      </section>
    </div>
  );
};

export default Services;
