"use client";

import { motion } from "framer-motion";
import {
  MapPin,
  Calendar,
  CheckCircle2,
  HardHat,
  Loader2,
  Anchor,
  Radar,
  Droplets,
  Ship,
  Fuel,
  Cylinder,
  Download,
  Wrench,
  ChevronRight,
  type LucideProps,
} from "lucide-react";
import Link from "next/link";
import Image from "next/image";
import SectionHeading from "@/components/SectionHeading";
import CountriesList from "@/components/regions/CountriesList";
import { SECTOR_ICONS } from "@/lib/sectorIconMap";
import type { Region } from "@/services/regions";
import type { RegionService, RegionProject } from "@/services/regions";


type IconComponent = React.ComponentType<LucideProps>;

const ICON_MAP: Record<string, IconComponent> = {
  Anchor,
  Radar,
  Droplets,
  Ship,
  Fuel,
  HardHat,
  Cylinder,
};

interface RegionDetailProps {
  region: Region;
  services: RegionService[];
  projects: RegionProject[];
}

const ServiceCard = ({
  service,
  index,
}: {
  service: RegionService;
  index: number;
}) => {
  const IconComponent = SECTOR_ICONS[service.icon]?.component || Wrench;

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true }}
      transition={{ delay: index * 0.08, duration: 0.5 }}
      whileHover={{ y: -5 }}
      className="petro-card overflow-hidden group"
    >

      <div className="relative h-48 overflow-hidden">
        {service.image_url ? (
          <Image
            src={service.image_url}
            alt={service.title}
            width={600}
            height={400}
            className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
            loading="lazy"
          />
        ) : (
          <div className="w-full h-full bg-primary/20" />
        )}
        <div className="absolute inset-0 bg-gradient-to-t from-primary/80 to-transparent" />
        <div className="absolute bottom-4 left-4 p-2.5 bg-primary-foreground/10 backdrop-blur-sm rounded-sm">
          <IconComponent size={22} className="text-accent" />
        </div>
      </div>
      <div className="p-6">
        <h3 className="text-lg font-bold text-foreground mb-2 group-hover:text-primary transition-colors leading-tight">
          {service.title}
        </h3>
        <p className="text-muted-foreground text-sm leading-relaxed mb-5">
          {service.short_desc}
        </p>

        <Link
          href={`/services/${service.slug}`}
          className="petro-btn-gold text-[11px] mt-5 inline-flex items-center gap-2 w-full justify-center"
        >
          Explore Service <ChevronRight size={14} />
        </Link>
      </div>
    </motion.div>
  );
};

function resolveIcon(name: string | null): IconComponent {
  return (name && ICON_MAP[name]) ? ICON_MAP[name] : HardHat;
}

