import { Badge } from "@/src/components/ui/badge";
import { Button } from "@/src/components/ui/button";
import { Card, CardContent } from "@/src/components/ui/card";
import Link from "next/link";
import {
  Calendar,
  Clock,
  ArrowLeft,
  Share2,
  Bookmark,
  ChevronRight,
  User,
  Tag,
  CheckCircle,
  ArrowRight,
  Facebook,
  Twitter,
  Linkedin,
  Mail,
} from "lucide-react";
import type { Metadata } from "next";

// Article data - in production, this would come from a CMS or database
const articles: Record<string, {
  title: string;
  excerpt: string;
  category: string;
  date: string;
  readTime: string;
  author: { name: string; role: string; avatar: string };
  tags: string[];
  content: { type: string; text?: string; items?: string[]; heading?: string }[];
  relatedPosts: { title: string; slug: string; category: string; readTime: string }[];
}> = {
  "import-agricultural-products-india-guide-2026": {
    title: "How to Import Agricultural Products from India: A Complete Guide for 2026",
    excerpt: "Everything you need to know about importing high-quality agricultural products from India, including regulatory requirements, quality standards, and best practices.",
    category: "Export Guide",
    date: "February 28, 2026",
    readTime: "12 min read",
    author: {
      name: "Rajesh Kumar",
      role: "Export Compliance Specialist",
      avatar: "/images/author-avatar.jpg",
    },
    tags: ["Agricultural Exports", "Import Guide", "Quality Standards", "FSSAI", "Trade Regulations"],
    content: [
      {
        type: "paragraph",
        text: "India is one of the world's largest exporters of agricultural products, offering a diverse range of commodities from premium Basmati rice to exotic spices, fresh fruits, and organic produce. For international buyers looking to source agricultural products from India, understanding the import process is crucial for ensuring smooth transactions and maintaining product quality."
      },
      {
        type: "heading",
        heading: "Why Import Agricultural Products from India?"
      },
      {
        type: "paragraph",
        text: "India's agricultural sector is renowned for its diversity, quality, and competitive pricing. The country's varied climate zones enable the production of a wide range of crops throughout the year, making it an ideal sourcing destination for global buyers."
      },
      {
        type: "list",
        items: [
          "Competitive pricing due to lower production costs",
          "Wide variety of agricultural products available year-round",
          "Established export infrastructure with major ports",
          "Growing number of certified organic producers",
          "Government support for agricultural exports"
        ]
      },
      {
        type: "heading",
        heading: "Key Agricultural Products for Export"
      },
      {
        type: "paragraph",
        text: "India exports a vast array of agricultural products. The most sought-after categories include cereals (especially Basmati rice), spices, tea and coffee, fresh and processed fruits, vegetables, and organic produce. Each category has its own set of quality standards and certification requirements."
      },
      {
        type: "heading",
        heading: "Regulatory Requirements and Certifications"
      },
      {
        type: "paragraph",
        text: "Before importing agricultural products from India, buyers must understand the regulatory framework. Key certifications include FSSAI (Food Safety and Standards Authority of India), APEDA registration for agricultural products, phytosanitary certificates for plant products, and specific certifications based on the destination country's requirements."
      },
      {
        type: "list",
        items: [
          "FSSAI License - Mandatory for all food products",
          "APEDA Registration - Required for scheduled agricultural products",
          "Phytosanitary Certificate - For plant and plant products",
          "Certificate of Origin - For preferential tariff benefits",
          "Organic Certification - For organic products (NPOP/NOP/EU Organic)"
        ]
      },
      {
        type: "heading",
        heading: "Quality Assurance and Testing"
      },
      {
        type: "paragraph",
        text: "Quality control is paramount when importing agricultural products. Indian exporters typically provide Certificate of Analysis (COA), product specifications, and third-party inspection reports. Buyers should also consider pre-shipment inspections and sampling before finalizing large orders."
      },
      {
        type: "heading",
        heading: "Shipping and Logistics Considerations"
      },
      {
        type: "paragraph",
        text: "Agricultural products require special attention during shipping due to their perishable nature. Proper packaging, temperature control, and timely delivery are essential. India has well-established export logistics with major ports like JNPT (Mumbai), Chennai, and Mundra offering efficient container handling and cold storage facilities."
      },
      {
        type: "heading",
        heading: "Payment Terms and Trade Finance"
      },
      {
        type: "paragraph",
        text: "Common payment terms for agricultural imports include Letter of Credit (LC), Documents against Payment (D/P), and Telegraphic Transfer (TT). For first-time buyers, LC is recommended as it provides security for both parties. Established relationships may move to more flexible payment terms over time."
      },
      {
        type: "heading",
        heading: "Conclusion"
      },
      {
        type: "paragraph",
        text: "Importing agricultural products from India offers significant opportunities for international buyers seeking quality products at competitive prices. By understanding the regulatory requirements, quality standards, and logistics considerations, buyers can establish successful and long-lasting trade relationships with Indian suppliers."
      }
    ],
    relatedPosts: [
      { title: "Indian Spices: Meeting Global Quality Standards", slug: "indian-spices-global-quality-standards", category: "Quality Standards", readTime: "5 min" },
      { title: "Essential Export Documentation Guide", slug: "export-documentation-guide", category: "Export Guide", readTime: "6 min" },
      { title: "Navigating Incoterms 2020", slug: "navigating-incoterms-2020", category: "Trade Terms", readTime: "7 min" }
    ]
  },
  "future-global-trade-trends-2026": {
    title: "The Future of Global Trade: Trends Shaping 2026",
    excerpt: "Explore the emerging trends in international trade, from digital transformation to sustainable supply chains, and how they impact Indian exporters.",
    category: "Industry Trends",
    date: "February 28, 2026",
    readTime: "8 min read",
    author: {
      name: "Priya Sharma",
      role: "Trade Analyst",
      avatar: "/images/author-avatar.jpg",
    },
    tags: ["Global Trade", "Industry Trends", "Digital Transformation", "Sustainability"],
    content: [
      {
        type: "paragraph",
        text: "The global trade landscape is undergoing significant transformation in 2026. From digital technologies reshaping supply chains to increasing focus on sustainability, exporters and importers alike must adapt to remain competitive in this evolving environment."
      },
      {
        type: "heading",
        heading: "Digital Transformation in Trade"
      },
      {
        type: "paragraph",
        text: "Blockchain, AI, and IoT are revolutionizing how international trade operates. These technologies are improving transparency, reducing paperwork, and enabling real-time tracking of shipments across borders."
      },
      {
        type: "list",
        items: [
          "Blockchain-based trade finance reducing transaction times",
          "AI-powered demand forecasting and inventory management",
          "IoT sensors enabling real-time cargo monitoring",
          "Digital documentation reducing customs clearance delays",
          "E-commerce platforms expanding market access for SMEs"
        ]
      },
      {
        type: "heading",
        heading: "Sustainability and Green Trade"
      },
      {
        type: "paragraph",
        text: "Environmental considerations are increasingly influencing trade decisions. Carbon footprint tracking, sustainable packaging, and eco-friendly logistics are becoming standard requirements rather than optional differentiators."
      },
      {
        type: "heading",
        heading: "Conclusion"
      },
      {
        type: "paragraph",
        text: "Staying ahead of these trends is essential for businesses engaged in international trade. Those who embrace digital transformation and sustainability will be best positioned to succeed in the evolving global marketplace."
      }
    ],
    relatedPosts: [
      { title: "Sustainable Packaging Solutions for Export", slug: "sustainable-packaging-export", category: "Sustainability", readTime: "4 min" },
      { title: "Digital Documentation in Trade", slug: "digital-documentation-trade", category: "Technology", readTime: "5 min" },
      { title: "Green Logistics Trends", slug: "green-logistics-trends", category: "Logistics", readTime: "6 min" }
    ]
  }
};

