import React, { useEffect, useState, useRef } from "react";
import { Link } from "react-router-dom";
import {
  Users,
  Target,
  Award,
  Heart,
  ArrowRight,
  Zap,
  Shield,
  Star,
  Lightbulb,
  TrendingUp,
  UserCheck,
  Sparkles,
} from "lucide-react";
import { Button } from "../components/ui/button";
import { Badge } from "../components/ui/badge";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "../components/ui/dialog";
import axios from "axios";

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

// Icon mapping for company values
const iconMap = {
  Target: Target,
  Users: Users,
  Award: Award,
  Heart: Heart,
  Zap: Zap,
  Shield: Shield,
  Star: Star,
  Lightbulb: Lightbulb,
  TrendingUp: TrendingUp,
  UserCheck: UserCheck,
  Sparkles: Sparkles,
};

// Default icons for common values
const getDefaultIcon = (title) => {
  const lowerTitle = title.toLowerCase();
  if (lowerTitle.includes("quality")) return Sparkles;
  if (lowerTitle.includes("customer") || lowerTitle.includes("focus"))
    return UserCheck;
  if (lowerTitle.includes("excellence") || lowerTitle.includes("excellent"))
    return TrendingUp;
  if (lowerTitle.includes("integrity") || lowerTitle.includes("honest"))
    return Shield;
  return Target;
};

