import type { Metadata } from "next";
import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";
import {
  ShieldCheckIcon,
  FactoryIcon,
  WarehouseIcon,
  GlobeIcon,
  WrenchIcon,
  WheatIcon,
  AwardIcon,
  CheckIcon,
  PhoneIcon,
  ArrowRightIcon,
  BadgeCheckIcon,
  MapPinIcon,
} from "lucide-react";
import { Container } from "@/app/components/layout/Container";
import Heading from "@/app/components/ui/Heading";
import { mills, getMillBySlug } from "../_data/mills";
import heroImg from "@/app/(services)/milling/_assets/milling-hero-banner.png";

export function generateStaticParams() {
  return mills.map((mill) => ({ slug: mill.slug }));
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const { slug } = await params;
  const mill = getMillBySlug(slug);
  if (!mill) return {};

  const certSummary =
    mill.certifications.length > 0
      ? ` Certified with ${mill.certifications.slice(0, 3).join(", ")}.`
      : "";
  const varietySummary =
    mill.riceVarieties.length > 0
      ? ` Supplying ${mill.riceVarieties.slice(0, 3).join(", ")}.`
      : "";

  const title = `${mill.name} — Rice Mill Profile | Basmati Pakistan`;
  const description = `Comprehensive profile of ${mill.name}, a premier rice processing mill in Pakistan.${certSummary}${varietySummary} Export-quality basmati and non-basmati rice.`;

  return {
    title,
    description,
    alternates: {
      canonical: `https://basmatipakistan.com/mills/${slug}/`,
    },
    openGraph: {
      title,
      description,
      url: `https://basmatipakistan.com/mills/${slug}/`,
      images: [
        {
          url: "https://basmatipakistan.com/wp-content/uploads/2024/10/Introduction-to-Paddy-Milling.png",
        },
      ],
      type: "website",
    },
    twitter: {
      card: "summary_large_image",
      title,
      description,
      images: [
        "https://basmatipakistan.com/wp-content/uploads/2024/10/Introduction-to-Paddy-Milling.png",
      ],
    },
  };
}

interface ProfileCardProps {
  title: string;
  icon: React.ReactNode;
  children: React.ReactNode;
}

function ProfileCard({ title, icon, children }: ProfileCardProps) {
  return (
    <div className="border border-gray-200 rounded-2xl p-7 lg:p-8 bg-white shadow-xs hover:border-primary/50 transition-all duration-300">
      <div className="flex items-center gap-3 mb-6 pb-4 border-b border-gray-100">
        <div className="bg-[#198A2121] p-3 rounded-full text-primary">
          {icon}
        </div>
        <Heading as="h2" variant="card" className="text-primary text-xl">
          {title}
        </Heading>
      </div>
      {children}
    </div>
  );
}

