import { createFileRoute, Link, notFound } from "@tanstack/react-router";
import { Button } from "@/components/ui/button";
import { AnimatedSection } from "@/components/AnimatedSection";
import blogGst from "@/assets/blog-gst.jpg";
import blogTaxSavings from "@/assets/blog-tax-savings.jpg";
import blogBookkeeping from "@/assets/blog-bookkeeping.jpg";
import blogMsme from "@/assets/blog-msme.jpg";
import blogTds from "@/assets/blog-tds.jpg";
import blogFssai from "@/assets/blog-fssai.jpg";

const posts: Record<string, { title: string; category: string; date: string; readTime: string; excerpt: string; content: string[] }> = {
  "understanding-gst-filing-deadlines-2025-26": {
    title: "Understanding GST Filing Deadlines for 2025-26",
    category: "GST",
    date: "April 10, 2026",
    readTime: "5 min read",
    excerpt: "Stay compliant with the latest GST return filing deadlines. Here's a complete guide to GSTR-1, GSTR-3B, and annual return due dates for FY 2025-26.",
    content: [
      "GST compliance is one of the most critical aspects of running a business in India. Missing filing deadlines can result in late fees, interest charges, and even penalties that can significantly impact your bottom line.",
      "For FY 2025-26, the GST Council has maintained a structured filing calendar. GSTR-1, which details outward supplies, must be filed by the 11th of each subsequent month for regular taxpayers. For those under the QRMP scheme, the deadline extends to the 13th of the month following each quarter.",
      "GSTR-3B, the summary return for tax payment, is due by the 20th of each subsequent month. Businesses with an annual turnover exceeding ₹5 crore must file monthly, while smaller businesses can opt for quarterly filing under the QRMP scheme.",
      "The annual return GSTR-9 is due by December 31, 2026, for FY 2025-26. Businesses with turnover exceeding ₹5 crore must also file GSTR-9C, a reconciliation statement certified by a CA.",
      "Key tips for staying compliant: Maintain accurate records of all transactions, reconcile your books regularly with GSTR-2A/2B data, set calendar reminders for each deadline, and consider working with a professional tax consultant to ensure timely and accurate filings.",
      "At SKS Associates, we help businesses across Coimbatore stay GST-compliant with our comprehensive filing services. From registration to monthly returns and annual reconciliation, our team ensures you never miss a deadline.",
    ],
  },
  "top-10-tax-saving-strategies-small-businesses": {
    title: "Top 10 Tax-Saving Strategies for Small Businesses in India",
    category: "Income Tax",
    date: "March 28, 2026",
    readTime: "7 min read",
    excerpt: "Discover legitimate ways to reduce your tax liability as a small business owner. From Section 80C to business expense deductions.",
    content: [
      "Tax planning is not about tax evasion — it's about legally optimizing your tax liability using provisions available under the Income Tax Act. Smart tax planning can save your business lakhs of rupees every year.",
      "1. Maximize Section 80C Deductions: Invest in PPF, ELSS, life insurance premiums, and other eligible instruments to claim up to ₹1.5 lakh in deductions. As a business owner, ensure you're utilizing this fully.",
      "2. Claim All Business Expenses: Every legitimate business expense — rent, utilities, salaries, travel, office supplies — reduces your taxable income. Maintain proper documentation and receipts for all expenditures.",
      "3. Depreciation on Assets: Claim depreciation on business assets like computers, furniture, vehicles, and machinery. Accelerated depreciation provisions can provide significant tax benefits in the year of purchase.",
      "4. Presumptive Taxation under Section 44AD: Small businesses with turnover up to ₹2 crore can opt for presumptive taxation, declaring income at 8% of turnover (6% for digital receipts), simplifying compliance significantly.",
      "5. Health Insurance Premiums (Section 80D): Deduct premiums paid for health insurance for yourself, family, and parents. This can save up to ₹75,000 in deductions annually.",
      "6. Home Loan Benefits: If you operate from a home office, you can claim a portion of home loan interest as a business expense, in addition to Section 24 benefits on the housing loan.",
      "7. Digital Payment Incentives: The government offers various incentives for businesses that adopt digital payment methods. Ensure you're taking advantage of lower presumptive taxation rates for digital receipts.",
      "8. Startup Tax Exemptions: If your business qualifies as a startup under DPIIT, you may be eligible for a 3-year tax holiday under Section 80-IAC.",
      "9. Investment in Employee Welfare: Contributions to employee provident fund, gratuity, and group insurance premiums are deductible business expenses that also help retain talent.",
      "10. Professional Tax Consultation: Working with experienced tax consultants like SKS Associates can help identify additional savings opportunities specific to your business structure and industry.",
    ],
  },
  "why-every-business-needs-professional-bookkeeping": {
    title: "Why Every Business Needs Professional Bookkeeping",
    category: "Accounting",
    date: "March 15, 2026",
    readTime: "4 min read",
    excerpt: "Learn how professional bookkeeping can save you time, reduce errors, and help you make better financial decisions for your business.",
    content: [
      "Many small business owners in Coimbatore try to handle their own bookkeeping to save costs. While understandable, this approach often leads to costly mistakes, missed deductions, and poor financial visibility.",
      "Professional bookkeeping provides accurate, up-to-date financial records that serve as the foundation for all business decisions. Without clean books, you're essentially flying blind — making decisions based on gut feeling rather than data.",
      "One of the biggest advantages of professional bookkeeping is error reduction. Trained bookkeepers understand accounting principles, GST requirements, and TDS provisions. They catch discrepancies early, preventing small mistakes from snowballing into major compliance issues.",
      "Time is another crucial factor. As a business owner, every hour spent on bookkeeping is an hour not spent on growing your business. Professional bookkeeping services free you to focus on what you do best — serving your customers and expanding your market.",
      "Professional bookkeeping also improves your relationship with banks and investors. Clean, well-maintained financial records make loan applications smoother and give potential investors confidence in your business management.",
      "At SKS Associates, our bookkeeping services are tailored for Coimbatore businesses of all sizes. We use modern accounting software, provide monthly financial reports, and ensure your books are always audit-ready. Contact us today to learn how we can streamline your financial management.",
    ],
  },
  "msme-registration-benefits-how-to-apply": {
    title: "MSME Registration: Benefits and How to Apply",
    category: "Registration",
    date: "March 5, 2026",
    readTime: "6 min read",
    excerpt: "A complete guide to Udyam registration for micro, small, and medium enterprises. Learn about benefits, eligibility, and the application process.",
    content: [
      "MSME registration (now known as Udyam Registration) is one of the most beneficial registrations available to small businesses in India. It unlocks a wide range of government benefits, subsidies, and protections that can significantly boost your business growth.",
      "The classification is based on investment and turnover: Micro enterprises have investment up to ₹1 crore and turnover up to ₹5 crore. Small enterprises have investment up to ₹10 crore and turnover up to ₹50 crore. Medium enterprises have investment up to ₹50 crore and turnover up to ₹250 crore.",
      "Key Benefits of MSME Registration: Priority sector lending from banks with lower interest rates, typically 1-1.5% lower than standard rates. This alone can save your business significant amounts on loan repayments.",
      "Government tenders often reserve a portion exclusively for MSMEs. With Udyam registration, you gain access to these opportunities, opening up new revenue streams that may not be available to unregistered businesses.",
      "MSMEs enjoy protection under the MSMED Act against delayed payments. If a buyer delays payment beyond 45 days, they're liable to pay compound interest at three times the bank rate. This legal protection ensures your cash flow remains healthy.",
      "The registration process is completely online through the Udyam Registration portal. You'll need your Aadhaar number, PAN, business details, and bank account information. The process is free and the certificate is issued immediately.",
      "SKS Associates has helped hundreds of businesses in Coimbatore obtain their Udyam registration. Our team handles the entire process, from eligibility assessment to documentation and filing. Reach out to us for hassle-free MSME registration.",
    ],
  },
  "tds-compliance-common-mistakes-to-avoid": {
    title: "TDS Compliance: Common Mistakes to Avoid",
    category: "TDS",
    date: "February 20, 2026",
    readTime: "5 min read",
    excerpt: "TDS non-compliance can lead to heavy penalties. Here are the most common mistakes businesses make and how to avoid them.",
    content: [
      "Tax Deducted at Source (TDS) is one of the government's primary mechanisms for tax collection. As a business owner, you're responsible for deducting TDS on various payments and depositing it with the government within specified timelines.",
      "Mistake #1: Not deducting TDS when required. Many businesses, especially smaller ones, are unaware of all the payments that attract TDS — rent exceeding ₹2.4 lakh annually, professional fees above ₹30,000, contractor payments above ₹30,000, and many more. Failure to deduct TDS makes you liable for the tax amount plus interest and penalties.",
      "Mistake #2: Late deposit of TDS. TDS deducted must be deposited by the 7th of the following month (30th April for March deductions). Late deposits attract interest at 1.5% per month from the date of deduction to the date of actual payment.",
      "Mistake #3: Incorrect TDS rates. Different sections prescribe different TDS rates, and these rates change periodically. Using the wrong rate can lead to short deduction, requiring you to pay the difference with interest.",
      "Mistake #4: Not filing TDS returns on time. Quarterly TDS returns (Form 24Q, 26Q, 27Q) must be filed within the prescribed due dates. Late filing attracts a fee of ₹200 per day under Section 234E, which can accumulate to significant amounts.",
      "Mistake #5: PAN-related issues. Not collecting PAN from deductees or quoting incorrect PAN leads to TDS at higher rates (20%) and mismatched credits in the deductee's Form 26AS.",
      "SKS Associates provides comprehensive TDS compliance services, ensuring your business stays penalty-free. From calculating correct TDS amounts to timely filing of returns, we handle it all. Contact us to simplify your TDS compliance.",
    ],
  },
  "fssai-license-requirements-food-businesses-tamil-nadu": {
    title: "FSSAI License: Requirements for Food Businesses in Tamil Nadu",
    category: "Registration",
    date: "February 8, 2026",
    readTime: "6 min read",
    excerpt: "Planning to start a food business? Here's everything you need to know about FSSAI registration and licensing requirements in Tamil Nadu.",
    content: [
      "If you're starting a food business in Tamil Nadu — whether it's a restaurant, bakery, food manufacturing unit, or even a home-based food business — you need an FSSAI license. Operating without one is illegal and can result in penalties up to ₹5 lakh.",
      "FSSAI licensing has three categories based on your business size: Basic Registration (for turnover up to ₹12 lakh and small manufacturers), State License (for turnover between ₹12 lakh and ₹20 crore), and Central License (for turnover above ₹20 crore or businesses operating in multiple states).",
      "Required documents include: identity proof of the Food Business Operator (FBO), proof of business premises (rent agreement or ownership documents), food safety management plan, list of equipment and machinery, and details of all food products to be manufactured or sold.",
      "For restaurants and eateries in Coimbatore, you'll typically need a State License. The application process involves filling Form B on the FSSAI portal, uploading required documents, paying the applicable fee, and awaiting inspection by the local food safety officer.",
      "Key compliance requirements after obtaining the license: Display the license at a prominent location in your premises, print the license number on all food packages, maintain hygiene and food safety standards, and get the license renewed before expiry.",
      "Common reasons for rejection include incomplete documentation, non-compliance with hygiene standards during inspection, and discrepancies in the application. Working with professional consultants can help avoid these pitfalls.",
      "SKS Associates assists food businesses across Coimbatore and Tamil Nadu with FSSAI registration and licensing. From determining the right license category to handling the complete application process, we ensure your food business starts on the right legal footing.",
    ],
  },
};