const About = () => {
  const [team, setTeam] = useState([]);
  const [values, setValues] = useState([]);
  const [content, setContent] = useState({});
  const [loading, setLoading] = useState(true);
  const [valuesHeadingVisible, setValuesHeadingVisible] = useState(false);
  const [visibleCards, setVisibleCards] = useState([]);
  const [selectedValue, setSelectedValue] = useState(null);
  const [dialogOpen, setDialogOpen] = useState(false);
  const valuesHeadingRef = useRef(null);
  const valueCardsRefs = useRef([]);

  useEffect(() => {
    window.scrollTo(0, 0);
    fetchAboutData();
  }, []);

  useEffect(() => {
    // Observer for heading
    const headingObserver = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            setValuesHeadingVisible(true);
          }
        });
      },
      { threshold: 0.3 },
    );

    if (valuesHeadingRef.current) {
      headingObserver.observe(valuesHeadingRef.current);
    }

    // Observer for individual cards
    const cardsObserver = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            const index = parseInt(entry.target.dataset.index);
            setVisibleCards((prev) => [...new Set([...prev, index])]);
          }
        });
      },
      { threshold: 0.3 },
    );

    valueCardsRefs.current.forEach((ref) => {
      if (ref) cardsObserver.observe(ref);
    });

    return () => {
      if (valuesHeadingRef.current) {
        headingObserver.unobserve(valuesHeadingRef.current);
      }
      valueCardsRefs.current.forEach((ref) => {
        if (ref) cardsObserver.unobserve(ref);
      });
    };
  }, [values]);

  const fetchAboutData = async () => {
    try {
      const [teamRes, valuesRes, contentRes] = await Promise.all([
        axios.get(`${API}/about/team`),
        axios.get(`${API}/about/values`),
        axios.get(`${API}/about/content`),
      ]);

      setTeam(teamRes.data || []);
      setValues(valuesRes.data || []);

      // Convert content array to object keyed by section
      const contentObj = {};
      (contentRes.data || []).forEach((item) => {
        contentObj[item.section] = item;
      });
      setContent(contentObj);
    } catch (error) {
      console.error("Error fetching about data:", error);
      // Use fallback data if API fails
      setTeam([]);
      setValues([
        {
          icon: "Target",
          title: "Quality First",
          description:
            "We never compromise on the quality of our products and services.",
        },
        {
          icon: "Users",
          title: "Customer Focus",
          description:
            "Your satisfaction is our top priority. We listen and deliver.",
        },
        {
          icon: "Award",
          title: "Excellence",
          description: "We strive for excellence in everything we do.",
        },
        {
          icon: "Heart",
          title: "Integrity",
          description: "Honest, transparent, and ethical business practices.",
        },
      ]);
    } finally {
      setLoading(false);
    }
  };

  // Get icon component from string name
  const getIcon = (iconName, title) => {
    if (iconName && iconMap[iconName]) {
      return iconMap[iconName];
    }
    return getDefaultIcon(title);
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin w-8 h-8 border-2 border-primary border-t-transparent rounded-full" />
      </div>
    );
  }

  return (
    <div className="min-h-screen">
      {/* Hero */}
      <section className="py-16 md:py-24">
        <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">
                About PromptTech Solutions
              </Badge>
              <h1 className="text-4xl sm:text-5xl font-bold font-['Outfit'] leading-tight">
                {content.hero?.title || "Your Trusted"}
                <br />
                <span className="text-muted-foreground">
                  {content.hero?.subtitle || "Tech Partner"}
                </span>
              </h1>
              <p className="text-lg text-muted-foreground leading-relaxed">
                {content.hero?.content ||
                  "Founded in 2021, PromptTech Solutions has evolved from a small repair shop into a comprehensive tech solutions provider. We're here to guide you through any technology challenge—whether it's laptops, desktops, smartphones, or other devices. With expert service and personalized support, we deliver reliable solutions for all your tech needs."}
              </p>
              <div className="flex flex-wrap gap-4">
                <Link to="/products" data-testid="about-shop-now">
                  <Button size="lg" className="rounded-full gap-2 btn-press">
                    Shop Now
                    <ArrowRight className="h-5 w-5" />
                  </Button>
                </Link>
                <Link to="/contact" data-testid="about-contact-us">
                  <Button size="lg" variant="outline" className="rounded-full">
                    Contact Us
                  </Button>
                </Link>
              </div>
            </div>

            <div className="relative">
              <img
                src={
                  content.hero?.image_url
                    ? content.hero.image_url.startsWith('/uploads')
                      ? `${process.env.REACT_APP_BACKEND_URL}${content.hero.image_url}`
                      : content.hero.image_url
                    : `${process.env.REACT_APP_BACKEND_URL}/uploads/media/aa5bcc15-3b1e-4ed8-8708-1a3dceb9494d.jpg`
                }
                alt="Tech Repair Services"
                className="rounded-2xl shadow-2xl w-full h-auto max-h-[500px] object-cover"
                data-testid="about-hero-image"
              />
              {/* Stats Card */}
              <div className="absolute -bottom-6 -left-6 bg-card border border-border rounded-xl p-6 shadow-lg">
                <p className="text-3xl font-bold font-['Outfit']">5+</p>
                <p className="text-sm text-muted-foreground">
                  Years of Excellence
                </p>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Stats */}
      <section className="py-12 bg-muted/30 overflow-hidden">
        <div className="max-w-7xl mx-auto px-4 md:px-8">
          <div className="relative">
            <style>{`
              @keyframes scroll-left {
                0% { transform: translateX(0); }
                100% { transform: translateX(-100%); }
              }
              .animate-scroll {
                animation: scroll-left 15s linear infinite;
              }
            `}</style>
            <div className="flex">
              <div className="flex animate-scroll">
                {/* First set */}
                {(
                  content.stats?.data?.stats || [
                    { value: "1K+", label: "Happy Customers" },
                    { value: "500+", label: "Products Sold" },
                    { value: "1,500+", label: "Repairs Done" },
                    { value: "90%", label: "Satisfaction Rate" },
                  ]
                ).map((stat, idx) => (
                  <div
                    key={idx}
                    className="text-center flex-shrink-0 px-8 md:px-16 min-w-[200px]"
                    data-testid={`stat-${idx}`}
                  >
                    <p className="text-4xl md:text-5xl font-bold font-['Outfit'] mb-2">
                      {stat.value}
                    </p>
                    <p className="text-muted-foreground whitespace-nowrap">
                      {stat.label}
                    </p>
                  </div>
                ))}
                {/* Duplicate set for seamless loop */}
                {(
                  content.stats?.data?.stats || [
                    { value: "1K+", label: "Happy Customers" },
                    { value: "500+", label: "Products Sold" },
                    { value: "1,500+", label: "Repairs Done" },
                    { value: "90%", label: "Satisfaction Rate" },
                  ]
                ).map((stat, idx) => (
                  <div
                    key={`dup-${idx}`}
                    className="text-center flex-shrink-0 px-8 md:px-16 min-w-[200px]"
                  >
                    <p className="text-4xl md:text-5xl font-bold font-['Outfit'] mb-2">
                      {stat.value}
                    </p>
                    <p className="text-muted-foreground whitespace-nowrap">
                      {stat.label}
                    </p>
                  </div>
                ))}
              </div>
              {/* Duplicate entire animation block for truly seamless loop */}
              <div className="flex animate-scroll" aria-hidden="true">
                {(
                  content.stats?.data?.stats || [
                    { value: "1K+", label: "Happy Customers" },
                    { value: "500+", label: "Products Sold" },
                    { value: "1,500+", label: "Repairs Done" },
                    { value: "90%", label: "Satisfaction Rate" },
                  ]
                ).map((stat, idx) => (
                  <div
                    key={`set2-${idx}`}
                    className="text-center flex-shrink-0 px-8 md:px-16 min-w-[200px]"
                  >
                    <p className="text-4xl md:text-5xl font-bold font-['Outfit'] mb-2">
                      {stat.value}
                    </p>
                    <p className="text-muted-foreground whitespace-nowrap">
                      {stat.label}
                    </p>
                  </div>
                ))}
                {(
                  content.stats?.data?.stats || [
                    { value: "1K+", label: "Happy Customers" },
                    { value: "500+", label: "Products Sold" },
                    { value: "1,500+", label: "Repairs Done" },
                    { value: "90%", label: "Satisfaction Rate" },
                  ]
                ).map((stat, idx) => (
                  <div
                    key={`set2-dup-${idx}`}
                    className="text-center flex-shrink-0 px-8 md:px-16 min-w-[200px]"
                  >
                    <p className="text-4xl md:text-5xl font-bold font-['Outfit'] mb-2">
                      {stat.value}
                    </p>
                    <p className="text-muted-foreground whitespace-nowrap">
                      {stat.label}
                    </p>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Our Story */}
      <section className="py-16 md:py-24">
        <div className="max-w-4xl 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">
              {content.story?.title || "Our Story"}
            </h2>
          </div>
          <div className="prose prose-lg dark:prose-invert max-w-none">
            {content.story?.content ? (
              <div
                className="text-muted-foreground leading-relaxed"
                dangerouslySetInnerHTML={{ __html: content.story.content }}
              />
            ) : (
              <>
                <p className="text-muted-foreground leading-relaxed mb-6">
                  PromptTech Solutions started with a simple vision: to make
                  quality tech accessible and provide expert support that
                  customers can trust. What began as a small phone repair shop
                  has evolved into a full-service tech destination.
                </p>
                <p className="text-muted-foreground leading-relaxed mb-6">
                  Our team of certified technicians brings decades of combined
                  experience in electronics repair, from smartphones to laptops
                  and everything in between. We've helped thousands of customers
                  bring their devices back to life.
                </p>
                <p className="text-muted-foreground leading-relaxed">
                  Today, we're proud to offer a curated selection of premium
                  electronics alongside our repair services. Every product we
                  sell meets our high standards for quality, and every repair we
                  do is backed by our satisfaction guarantee.
                </p>
              </>
            )}
          </div>
        </div>
      </section>

      {/* Values */}
      <section className="py-16 md:py-24 bg-muted/30">
        <div className="max-w-7xl mx-auto px-4 md:px-8">
          <div
            ref={valuesHeadingRef}
            className={`text-center mb-12 transition-all duration-700 ${valuesHeadingVisible ? "opacity-100 translate-y-0" : "opacity-0 translate-y-10"}`}
          >
            <h2 className="text-3xl md:text-4xl font-bold font-['Outfit'] mb-4">
              Our Values
            </h2>
            <p className="text-muted-foreground max-w-2xl mx-auto">
              The principles that guide everything we do
            </p>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            <style>{`
              @keyframes slide-up-fade {
                from {
                  opacity: 0;
                  transform: translateY(60px);
                }
                to {
                  opacity: 1;
                  transform: translateY(0);
                }
              }
              .value-card {
                opacity: 0;
                transform: translateY(60px);
                cursor: pointer;
                transition: all 0.3s ease;
              }
              .value-card.visible {
                animation: slide-up-fade 0.8s ease-out forwards;
              }
              .value-card:hover {
                transform: translateY(-8px) scale(1.02);
                box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
              }
              .value-card:hover .card-bg {
                opacity: 1;
              }
              .card-bg {
                position: absolute;
                inset: 0;
                border-radius: 1rem;
                opacity: 0;
                transition: opacity 0.3s ease;
                pointer-events: none;
              }
              .quality-bg { background: linear-gradient(135deg, rgba(99, 102, 241, 0.1), rgba(168, 85, 247, 0.1)); }
              .customer-bg { background: linear-gradient(135deg, rgba(59, 130, 246, 0.1), rgba(14, 165, 233, 0.1)); }
              .excellence-bg { background: linear-gradient(135deg, rgba(239, 68, 68, 0.1), rgba(249, 115, 22, 0.1)); }
              .integrity-bg { background: linear-gradient(135deg, rgba(34, 197, 94, 0.1), rgba(16, 185, 129, 0.1)); }
            `}</style>
            {values.length > 0
              ? values.map((value, idx) => {
                  const Icon = getIcon(value.icon, value.title);
                  const bgClass = [
                    "quality-bg",
                    "customer-bg",
                    "excellence-bg",
                    "integrity-bg",
                  ][idx % 4];
                  return (
                    <div
                      key={value.id || idx}
                      ref={(el) => (valueCardsRefs.current[idx] = el)}
                      data-index={idx}
                      className={`value-card relative p-6 rounded-2xl bg-card border border-border text-center overflow-hidden ${visibleCards.includes(idx) ? "visible" : ""}`}
                      onClick={() => {
                        setSelectedValue(value);
                        setDialogOpen(true);
                      }}
                      data-testid={`value-${idx}`}
                    >
                      <div className={`card-bg ${bgClass}`} />
                      <div className="relative z-10">
                        <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']">
                          {value.title}
                        </h3>
                        <p className="text-sm text-muted-foreground">
                          {value.description}
                        </p>
                      </div>
                    </div>
                  );
                })
              : // Fallback values
                [
                  {
                    icon: Sparkles,
                    title: "Quality First",
                    desc: "We never compromise on the quality of our products and services.",
                  },
                  {
                    icon: UserCheck,
                    title: "Customer Focus",
                    desc: "Your satisfaction is our top priority. We listen and deliver.",
                  },
                  {
                    icon: TrendingUp,
                    title: "Excellence",
                    desc: "We strive for excellence in everything we do.",
                  },
                  {
                    icon: Shield,
                    title: "Integrity",
                    desc: "Honest, transparent, and ethical business practices.",
                  },
                ].map((value, idx) => {
                  const Icon = value.icon;
                  const bgClass = [
                    "quality-bg",
                    "customer-bg",
                    "excellence-bg",
                    "integrity-bg",
                  ][idx];
                  return (
                    <div
                      key={idx}
                      ref={(el) => (valueCardsRefs.current[idx] = el)}
                      data-index={idx}
                      className={`value-card relative p-6 rounded-2xl bg-card border border-border text-center overflow-hidden ${visibleCards.includes(idx) ? "visible" : ""}`}
                      onClick={() => {
                        setSelectedValue({
                          title: value.title,
                          description: value.desc,
                          icon: value.icon,
                        });
                        setDialogOpen(true);
                      }}
                      data-testid={`value-${idx}`}
                    >
                      <div className={`card-bg ${bgClass}`} />
                      <div className="relative z-10">
                        <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']">
                          {value.title}
                        </h3>
                        <p className="text-sm text-muted-foreground">
                          {value.desc}
                        </p>
                      </div>
                    </div>
                  );
                })}
          </div>
        </div>

        {/* Value Detail Dialog */}
        <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
          <DialogContent className="sm:max-w-[600px]">
            <DialogHeader>
              {selectedValue && (
                <>
                  <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-primary/10 flex items-center justify-center">
                    {React.createElement(
                      getIcon(selectedValue.icon, selectedValue.title),
                      { className: "h-8 w-8 text-primary" },
                    )}
                  </div>
                  <DialogTitle className="text-2xl font-bold text-center font-['Outfit']">
                    {selectedValue.title}
                  </DialogTitle>
                  <DialogDescription className="text-center text-base mt-4">
                    {selectedValue.description}
                  </DialogDescription>
                  <div className="mt-6 p-6 rounded-lg bg-muted/50">
                    <p className="text-sm text-muted-foreground leading-relaxed">
                      At PromptTech Solutions,{" "}
                      <strong>{selectedValue.title.toLowerCase()}</strong> is at
                      the core of everything we do. We believe that{" "}
                      {selectedValue.description.toLowerCase()} This commitment
                      drives us to deliver exceptional service and build lasting
                      relationships with our customers.
                    </p>
                  </div>
                </>
              )}
            </DialogHeader>
          </DialogContent>
        </Dialog>
      </section>

      {/* Team */}
      {team.length > 0 && (
        <section className="py-16 md:py-24">
          <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">
                Meet Our Team
              </h2>
              <p className="text-muted-foreground max-w-2xl mx-auto">
                The people behind PromptTech Solutions' success
              </p>
            </div>

            <div
              className={`grid grid-cols-2 ${team.length <= 3 ? "md:grid-cols-3" : "md:grid-cols-4"} gap-6`}
            >
              {team.map((member, idx) => (
                <div
                  key={member.id || idx}
                  className="group text-center"
                  data-testid={`team-member-${idx}`}
                >
                  <div className="relative mb-4 overflow-hidden rounded-2xl aspect-square">
                    <img
                      src={
                        member.image_url
                          ? member.image_url.startsWith('/uploads')
                            ? `${process.env.REACT_APP_BACKEND_URL}${member.image_url}`
                            : member.image_url
                          : "https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=400"
                      }
                      alt={member.name}
                      className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
                    />
                  </div>
                  <h3 className="font-semibold font-['Outfit']">
                    {member.name}
                  </h3>
                  <p className="text-sm text-muted-foreground">{member.role}</p>
                </div>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* CTA */}
      <section className="py-16 md:py-24 bg-primary text-primary-foreground">
        <div className="max-w-4xl mx-auto px-4 md:px-8 text-center">
          <h2 className="text-3xl md:text-4xl font-bold font-['Outfit'] mb-4">
            Ready to Get Started?
          </h2>
          <p className="text-primary-foreground/80 mb-8 max-w-2xl mx-auto">
            Whether you need a new device or want to repair your current one,
            we're here to help.
          </p>
          <div className="flex flex-wrap justify-center gap-4">
            <Link to="/products" data-testid="cta-browse-products">
              <Button
                size="lg"
                variant="secondary"
                className="rounded-full px-8 btn-press"
              >
                Browse Products
              </Button>
            </Link>
            <Link to="/services" data-testid="cta-our-services">
              <Button
                size="lg"
                variant="outline"
                className="rounded-full px-8 border-primary-foreground/30 text-primary-foreground hover:bg-primary-foreground/10"
              >
                Our Services
              </Button>
            </Link>
          </div>
        </div>
      </section>
    </div>
  );
};

export default About;