export default async function MillProfilePage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const mill = getMillBySlug(slug);

  if (!mill) {
    notFound();
  }

  const hasCapacity =
    mill.millingCapacities.length > 0 || mill.storageCapacities.length > 0;

  return (
    <>
      {/* Hero Section matching the website design */}
      <section className="relative h-[65vh] w-full">
        <Image
          src={heroImg}
          alt={`${mill.name} Facility Hero`}
          fill
          placeholder="blur"
          className="absolute top-0 left-0 w-full h-full object-cover object-center"
          priority
          fetchPriority="high"
          loading="eager"
        />
        <div className="relative bg-black/60 w-full h-full flex items-center">
          <Container>
            <div className="flex flex-col items-center gap-4 text-center">
              <Heading
                as="h1"
                variant="title"
                className="text-white text-center max-w-4xl"
              >
                {mill.name}
              </Heading>

              {/* Highlights badge bar in hero */}
              <div className="flex flex-wrap justify-center gap-3 mt-3">
                {mill.locationSummary && (
                  <span className="flex items-center gap-1.5 bg-white/20 backdrop-blur-xs text-white text-sm px-4 py-1.5 rounded-full font-medium">
                    <MapPinIcon size={16} />
                    {mill.locationSummary}
                  </span>
                )}
                {mill.certifications.length > 0 && (
                  <span className="flex items-center gap-1.5 bg-white/20 backdrop-blur-xs text-white text-sm px-4 py-1.5 rounded-full font-medium">
                    <ShieldCheckIcon size={16} />
                    {mill.certifications.length} Certification
                    {mill.certifications.length !== 1 && "s"}
                  </span>
                )}
                {mill.riceVarieties.length > 0 && (
                  <span className="flex items-center gap-1.5 bg-white/20 backdrop-blur-xs text-white text-sm px-4 py-1.5 rounded-full font-medium">
                    <WheatIcon size={16} />
                    {mill.riceVarieties.length} Product
                    {mill.riceVarieties.length !== 1 && "s"}
                  </span>
                )}
                {mill.exportDestinations.length > 0 && (
                  <span className="flex items-center gap-1.5 bg-white/20 backdrop-blur-xs text-white text-sm px-4 py-1.5 rounded-full font-medium">
                    <GlobeIcon size={16} />
                    {mill.exportDestinations.length} Export Market
                    {mill.exportDestinations.length !== 1 && "s"}
                  </span>
                )}
                {mill.tradeMemberships.length > 0 && (
                  <span className="flex items-center gap-1.5 bg-white/20 backdrop-blur-xs text-white text-sm px-4 py-1.5 rounded-full font-medium">
                    <AwardIcon size={16} />
                    Trade Member
                  </span>
                )}
              </div>
            </div>
          </Container>
        </div>
        <div className="absolute z-10 bottom-0 w-full bg-white h-24 [clip-path:polygon(100%_100%,100%_0,0_100%)]"></div>
      </section>

      {/* Main Profile Layout with Right Sidebar */}
      <section className="mt-16 lg:mt-24">
        <Container>
          <div className="flex flex-col lg:flex-row gap-10 lg:gap-12 items-start">
            {/* Left Content Column (Profile details) */}
            <div className="w-full lg:w-2/3 flex flex-col gap-8">
              {/* Quality & Food Safety Certifications */}
              {mill.certifications.length > 0 && (
                <ProfileCard
                  title="Quality & Food Safety Certifications"
                  icon={<ShieldCheckIcon size={22} />}
                >
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    {mill.certifications.map((cert, idx) => (
                      <div
                        key={`cert-item-${mill.slug}-${idx}-${cert}`}
                        className="flex items-center gap-2.5 bg-[#EFF8E1]/60 border border-[#467302]/20 rounded-xl p-3.5"
                      >
                        <BadgeCheckIcon
                          size={18}
                          className="text-primary shrink-0"
                        />
                        <span className="text-sm font-semibold text-gray-800">
                          {cert}
                        </span>
                      </div>
                    ))}
                  </div>
                </ProfileCard>
              )}

              {/* Rice Varieties & Products */}
              {mill.riceProducts.length > 0 && (
                <ProfileCard
                  title="Rice Varieties &amp; Products"
                  icon={<WheatIcon size={22} />}
                >
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                    {mill.riceProducts.map((prod, idx) => {
                      const isOrganic = prod.toLowerCase().includes("organic");
                      const isFairtrade = prod
                        .toLowerCase()
                        .includes("fairtrade");
                      return (
                        <div
                          key={`prod-item-${mill.slug}-${idx}-${prod}`}
                          className="flex items-center justify-between gap-3 border border-gray-200 rounded-xl p-4 bg-gray-50/50 hover:border-primary/40 transition-colors"
                        >
                          <span className="font-semibold text-gray-900 text-sm">
                            {prod}
                          </span>
                          <div className="flex items-center gap-1.5 shrink-0">
                            {isOrganic && (
                              <span className="bg-primary/10 text-primary text-[11px] font-bold px-2.5 py-0.5 rounded-full">
                                Organic
                              </span>
                            )}
                            {isFairtrade && (
                              <span className="bg-accent/10 text-accent text-[11px] font-bold px-2.5 py-0.5 rounded-full">
                                Fairtrade
                              </span>
                            )}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </ProfileCard>
              )}

              {/* Processing & Storage Capacity */}
              {hasCapacity && (
                <ProfileCard
                  title="Milling &amp; Storage Capabilities"
                  icon={<FactoryIcon size={22} />}
                >
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    {mill.millingCapacities.length > 0 && (
                      <div className="bg-[#EFF8E1]/40 border border-[#467302]/20 rounded-xl p-5">
                        <div className="flex items-center gap-2 mb-2">
                          <FactoryIcon size={18} className="text-primary" />
                          <p className="text-xs uppercase tracking-wider font-bold text-primary">
                            Milling Capacity
                          </p>
                        </div>
                        <div className="space-y-1">
                          {mill.millingCapacities.map((cap, idx) => (
                            <p
                              key={`mill-cap-${mill.slug}-${idx}`}
                              className="text-lg font-bold text-gray-900"
                            >
                              {cap.formatted}
                            </p>
                          ))}
                        </div>
                      </div>
                    )}

                    {mill.storageCapacities.length > 0 && (
                      <div className="bg-[#EFF8E1]/40 border border-[#467302]/20 rounded-xl p-5">
                        <div className="flex items-center gap-2 mb-2">
                          <WarehouseIcon size={18} className="text-primary" />
                          <p className="text-xs uppercase tracking-wider font-bold text-primary">
                            Storage Capacity
                          </p>
                        </div>
                        <div className="space-y-1">
                          {mill.storageCapacities.map((cap, idx) => (
                            <p
                              key={`stor-cap-${mill.slug}-${idx}`}
                              className="text-lg font-bold text-gray-900"
                            >
                              {cap.formatted}
                            </p>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                </ProfileCard>
              )}

              {/* Export Destinations & Global Markets */}
              {(mill.exportDestinations.length > 0 ||
                mill.exportReachClaims.length > 0) && (
                <ProfileCard
                  title="International Export Markets"
                  icon={<GlobeIcon size={22} />}
                >
                  {mill.exportReachClaims.length > 0 && (
                    <div className="mb-4 p-3.5 bg-[#EFF8E1]/60 border border-[#467302]/20 rounded-xl flex items-center gap-2 text-primary text-sm font-semibold">
                      <GlobeIcon size={18} className="text-primary shrink-0" />
                      <span>{mill.exportReachClaims.join(" • ")}</span>
                    </div>
                  )}
                  {mill.exportDestinations.length > 0 && (
                    <div>
                      <p className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3">
                        Confirmed Export Destinations
                      </p>
                      <div className="flex flex-wrap gap-2">
                        {mill.exportDestinations.map((dest, idx) => (
                          <span
                            key={`dest-item-${mill.slug}-${idx}-${dest}`}
                            className="bg-[#EFF8E1]/70 text-primary border border-primary/20 text-sm px-4 py-2 rounded-full font-medium"
                          >
                            {dest}
                          </span>
                        ))}
                      </div>
                    </div>
                  )}
                </ProfileCard>
              )}

              {/* Machinery & Processing Brands */}
              {mill.machineryBrands.length > 0 && (
                <ProfileCard
                  title="Machinery &amp; Technology"
                  icon={<WrenchIcon size={22} />}
                >
                  <p className="text-sm text-gray-600 mb-3">
                    State-of-the-art rice processing machinery and cleaning,
                    dehulling, polishing, and optical color sorting equipment:
                  </p>
                  <div className="flex flex-wrap gap-2.5">
                    {mill.machineryBrands.map((brand, idx) => (
                      <span
                        key={`mach-item-${mill.slug}-${idx}-${brand}`}
                        className="bg-gray-100 text-gray-800 border border-gray-200 text-sm px-4 py-2 rounded-full font-semibold"
                      >
                        {brand}
                      </span>
                    ))}
                  </div>
                </ProfileCard>
              )}

              {/* Trade Memberships */}
              {mill.tradeMemberships.length > 0 && (
                <ProfileCard
                  title="Trade Memberships &amp; Industry Affiliations"
                  icon={<AwardIcon size={22} />}
                >
                  <div className="space-y-2.5">
                    {mill.tradeMemberships.map((mem, idx) => (
                      <div
                        key={`mem-item-${mill.slug}-${idx}-${mem}`}
                        className="flex items-center gap-3 p-3 bg-gray-50 rounded-xl border border-gray-100 text-sm text-gray-800 font-medium"
                      >
                        <CheckIcon
                          size={16}
                          className="text-primary shrink-0"
                        />
                        <span>{mem}</span>
                      </div>
                    ))}
                  </div>
                </ProfileCard>
              )}
            </div>

            {/* Right Column - Sticky Quote & Contact Card */}
            <div className="w-full lg:w-1/3 lg:sticky lg:top-32 flex flex-col gap-6">
              {/* Primary Inquire / Quote Card */}
              <div className="bg-gradient-to-b from-[#273c07] to-primary text-white rounded-3xl p-7 lg:p-8 shadow-xl flex flex-col gap-6">
                <div>
                  <span className="text-xs uppercase tracking-wider text-white/70 font-bold block mb-1">
                    Export Desk Inquiry
                  </span>
                  <Heading as="h3" variant="card" className="text-white text-xl">
                    Inquire About {mill.name}
                  </Heading>
                </div>

                <p className="text-sm text-gray-100/90 leading-relaxed">
                  Looking to source premium Basmati or non-Basmati rice processed
                  by <strong className="text-white">{mill.name}</strong>?
                  Contact our export desk for specifications, private label
                  options, and FOB / CIF pricing.
                </p>

                <div className="space-y-3 py-3 border-y border-white/15 text-sm text-gray-100">
                  <div className="flex items-center gap-2.5">
                    <CheckIcon size={16} className="text-white shrink-0" />
                    <span>Quality-tested export shipments</span>
                  </div>
                  <div className="flex items-center gap-2.5">
                    <CheckIcon size={16} className="text-white shrink-0" />
                    <span>Custom packaging (1kg to 50kg)</span>
                  </div>
                  <div className="flex items-center gap-2.5">
                    <CheckIcon size={16} className="text-white shrink-0" />
                    <span>Worldwide port logistics support</span>
                  </div>
                </div>

                <div className="flex flex-col gap-3 pt-2">
                  <Link
                    href="/get-a-quote"
                    className="w-full text-center bg-white text-primary hover:bg-accent hover:text-white py-3.5 px-6 rounded-full font-bold text-sm transition-all duration-300 shadow-md hover:shadow-lg flex items-center justify-center gap-2 group"
                  >
                    <span>Request a Quote</span>
                    <ArrowRightIcon
                      size={16}
                      className="group-hover:translate-x-1 transition-transform"
                    />
                  </Link>
                  <Link
                    href="/contact"
                    className="w-full text-center border border-white/40 hover:bg-white/15 text-white py-3 px-6 rounded-full font-semibold text-sm transition-all duration-300 flex items-center justify-center gap-2"
                  >
                    <PhoneIcon size={15} />
                    <span>Contact Sales Desk</span>
                  </Link>
                </div>

                <div className="text-xs text-white/70 text-center pt-2 border-t border-white/10 space-y-1">
                  <p>Direct assistance:</p>
                  <Link
                    href="tel:+923151558886"
                    className="text-white font-semibold hover:underline block"
                  >
                    +92 315 1558886
                  </Link>
                  <Link
                    href="mailto:sales@basmatipakistan.com"
                    className="text-white/90 hover:underline block"
                  >
                    sales@basmatipakistan.com
                  </Link>
                </div>
              </div>

              {/* Secondary Trust Card */}
              <div className="border border-gray-200 rounded-2xl p-6 bg-white shadow-xs flex flex-col gap-3 text-sm text-gray-600">
                <Heading as="h4" variant="card" className="text-primary text-base">
                  Export Assurance
                </Heading>
                <p className="text-xs text-gray-500 leading-relaxed">
                  Basmati Pakistan coordinates directly with accredited mills to
                  guarantee purity, moisture standards, grain length, and
                  timely global container shipments.
                </p>
              </div>
            </div>
          </div>
        </Container>
      </section>
    </>
  );
}