// Article type definition
type Article = {
  title: string;
  excerpt: string;
  category: string;
  date: string;
  readTime: string;
  author: { name: string; role: string; avatar: string };
  tags: string[];
  content: { type: string; text?: string; items?: string[]; heading?: string }[];
  relatedPosts: { title: string; slug: string; category: string; readTime: string }[];
};

// Default article for unknown slugs
const defaultArticle: Article = {
  title: "Trade Insights Article",
  excerpt: "Expert analysis and insights for international trade.",
  category: "Export Guide",
  date: "February 2026",
  readTime: "5 min read",
  author: {
    name: "Xpecto Team",
    role: "Trade Experts",
    avatar: "/images/author-avatar.jpg",
  },
  tags: ["Trade", "Export", "India"],
  content: [
    {
      type: "paragraph",
      text: "This article provides valuable insights into international trade practices and export procedures from India."
    }
  ],
  relatedPosts: []
};

type Props = {
  params: Promise<{ slug: string }>;
};

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const article = articles[slug] || defaultArticle;
  
  return {
    title: article.title,
    description: article.excerpt,
    keywords: article.tags,
    authors: [{ name: article.author.name }],
    alternates: {
      canonical: `/insights/${slug}`,
    },
    openGraph: {
      title: article.title,
      description: article.excerpt,
      type: "article",
      publishedTime: article.date,
      authors: [article.author.name],
      tags: article.tags,
    },
    twitter: {
      card: "summary_large_image",
      title: article.title,
      description: article.excerpt,
    },
  };
}