const slugFromTitle = (title: string) =>
  title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");

const postList = Object.entries(posts).map(([slug, p]) => ({ slug, ...p }));

export const Route = createFileRoute("/blog/$slug")({
  head: ({ params }) => {
    const post = posts[params.slug];
    const title = post ? `${post.title} — SKS Associates Blog` : "Post Not Found";
    const desc = post?.excerpt || "";
    return {
      meta: [
        { title },
        { name: "description", content: desc },
        { property: "og:title", content: title },
        { property: "og:description", content: desc },
      ],
    };
  },
  component: BlogDetailPage,
  notFoundComponent: () => (
    <div className="min-h-screen flex items-center justify-center">
      <div className="text-center">
        <h1 className="text-4xl font-bold font-heading mb-4">Post Not Found</h1>
        <p className="text-muted-foreground mb-8">The blog post you're looking for doesn't exist.</p>
        <Link to="/blog"><Button variant="gold">Back to Blog</Button></Link>
      </div>
    </div>
  ),
});

function BlogDetailPage() {
  const { slug } = Route.useParams();
  const post = posts[slug];

  if (!post) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-4xl font-bold font-heading mb-4">Post Not Found</h1>
          <Link to="/blog"><Button variant="gold">Back to Blog</Button></Link>
        </div>
      </div>
    );
  }

  const heroCategoryColors: Record<string, string> = {
    GST: "bg-accent/25 text-[#00F3FF] border border-[#00F3FF]/30",
    "Income Tax": "bg-gold/25 text-gold border border-gold/30",
    Accounting: "bg-emerald-500/25 text-emerald-300 border border-emerald-500/30",
    Registration: "bg-purple-500/25 text-purple-300 border border-purple-500/30",
    TDS: "bg-orange-500/25 text-orange-300 border border-orange-500/30",
  };

  const cardCategoryColors: Record<string, string> = {
    GST: "bg-accent/20 text-accent",
    "Income Tax": "bg-navy/10 text-navy",
    Accounting: "bg-gold/20 text-gold-foreground",
    Registration: "bg-secondary text-secondary-foreground",
    TDS: "bg-accent/20 text-accent",
  };

  const postImages: Record<string, string> = {
    "understanding-gst-filing-deadlines-2025-26": blogGst,
    "top-10-tax-saving-strategies-small-businesses": blogTaxSavings,
    "why-every-business-needs-professional-bookkeeping": blogBookkeeping,
    "msme-registration-benefits-how-to-apply": blogMsme,
    "tds-compliance-common-mistakes-to-avoid": blogTds,
    "fssai-license-requirements-food-businesses-tamil-nadu": blogFssai,
  };

  const related = postList.filter((p) => p.slug !== slug).slice(0, 3);

  return (
    <div>
      {/* Hero */}
      <section className="gradient-hero py-20 md:py-28">
        <div className="mx-auto max-w-4xl px-4 sm:px-6 lg:px-8">
          <AnimatedSection>
            <Link to="/blog" className="inline-flex items-center gap-2 text-primary-foreground/60 hover:text-primary-foreground transition-colors mb-6 group">
              <svg className="w-4 h-4 group-hover:-translate-x-1 transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" /></svg>
              Back to Blog
            </Link>
            <div className="flex items-center gap-3 mb-4">
              <span className={`px-3 py-1 rounded-full text-xs font-semibold ${heroCategoryColors[post.category] || "bg-muted text-muted-foreground"}`}>
                {post.category}
              </span>
              <span className="text-primary-foreground/50 text-sm">{post.date}</span>
              <span className="text-primary-foreground/50 text-sm">·</span>
              <span className="text-primary-foreground/50 text-sm">{post.readTime}</span>
            </div>
            <h1 className="text-3xl md:text-4xl lg:text-5xl font-bold font-heading text-primary-foreground leading-tight">
              {post.title}
            </h1>
            <p className="mt-6 text-lg text-primary-foreground/70 leading-relaxed">
              {post.excerpt}
            </p>
          </AnimatedSection>
        </div>
      </section>

      {/* Content */}
      <section className="py-16 md:py-24">
        <div className="mx-auto max-w-3xl px-4 sm:px-6 lg:px-8">
          <AnimatedSection>
            <div className="prose prose-lg max-w-none">
              {post.content.map((paragraph, i) => (
                <p key={i} className="text-foreground/80 leading-relaxed mb-6 text-base md:text-lg">
                  {paragraph}
                </p>
              ))}
            </div>
          </AnimatedSection>

          {/* Author card */}
          <AnimatedSection delay={0.2}>
            <div className="mt-16 glass-card rounded-xl p-6 md:p-8 flex flex-col sm:flex-row items-center gap-6">
              <div className="w-20 h-20 rounded-full gradient-gold flex items-center justify-center shrink-0">
                <span className="text-2xl font-bold font-heading text-gold-foreground">SS</span>
              </div>
              <div>
                <p className="text-sm text-muted-foreground uppercase tracking-wider mb-1">Written by</p>
                <h3 className="text-lg font-bold font-heading text-foreground">S. Sangaiah</h3>
                <p className="text-muted-foreground text-sm mt-1">
                  Founder of SKS Associates with 4+ years of experience in tax consulting, GST compliance, and business registration services across Coimbatore.
                </p>
              </div>
            </div>
          </AnimatedSection>

          {/* CTA */}
          <AnimatedSection delay={0.3}>
            <div className="mt-12 gradient-navy rounded-xl p-8 md:p-10 text-center">
              <h3 className="text-2xl font-bold font-heading text-primary-foreground mb-3">
                Need Help With {post.category}?
              </h3>
              <p className="text-primary-foreground/70 mb-6 max-w-md mx-auto">
                Get personalized guidance from our experts. We'll help you navigate the complexities.
              </p>
              <Link to="/contact">
                <Button variant="hero" size="lg">Get Free Consultation</Button>
              </Link>
            </div>
          </AnimatedSection>
        </div>
      </section>

      {/* Related Posts */}
      <section className="py-16 md:py-24 bg-secondary/50">
        <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
          <AnimatedSection>
            <h2 className="text-2xl md:text-3xl font-bold font-heading text-center mb-12">
              More <span className="text-gradient-gold">Insights</span>
            </h2>
          </AnimatedSection>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            {related.map((rp, i) => (
              <AnimatedSection key={rp.slug} delay={i * 0.1}>
                <Link to="/blog/$slug" params={{ slug: rp.slug }} className="block h-full">
                  <article className="glass-card rounded-xl overflow-hidden hover-lift h-full flex flex-col group">
                    <div className="h-48 overflow-hidden">
                      <img
                        src={postImages[rp.slug]}
                        alt={rp.title}
                        loading="lazy"
                        width={800}
                        height={512}
                        className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
                      />
                    </div>
                    <div className="p-6 flex-1 flex flex-col">
                      <div className="flex items-center gap-2 mb-3">
                        <span className={`px-2.5 py-0.5 rounded-full text-xs font-medium ${cardCategoryColors[rp.category] || "bg-muted text-muted-foreground"}`}>
                          {rp.category}
                        </span>
                        <span className="text-xs text-muted-foreground">{rp.readTime}</span>
                      </div>
                      <h3 className="text-lg font-bold font-heading text-foreground group-hover:text-accent transition-colors line-clamp-2">
                        {rp.title}
                      </h3>
                      <p className="mt-2 text-sm text-muted-foreground leading-relaxed flex-1 line-clamp-3">
                        {rp.excerpt}
                      </p>
                      <div className="mt-4 pt-4 border-t border-border flex items-center justify-between">
                        <span className="text-xs text-muted-foreground">{rp.date}</span>
                        <span className="text-sm font-medium text-accent group-hover:underline">Read More →</span>
                      </div>
                    </div>
                  </article>
                </Link>
              </AnimatedSection>
            ))}
          </div>
        </div>
      </section>
    </div>
  );
}