const ProjectCard = ({
  project,
  index,
}: {
  project: RegionProject;
  index: number;
}) => {
  const isReversed = index % 2 !== 0;

  return (
    <motion.article
      initial={{ opacity: 0, y: 40 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true, margin: "-60px" }}
      transition={{ delay: index * 0.1, duration: 0.6 }}
      className={`grid lg:grid-cols-2 gap-0 petro-card overflow-hidden ${isReversed ? "lg:direction-rtl" : ""}`}
    >
      {/* Image */}
      <div className={`relative h-72 lg:h-auto min-h-[360px] overflow-hidden ${isReversed ? "lg:order-2" : ""}`}>
        {project.image_url ? (
          <Image
            src={project.image_url}
            alt={project.title}
            fill
            className="w-full h-full object-cover transition-transform duration-700 hover:scale-105"
          />
        ) : (
          <div className="flex h-full items-center justify-center bg-primary/10">
            <Wrench size={64} className="text-primary/20" />
          </div>
        )}
        {project.year && (
          <div className="absolute top-6 left-6 bg-primary/90 backdrop-blur-sm px-4 py-2 flex items-center gap-2">
            <Calendar size={14} className="text-accent" />
            <span className="text-xs font-bold text-primary-foreground tracking-wider">{project.year}</span>
          </div>
        )}
      </div>

      {/* Content */}
      <div className={`p-8 lg:p-12 flex flex-col justify-center ${isReversed ? "lg:order-1" : ""}`}>
        <div className="flex items-center gap-3 mb-4">
          <div className="w-10 h-10 rounded bg-accent/10 flex items-center justify-center">
            <Wrench size={20} className="text-accent" />
          </div>
          {project.location && (
            <div className="flex items-center gap-2 text-accent text-[10px] font-bold uppercase tracking-[0.2em]">
              <MapPin size={12} />
              {project.location}
            </div>
          )}
        </div>

        <h3 className="text-2xl font-bold text-foreground mb-2 tracking-tight">
          {project.title}
        </h3>
        <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-4">
          {project.client && `Client: ${project.client}`}
        </p>

        {project.summary && (
          <p className="text-muted-foreground text-sm leading-relaxed mb-6">{project.summary}</p>
        )}

        {/* Scope */}
        {project.scope.length > 0 && (
          <div className="mb-6">
            <h4 className="text-xs font-bold uppercase tracking-[0.2em] text-primary mb-3">Scope of Work</h4>
            <ul className="space-y-2">
              {project.scope.map((item, i) => (
                <li key={i} className="flex items-start gap-2 text-sm text-muted-foreground">
                  <CheckCircle2 size={14} className="text-accent mt-0.5 shrink-0" />
                  {item}
                </li>
              ))}
            </ul>
          </div>
        )}

        {/* Technologies */}
        {project.technologies.length > 0 && (
          <div className="flex flex-wrap gap-2 mb-6">
            {project.technologies.map((tech, i) => (
              <span
                key={i}
                className="px-3 py-1 bg-secondary text-secondary-foreground text-[10px] font-bold uppercase tracking-wider rounded-sm"
              >
                {tech}
              </span>
            ))}
          </div>
        )}

        {/* Outcome */}
        {project.outcome && (
          <div className="bg-secondary/50 border-l-2 border-accent p-4 rounded-r-sm">
            <h4 className="text-xs font-bold uppercase tracking-[0.2em] text-accent mb-2">Key Outcome</h4>
            <p className="text-sm text-foreground leading-relaxed">{project.outcome}</p>
          </div>
        )}

        {/* Document download */}
        {project.document_url && (
          <a
            href={project.document_url}
            download
            target="_blank"
            rel="noopener noreferrer"
            className="mt-6 inline-flex items-center gap-2 self-start px-4 py-2 border border-accent/40 text-accent text-xs font-bold uppercase tracking-wider rounded-sm hover:bg-accent hover:text-accent-foreground transition-colors"
          >
            <Download size={13} />
            Download Project Report
          </a>
        )}
      </div>
    </motion.article>

  );
};


const RegionDetail = ({
  region,
  services,
  projects,
}: RegionDetailProps) => {
  return (
    <>
      {/* Region Header */}
      <section className="bg-gradient-to-br from-primary/10 to-primary/5 petro-section pt-32">
        <div className="petro-container">
          <motion.div
            initial={{ opacity: 0, y: -20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5 }}
          >
            <h1 className="text-5xl md:text-6xl font-bold text-foreground mb-4">
              {region.name}
            </h1>
            <p className="text-lg text-muted-foreground max-w-2xl">
              Explore our comprehensive services and successfully completed
              projects across this dynamic region.
            </p>
          </motion.div>
        </div>
      </section>

      {/* Countries Section */}
      <section className="petro-section">
        <div className="petro-container">
          <SectionHeading
            title="Countries in This Region"
            subtitle={`${region.countries?.length || 0} countries covered`}
          />
          {region.countries && region.countries.length > 0 ? (
            <CountriesList countries={region.countries} />
          ) : (
            <div className="text-center py-12 text-muted-foreground">
              <p className="text-lg">No countries listed for this region.</p>
            </div>
          )}
        </div>
      </section>

      {/* Services Section */}
      <section className="petro-section bg-secondary">
        <div className="petro-container">
          <SectionHeading
            title="Services Offered"
            subtitle={`${services.length} services available in ${region.name}`}
          />
          {services.length > 0 ? (
            <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
              {services.map((service, index) => (
                <ServiceCard
                  key={service.id}
                  service={service}
                  index={index}
                />
              ))}
            </div>
          ) : (
            <div className="text-center py-12 text-muted-foreground">
              <p className="text-lg">
                No services currently listed for this region.
              </p>
            </div>
          )}
        </div>
      </section>

      {/* Projects Section */}
      <section className="petro-section">
        <div className="petro-container">
          <SectionHeading
            title="Featured Projects"
            subtitle={`${projects.length} projects completed in ${region.name}`}
          />
          {projects.length > 0 ? (
            <div className="space-y-12">
              {projects.map((project, index) => (
                <ProjectCard key={project.id} project={project} index={index} />

              ))}
            </div>
          ) : (
            <div className="text-center py-12 text-muted-foreground">
              <p className="text-lg">
                No projects currently listed for this region.
              </p>
            </div>
          )}
        </div>
      </section>
    </>
  );
};

export default RegionDetail;
