'use client';
import Autoplay from 'embla-carousel-autoplay';
import { AnimatePresence, motion } from 'framer-motion';
import { BookOpen, Globe, Heart, Target, Trophy, Users } from 'lucide-react';
import Image from 'next/image';
import Link from 'next/link';
import React, { useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Skeleton } from '@/components/ui/skeleton';
import ClientsCarousel from '@/components/web/home/ClientsCarousel';
import ProjectImageSlider from '@/components/web/home/ProjectImageSlider';
import WebLayout from '@/components/web/layout/web-layout';
import type { Photo, Team } from '@/db/schema';
import { useAboutStore } from '@/stores/useAboutStore';
import { useTeamsStore } from '@/stores/useTeamsStore';

const About = () => {
  const [selectedMember, setSelectedMember] = useState<Team | null>(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  // const [branches, setBranches] = useState<Branch[]>([]);
  // const [loadingBranch, setLoadingBranch] = useState(true);
  const [galleries, setGalleries] = useState<Photo[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [bgImage, setBgImage] = useState<string>('');

  // Animation variants
  const fadeIn = {
    hidden: { opacity: 0, y: 20 },
    visible: {
      opacity: 1,
      y: 0,
      transition: { duration: 0.6 },
    },
  };

  const staggerContainer = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: {
        staggerChildren: 0.2,
      },
    },
  };

  const dialogVariants = {
    hidden: {
      opacity: 0,
      y: 20,
      scale: 0.95,
    },
    visible: {
      opacity: 1,
      y: 0,
      scale: 1,
      transition: {
        type: 'spring',
        damping: 25,
        stiffness: 300,
      },
    },
    exit: {
      opacity: 0,
      y: 20,
      transition: { duration: 0.2 },
    },
  };

  const overlayVariants = {
    hidden: { opacity: 0 },
    visible: { opacity: 1 },
  };

  // Store hooks
  const { about, loadingAbout, fetchAbout } = useAboutStore();
  const { teams, loadingTeams, fetchTeams } = useTeamsStore();
  // const { projects, loadingProjects, fetchProjects } = useProjectsStore();

  const plugin = useRef(Autoplay({ delay: 6300, stopOnInteraction: false }));
  const fallbackImage = '/images/logo.png';

  const fetchGalleries = async () => {
    try {
      const response = await fetch('/api/photos/history');
      const data = await response.json();
      setGalleries(data);
    } catch (error) {
      toast.error('Failed to load gallery images');
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchGalleries();

    if (teams?.length === 0) {
      fetchTeams().catch(() => toast.error('Error loading Teams'));
    }
  }, [about, teams?.length]);

  useEffect(() => {
    let intervalId: NodeJS.Timeout;

    if (Array.isArray(galleries) && galleries.length > 0) {
      const validImages = galleries
        .map((h) => h?.url?.trim())
        .filter((img) => img);

      if (validImages.length > 1) {
        setBgImage(validImages[Math.floor(Math.random() * validImages.length)]);
        intervalId = setInterval(() => {
          const randomImage =
            validImages[Math.floor(Math.random() * validImages.length)];
          setBgImage(randomImage);
        }, 5000);
      } else {
        setBgImage(validImages[0] || fallbackImage);
      }
    } else {
      setBgImage(fallbackImage);
    }

    return () => {
      if (intervalId) clearInterval(intervalId);
    };
  }, [galleries]);

  const splitParagraphs = (text: string) => {
    return (
      text?.split('\r\n').filter((paragraph) => paragraph.trim() !== '') || []
    );
  };

  return (
    <WebLayout>
      <div className="bg-white">
        {/* Hero Section */}
        <section
          className="w-full bg-center bg-cover py-20 text-white"
          style={{
            backgroundImage: `linear-gradient(to right, rgba(0, 70, 173, 0.85), rgba(0, 160, 233, 0.85)), url(${bgImage})`,
          }}
        >
          <div className="container mx-auto px-4">
            <motion.div
              animate="visible"
              className="mt-12 max-w-3xl"
              initial="hidden"
              variants={fadeIn}
            >
              <h1 className="mb-6 font-bold text-4xl md:text-5xl">About Us</h1>
              {loadingAbout ? (
                new Array(3)
                  .fill(0)
                  .map((_, i) => (
                    <Skeleton className="mb-4 h-5 w-full bg-white/20" key={i} />
                  ))
              ) : (
                <div
                  className="prose prose-invert"
                  dangerouslySetInnerHTML={{ __html: about?.about || '' }}
                />
              )}
            </motion.div>
          </div>
        </section>

        {/* Purpose, Vision, Mission Section */}
        <section className="bg-gradient-to-b from-oki-gray-light to-white py-16">
          <div className="container mx-auto px-4">
            <motion.div
              animate="visible"
              className="grid grid-cols-1 gap-8 md:grid-cols-3"
              initial="hidden"
              variants={staggerContainer}
            >
              <motion.div
                className="rounded-lg border-oki-blue-dark border-t-4 bg-white p-8 shadow-lg"
                variants={fadeIn}
              >
                <div className="mb-6 flex items-center">
                  <Heart className="mr-3 h-8 w-8 text-oki-blue-dark" />
                  <h2 className="font-bold text-2xl text-oki-gray-dark">
                    Our Purpose
                  </h2>
                </div>
                {loadingAbout ? (
                  new Array(3)
                    .fill(0)
                    .map((_, i) => (
                      <Skeleton
                        className="mb-4 h-5 w-full bg-gray-400"
                        key={i}
                      />
                    ))
                ) : (
                  <div
                    className="prose text-black"
                    dangerouslySetInnerHTML={{ __html: about?.purpose || '' }}
                  />
                )}
              </motion.div>

              <motion.div
                className="rounded-lg border-oki-blue-light border-t-4 bg-white p-8 shadow-lg"
                variants={fadeIn}
              >
                <div className="mb-6 flex items-center">
                  <Target className="mr-3 h-8 w-8 text-oki-blue-light" />
                  <h2 className="font-bold text-2xl text-oki-gray-dark">
                    Our Vision
                  </h2>
                </div>
                {loadingAbout ? (
                  new Array(3)
                    .fill(0)
                    .map((_, i) => (
                      <Skeleton
                        className="mb-4 h-5 w-full bg-gray-400"
                        key={i}
                      />
                    ))
                ) : (
                  <div
                    className="prose text-black"
                    dangerouslySetInnerHTML={{ __html: about?.vision || '' }}
                  />
                )}
              </motion.div>

              <motion.div
                className="rounded-lg border-oki-red border-t-4 bg-white p-8 shadow-lg"
                variants={fadeIn}
              >
                <div className="mb-6 flex items-center">
                  <BookOpen className="mr-3 h-8 w-8 text-oki-red" />
                  <h2 className="font-bold text-2xl text-oki-gray-dark">
                    Our Mission
                  </h2>
                </div>
                {loadingAbout ? (
                  new Array(3)
                    .fill(0)
                    .map((_, i) => (
                      <Skeleton
                        className="mb-4 h-5 w-full bg-gray-400"
                        key={i}
                      />
                    ))
                ) : (
                  <div className="prose text-black">
                    {about?.mission ? (
                      <div
                        dangerouslySetInnerHTML={{ __html: about.mission }}
                      />
                    ) : (
                      ''
                    )}
                  </div>
                )}
              </motion.div>
            </motion.div>
          </div>
        </section>

        {/* History Section */}
        <section className="bg-oki-gray-light py-16">
          <div className="container mx-auto px-4">
            <div className="grid grid-cols-1 items-center gap-12 lg:grid-cols-2">
              <motion.div
                animate={{ opacity: 1, x: 0 }}
                initial={{ opacity: 0, x: -20 }}
                transition={{ duration: 0.7 }}
              >
                <h2 className="mb-6 font-bold text-3xl text-oki-gray-dark">
                  Our History
                </h2>

                {loadingAbout ? (
                  new Array(7)
                    .fill(0)
                    .map((_, i) => (
                      <Skeleton
                        className="mb-4 h-5 w-full bg-gray-400"
                        key={i}
                      />
                    ))
                ) : about?.history ? (
                  <div
                    className="prose text-black"
                    dangerouslySetInnerHTML={{ __html: about.history }}
                  />
                ) : (
                  <p className="text-gray-500">No history available</p>
                )}
              </motion.div>

              <ProjectImageSlider initialGalleries={galleries} />
            </div>
          </div>
        </section>

        {/* Team Section */}
        <section className="bg-oki-gray-light py-16">
          <div className="container mx-auto px-4">
            <motion.div
              animate={{ opacity: 1, y: 0 }}
              className="mb-12 text-center"
              initial={{ opacity: 0, y: 20 }}
              transition={{ duration: 0.5 }}
            >
              <h2 className="mb-4 font-bold text-3xl text-oki-gray-dark">
                MEET OUR TOP MANAGEMENT
              </h2>
              <p className="mx-auto max-w-3xl text-gray-600">
                At O.K. Isokariari Nigeria Limited (O.K.I), our success is
                driven by the expertise and leadership of our top management
                team. We are proud to introduce the individuals who spearhead
                our company's vision, ensuring the delivery of exceptional
                engineering, procurement, and construction solutions.
              </p>
            </motion.div>

            <motion.div
              animate="visible"
              className="grid grid-cols-1 gap-8 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4"
              initial="hidden"
              variants={staggerContainer}
            >
              {loadingTeams
                ? Array.from({ length: 4 }).map((_, index) => (
                    <motion.div
                      className="grid grid-cols-1 items-center overflow-hidden rounded-lg bg-white shadow-lg transition-shadow hover:shadow-xl"
                      key={`skeleton-${index}`}
                      variants={fadeIn}
                      viewport={{ once: false }}
                    >
                      <div className="h-64 overflow-hidden">
                        <Skeleton className="h-full w-full" />
                      </div>
                      <div className="p-6">
                        <Skeleton className="mb-2 h-6 w-3/4" />
                        <Skeleton className="mb-4 h-4 w-1/2" />
                        <Skeleton className="h-4 w-full" />
                        <Skeleton className="mt-2 h-4 w-2/3" />
                      </div>
                    </motion.div>
                  ))
                : teams.map((member, index) => (
                    <motion.div
                      className="group relative overflow-hidden rounded-lg bg-white shadow-lg transition-shadow hover:shadow-xl"
                      key={index}
                      variants={fadeIn}
                      viewport={{ once: false }}
                    >
                      <div className="relative h-64 overflow-hidden">
                        <Image
                          alt={member.name}
                          className="h-full w-full object-cover object-center transition-transform duration-500 group-hover:scale-105"
                          height={300}
                          src={member.image}
                          width={300}
                        />
                      </div>

                      <div className="absolute inset-0 flex flex-col justify-end bg-gradient-to-t from-black/80 via-black/50 to-transparent p-6 opacity-0 transition-opacity duration-300 group-hover:opacity-100">
                        <div className="translate-y-8 transform transition-transform duration-300 group-hover:translate-y-0">
                          <h3 className="font-bold text-2xl text-white">
                            {member.name}
                          </h3>
                          <p className="mb-4 font-medium text-lg text-rose-500">
                            {member.title}
                          </p>
                          <Button
                            className="mt-2 border-white text-rose-500 hover:bg-white/20 hover:text-white"
                            onClick={(e) => {
                              e.stopPropagation();
                              setSelectedMember(member);
                              setIsDialogOpen(true);
                            }}
                            variant="outline"
                          >
                            Read More
                          </Button>
                        </div>
                      </div>
                    </motion.div>
                  ))}
            </motion.div>
          </div>
        </section>

        {/* Team Member Dialog */}
        <AnimatePresence>
          {isDialogOpen && (
            <Dialog onOpenChange={setIsDialogOpen} open={isDialogOpen}>
              <motion.div
                animate="visible"
                className="fixed inset-0 z-50 bg-black/50"
                exit="hidden"
                initial="hidden"
                variants={overlayVariants}
              >
                <DialogContent className="overflow-hidden sm:max-w-[800px]">
                  <ScrollArea className="max-h-[700px] overflow-y-auto pr-2">
                    <motion.div
                      animate="visible"
                      exit="exit"
                      initial="hidden"
                      variants={dialogVariants}
                    >
                      <motion.div
                        animate={{ opacity: 1 }}
                        className="grid grid-cols-1 gap-4 py-4 sm:grid-cols-2"
                        initial={{ opacity: 0 }}
                        transition={{ delay: 0.2 }}
                      >
                        <motion.div
                          animate={{ scale: 1 }}
                          className="flex justify-center"
                          initial={{ scale: 0.9 }}
                          transition={{ type: 'spring', delay: 0.1 }}
                        >
                          <Image
                            alt={selectedMember?.name || ''}
                            className="border-1 border-oki-blue-light object-cover shadow-lg"
                            height={300}
                            src={selectedMember?.image || ''}
                            width={300}
                          />
                        </motion.div>

                        <motion.div
                          animate={{ y: 0, opacity: 1 }}
                          className="justify-center text-gray-700"
                          initial={{ y: 10, opacity: 0 }}
                          transition={{ delay: 0.3 }}
                        >
                          <h3 className="font-bold text-2xl">
                            {selectedMember?.name}
                          </h3>
                          <p className="mb-4 font-medium text-lg text-oki-blue-light">
                            {selectedMember?.title}
                          </p>
                          {selectedMember?.about &&
                            splitParagraphs(selectedMember.about).map(
                              (paragraph, index) => (
                                <p
                                  className="mb-4 leading-relaxed"
                                  key={`about-me-${index}`}
                                >
                                  {paragraph}
                                </p>
                              )
                            )}
                        </motion.div>
                      </motion.div>
                    </motion.div>
                  </ScrollArea>
                </DialogContent>
              </motion.div>
            </Dialog>
          )}
        </AnimatePresence>

        {/* Core Values Section */}
        <section className="bg-oki-gray-light py-16">
          <div className="container mx-auto px-4">
            <motion.h2
              animate={{ opacity: 1, y: 0 }}
              className="mb-12 text-center font-bold text-3xl text-oki-gray-dark"
              initial={{ opacity: 0, y: 20 }}
              transition={{ duration: 0.5 }}
            >
              Our Core Values
            </motion.h2>
            <motion.div
              animate="visible"
              className="grid grid-cols-1 gap-8 sm:grid-cols-2 lg:grid-cols-4"
              initial="hidden"
              variants={staggerContainer}
            >
              <motion.div
                className="rounded-lg border-oki-blue-dark border-b-4 bg-white p-6 shadow-md transition-shadow hover:shadow-lg"
                variants={fadeIn}
              >
                <div className="mb-4 flex items-center justify-center">
                  <Trophy className="h-12 w-12 text-oki-blue-dark" />
                </div>
                <h3 className="mb-3 text-center font-semibold text-oki-gray-dark text-xl">
                  Excellence
                </h3>
                <p className="text-center text-gray-600">
                  We strive for excellence in every aspect of our work, from
                  project planning to execution and delivery.
                </p>
              </motion.div>
              <motion.div
                className="rounded-lg border-oki-blue-dark border-b-4 bg-white p-6 shadow-md transition-shadow hover:shadow-lg"
                variants={fadeIn}
              >
                <div className="mb-4 flex items-center justify-center">
                  <Users className="h-12 w-12 text-oki-blue-dark" />
                </div>
                <h3 className="mb-3 text-center font-semibold text-oki-gray-dark text-xl">
                  Integrity
                </h3>
                <p className="text-center text-gray-600">
                  We operate with honesty, transparency, and ethical conduct in
                  all our business dealings.
                </p>
              </motion.div>
              <motion.div
                className="rounded-lg border-oki-blue-dark border-b-4 bg-white p-6 shadow-md transition-shadow hover:shadow-lg"
                variants={fadeIn}
              >
                <div className="mb-4 flex items-center justify-center">
                  <svg
                    className="h-12 w-12 text-oki-blue-dark"
                    fill="none"
                    stroke="currentColor"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth="2"
                    viewBox="0 0 24 24"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <title>Innovation Icon</title>
                    <circle cx="12" cy="12" r="10" />
                    <line x1="12" x2="12" y1="8" y2="12" />
                    <line x1="12" x2="12.01" y1="16" y2="16" />
                  </svg>
                </div>
                <h3 className="mb-3 text-center font-semibold text-oki-gray-dark text-xl">
                  Innovation
                </h3>
                <p className="text-center text-gray-600">
                  We embrace innovative approaches and technologies to deliver
                  superior results.
                </p>
              </motion.div>
              <motion.div
                className="rounded-lg border-oki-blue-dark border-b-4 bg-white p-6 shadow-md transition-shadow hover:shadow-lg"
                variants={fadeIn}
              >
                <div className="mb-4 flex items-center justify-center">
                  <Globe className="h-12 w-12 text-oki-blue-dark" />
                </div>
                <h3 className="mb-3 text-center font-semibold text-oki-gray-dark text-xl">
                  Sustainability
                </h3>
                <p className="text-center text-gray-600">
                  We are committed to environmentally responsible practices and
                  sustainable development.
                </p>
              </motion.div>
            </motion.div>
          </div>
        </section>

        <ClientsCarousel />

        {/* CTA Section */}
        <section className="bg-gradient-to-r from-oki-blue-dark to-oki-blue-light py-16 text-white">
          <div className="container mx-auto px-4 text-center">
            <motion.div
              animate={{ opacity: 1, y: 0 }}
              initial={{ opacity: 0, y: 30 }}
              transition={{ duration: 0.7 }}
              viewport={{ once: false }}
            >
              <h2 className="mb-6 font-bold text-3xl">
                Ready to Work With Us?
              </h2>
              <p className="mx-auto mb-8 max-w-2xl text-lg text-white/80">
                Whether you're looking for a construction partner, career
                opportunities, or more information about our services, we'd love
                to hear from you.
              </p>
              <div className="flex flex-col justify-center gap-4 sm:flex-row">
                <Link href="/contact">
                  <Button className="bg-white px-8 py-6 text-oki-blue-dark hover:bg-white/90">
                    Contact Us
                  </Button>
                </Link>
                <Link href="/team">
                  <Button
                    className="bg-red px-8 py-6 text-white hover:bg-white"
                    variant="outline"
                  >
                    Meet Our Team
                  </Button>
                </Link>
              </div>
            </motion.div>
          </div>
        </section>
      </div>
    </WebLayout>
  );
};

export default About;