// JSON-LD Schema for Article
function generateArticleSchema(article: Article, slug: string) {
  const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || "https://xpectoglobaltrade.com";
  
  return {
    "@context": "https://schema.org",
    "@type": "Article",
    headline: article.title,
    description: article.excerpt,
    author: {
      "@type": "Person",
      name: article.author.name,
      jobTitle: article.author.role,
    },
    publisher: {
      "@type": "Organization",
      name: "Xpecto Global",
      logo: {
        "@type": "ImageObject",
        url: `${siteUrl}/logo.png`,
      },
    },
    datePublished: article.date,
    dateModified: article.date,
    mainEntityOfPage: {
      "@type": "WebPage",
      "@id": `${siteUrl}/insights/${slug}`,
    },
    keywords: article.tags.join(", "),
    articleSection: article.category,
  };
}

export default async function InsightDetail({ params }: Props) {
  const { slug } = await params;
  const article = articles[slug] || defaultArticle;
  const articleSchema = generateArticleSchema(article, slug);

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(articleSchema) }}
      />
      <div className="bg-white">
        {/* Breadcrumb */}
        <section className="bg-[#F5F7FA] py-4 border-b">
          <div className="max-w-360 mx-auto px-6">
            <nav className="flex items-center gap-2 text-sm text-gray-600">
              <Link href="/" className="hover:text-[#B8860B] transition-colors">
                Home
              </Link>
              <ChevronRight size={14} />
              <Link href="/insights" className="hover:text-[#B8860B] transition-colors">
                Insights
              </Link>
              <ChevronRight size={14} />
              <span className="text-[#0B1C2D] font-medium truncate max-w-50 md:max-w-none">
                {article.category}
              </span>
            </nav>
          </div>
        </section>

        {/* Article Header */}
        <section className="py-12 bg-linear-to-b from-[#F5F7FA] to-white">
          <div className="max-w-225 mx-auto px-6">
            <Link
              href="/insights"
              className="inline-flex items-center gap-2 text-[#B8860B] hover:text-[#9A7209] mb-6 transition-colors"
            >
              <ArrowLeft size={18} />
              Back to Insights
            </Link>
            
            <Badge className="mb-4 bg-[#B8860B]/10 text-[#B8860B] hover:bg-[#B8860B]/20">
              {article.category}
            </Badge>
            
            <h1 className="text-3xl md:text-4xl lg:text-5xl font-bold text-[#0B1C2D] mb-6 leading-tight">
              {article.title}
            </h1>
            
            <p className="text-xl text-gray-600 mb-8 leading-relaxed">
              {article.excerpt}
            </p>

            {/* Author and Meta Info */}
            <div className="flex flex-wrap items-center gap-6 pb-8 border-b border-gray-200">
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-full bg-[#0B1C2D] flex items-center justify-center">
                  <User className="text-white" size={20} />
                </div>
                <div>
                  <p className="font-semibold text-[#0B1C2D]">{article.author.name}</p>
                  <p className="text-sm text-gray-500">{article.author.role}</p>
                </div>
              </div>
              
              <div className="flex items-center gap-4 text-sm text-gray-500">
                <span className="flex items-center gap-1">
                  <Calendar size={16} />
                  {article.date}
                </span>
                <span className="flex items-center gap-1">
                  <Clock size={16} />
                  {article.readTime}
                </span>
              </div>

              {/* Share Buttons */}
              <div className="flex items-center gap-2 ml-auto">
                <span className="text-sm text-gray-500 mr-2">Share:</span>
                <button className="p-2 rounded-full hover:bg-[#1877F2]/10 text-[#1877F2] transition-colors" aria-label="Share on Facebook">
                  <Facebook size={18} />
                </button>
                <button className="p-2 rounded-full hover:bg-[#1DA1F2]/10 text-[#1DA1F2] transition-colors" aria-label="Share on Twitter">
                  <Twitter size={18} />
                </button>
                <button className="p-2 rounded-full hover:bg-[#0A66C2]/10 text-[#0A66C2] transition-colors" aria-label="Share on LinkedIn">
                  <Linkedin size={18} />
                </button>
                <button className="p-2 rounded-full hover:bg-gray-100 text-gray-600 transition-colors" aria-label="Share via Email">
                  <Mail size={18} />
                </button>
              </div>
            </div>
          </div>
        </section>

        {/* Article Content */}
        <section className="py-12">
          <div className="max-w-225 mx-auto px-6">
            <article className="prose prose-lg max-w-none">
              {article.content.map((block, index) => {
                if (block.type === "paragraph") {
                  return (
                    <p key={index} className="text-gray-700 leading-relaxed mb-6">
                      {block.text}
                    </p>
                  );
                }
                if (block.type === "heading") {
                  return (
                    <h2 key={index} className="text-2xl font-bold text-[#0B1C2D] mt-10 mb-4">
                      {block.heading}
                    </h2>
                  );
                }
                if (block.type === "list" && block.items) {
                  return (
                    <ul key={index} className="space-y-3 mb-6 ml-0 pl-0">
                      {block.items.map((item, itemIndex) => (
                        <li key={itemIndex} className="flex items-start gap-3 text-gray-700">
                          <CheckCircle className="text-[#B8860B] mt-1 shrink-0" size={18} />
                          <span>{item}</span>
                        </li>
                      ))}
                    </ul>
                  );
                }
                return null;
              })}
            </article>

            {/* Tags */}
            <div className="mt-12 pt-8 border-t border-gray-200">
              <div className="flex items-center gap-2 flex-wrap">
                <Tag size={18} className="text-gray-500" />
                {article.tags.map((tag, index) => (
                  <Badge
                    key={index}
                    variant="outline"
                    className="text-gray-600 border-gray-300 hover:border-[#B8860B] hover:text-[#B8860B] transition-colors cursor-pointer"
                  >
                    {tag}
                  </Badge>
                ))}
              </div>
            </div>

            {/* CTA Box */}
            <Card className="mt-12 bg-linear-to-r from-[#0B1C2D] to-[#1a3a52] border-0">
              <CardContent className="p-8 text-center">
                <h3 className="text-2xl font-bold text-white mb-3">
                  Ready to Source Quality Products from India?
                </h3>
                <p className="text-gray-300 mb-6 max-w-xl mx-auto">
                  Connect with verified manufacturers and start your import journey with Xpecto Global.
                </p>
                <div className="flex flex-col sm:flex-row gap-4 justify-center">
                  <Button asChild className="bg-[#B8860B] hover:bg-[#9A7209] text-white">
                    <Link href="/contact">
                      Get Started
                      <ArrowRight className="ml-2" size={16} />
                    </Link>
                  </Button>
                  <Button asChild variant="outline" className="border-white text-white hover:bg-white/10">
                    <Link href="/products">
                      Browse Products
                    </Link>
                  </Button>
                </div>
              </CardContent>
            </Card>
          </div>
        </section>

        {/* Related Articles */}
        {article.relatedPosts.length > 0 && (
          <section className="py-16 bg-[#F5F7FA]">
            <div className="max-w-360 mx-auto px-6">
              <h2 className="text-2xl md:text-3xl font-bold text-[#0B1C2D] mb-8">
                Related Articles
              </h2>
              <div className="grid md:grid-cols-3 gap-6">
                {article.relatedPosts.map((post, index) => (
                  <Card key={index} className="hover:shadow-lg transition-shadow">
                    <CardContent className="p-6">
                      <Badge
                        variant="outline"
                        className="mb-3 text-[#B8860B] border-[#B8860B]"
                      >
                        {post.category}
                      </Badge>
                      <h3 className="text-lg font-bold text-[#0B1C2D] mb-3 line-clamp-2">
                        {post.title}
                      </h3>
                      <div className="flex items-center justify-between text-sm text-gray-500">
                        <span className="flex items-center gap-1">
                          <Clock size={14} />
                          {post.readTime}
                        </span>
                        <Link
                          href={`/insights/${post.slug}`}
                          className="text-[#B8860B] hover:underline flex items-center gap-1"
                        >
                          Read More
                          <ArrowRight size={14} />
                        </Link>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </div>
          </section>
        )}

        {/* Newsletter Section */}
        <section className="py-20 bg-[#0B1C2D]">
          <div className="max-w-360 mx-auto px-6 text-center">
            <h2 className="text-3xl md:text-4xl font-bold text-white mb-4">
              Stay Updated with Trade Insights
            </h2>
            <p className="text-gray-300 mb-8 max-w-2xl mx-auto">
              Subscribe to our newsletter for the latest industry news, export tips,
              and market analysis delivered to your inbox.
            </p>
            <div className="flex flex-col sm:flex-row gap-4 justify-center max-w-md mx-auto">
              <input
                type="email"
                placeholder="Enter your email"
                className="flex-1 px-4 py-3 rounded-lg bg-white/10 border border-white/20 text-white placeholder:text-gray-400 focus:outline-none focus:border-[#B8860B]"
              />
              <Button className="bg-[#B8860B] hover:bg-[#9A7209] text-white px-8">
                Subscribe
              </Button>
            </div>
          </div>
        </section>
      </div>
    </>
  );
}
