"use client";

import React, { useState, useEffect, useRef } from "react";
import Navbar from "@/components/Navbar";
import Breadcrumbs from "@/components/Breadcrumbs";
import Footer from "@/components/Footer";
import Image from "next/image";
import { ChevronDown, Search, HelpCircle, Layers, ShieldAlert, Sparkles } from "lucide-react";
import gsap from "gsap";

const faqCategories = [
    { id: "all", name: "All Questions", icon: <HelpCircle className="w-4 h-4" /> },
    { id: "basics", name: "Product Basics", icon: <Layers className="w-4 h-4" /> },
    { id: "technical", name: "Technical & ASA", icon: <ShieldAlert className="w-4 h-4" /> },
    { id: "health-durability", name: "Health & Performance", icon: <Sparkles className="w-4 h-4" /> }
];

const faqs = [
    {
        category: "basics",
        question: "What is i-Roof?",
        answer: "i-roof is a revolutionary polymer based roofing sheet introduced to Sri Lanka. This Spanish style roofing sheet is unique, strong and consists of 4 special layers."
    },
    {
        category: "basics",
        question: "What is i-Roof made of?",
        answer: "The top layer of the sheet is made of ASA material (Acrylonitrile Styrene Acrylate) while the other three layers consist of special PVC material."
    },
    {
        category: "technical",
        question: "What is special in ASA?",
        answer: "The ASA (Acrylonitrile Styrene Acrylate) is a high tech formula that has higher resistance towards sun heat. This special material is used even on satellites to avoid heat and UV rays in the space."
    },
    {
        category: "technical",
        question: "What is ASA doing in i-Roof?",
        answer: "The ASA layer of the i-roof reduces the heat inside the home and cuts off harmful UV rays. So that it preserves the roof colour as well as provides further durability to the roof (Extended life time) while maintaining a cool and comfortable environment inside the home."
    },
    {
        category: "technical",
        question: "Can roofing sheets be made without ASA?",
        answer: "Yes. Roofing sheets can be made without an ASA layer. There are lots of PVC roofing products made without an ASA layer and made of second grade raw materials available in the market. The appearance of these fake products is similar to i-Roof. But due to the usage of inferior quality raw materials and the non-availability of the ASA layer, these fake products do not last long. Hence, always insist on i-Roof branded roofing sheets where the quality is a consistent norm and guaranteed."
    },
    {
        category: "technical",
        question: "Is i-Roof an imported product?",
        answer: "i-Roof is manufactured in Sri Lanka at a highly sophisticated production facility with German technology. All the raw materials utilised in the production are imported from an associate company of world-renowned LG Company of Korea."
    },
    {
        category: "health-durability",
        question: "Are there health effects in living in a home with i-Roof roofing?",
        answer: "i-Roof is a 100% environmentally friendly and hygienic product. This unique product does not contain any cancerous material or any other harmful material to any living being. And further, this product does not discharge any radioactive rays which are harmful to human health. So living in a home with a i-Roof Roofing is free of any health issues and ensures healthy living with confidence."
    },
    {
        category: "basics",
        question: "What are the dimensions available in i-Roof?",
        answer: "The standard width of i-roof is 3 feet and 5 inches and available in 10 different lengths from 5’ 9” to 24’5”. This remarkable availability in 10 different lengths ensures cost savings through zero or minimum wastage, and a 100% waterproof roof by using a single sheet for the full length requirement."
    },
    {
        category: "basics",
        question: "Is i-Roof confined to a single colour option?",
        answer: "No. i-Roof is available in 4 different colours that can be chosen as per individual interests: Brick Red, Chocolate Brown, Dark Green, and White."
    },
    {
        category: "basics",
        question: "Are accessories available?",
        answer: "Yes. All the accessories to fabricate any roof design are adequately available in all our Sivilima showrooms."
    },
    {
        category: "health-durability",
        question: "What is the strength and the durability of i-Roof?",
        answer: "There is no other roofing product in the Sri Lankan market that can be compared with the strength and the durability of the i-Roof roofing sheet. The unbelievable load bearing capacity of the i-Roof sheet has been proven by driving a vehicle of 3 tons weight on the sheet."
    },
    {
        category: "health-durability",
        question: "Can animals like monkeys damage the roof?",
        answer: "No. i-Roof is totally an animal resistant roofing solution. Due to the rigidness of the sheet, no animal can damage or deteriorate the shape of the roofing sheets or accessories."
    },
    {
        category: "health-durability",
        question: "Is it a noisy rain roof?",
        answer: "No. i-Roof is a perfect sound insulation roofing solution. The special ASA layer with other three layers function as a sound barrier and lower the noise of the rain falling on the roof. So a calm and quiet environment is maintained inside the home during the rainy seasons."
    },
    {
        category: "health-durability",
        question: "Does color fading, dust accumulation, or moss growth affect i-Roof over time?",
        answer: "No. i-Roof possesses the special characteristic of a self-cleaning mechanism when it rains. The special ASA layer assures color fastness of the roof for years and resistance to moss gathering."
    },
    {
        category: "technical",
        question: "Is i-Roof a fire spreading material or affected by acid rain and other chemicals?",
        answer: "No. The Industrial Technology Institute of Sri Lanka (ITI) has tested i-Roof and has certified that this product is fire retardant and unresponsive to acid rains or any other chemical contaminations."
    },
    {
        category: "technical",
        question: "Can i-Roof be used in coastal areas?",
        answer: "Absolutely yes. Since this is not a metal base product that tends to corrosion, it is the ideal roofing solution for coastal areas."
    },
    {
        category: "technical",
        question: "Is i-Roof heavier than other types of roofing sheets?",
        answer: "No. The maximum weight of 1 Sq.Ft of i-Roof is 500 grams. Hence, it is 8 times lighter than traditional clay tiles. So the structural material consumption is comparatively low giving a time and money saving (The recommended length of rafters and purlins is 30”). Due to the non-absorbent nature of this product, a constant weight is maintained during the rainy season as well as the dry season."
    },
    {
        category: "health-durability",
        question: "Other benefits that i-Roof customers can enjoy?",
        answer: "• Issuance of a certificate that certifies the usage of high quality raw material and manufactured in highest standards\n• Easy ordering process through Sivilima Store\n• Technical support and information pertaining to i-Roof is freely available when and where required."
    },
    {
        category: "basics",
        question: "How to purchase i-Roof?",
        answer: "There are several methods for purchasing i-Roof:\nI. Orders for i-Roof can be placed through Sivilima Store\nII. i-Roof can be purchased from all the Sivilima showrooms island wide."
    },
    {
        category: "health-durability",
        question: "What is the warranty period for i-Roof?",
        answer: "i-Roof comes with a comprehensive 20-year structural warranty, ensuring long-term peace of mind and guaranteed protection for your home."
    },
    {
        category: "technical",
        question: "How does i-Roof compare with clay tiles in cost?",
        answer: "While the initial purchase cost of i-Roof is competitive, it offers massive savings in construction costs. Since it is 8 times lighter than clay tiles, it requires less timber and structural support, leading to a much lower overall cost."
    },
    {
        category: "basics",
        question: "Is professional training required to install i-Roof sheets?",
        answer: "No, i-Roof is designed for easy installation and can be installed by any standard carpenter or roofer. We also provide free installation manuals and technical support at Sivilima showrooms."
    },
    {
        category: "technical",
        question: "Are custom sizes and colors available for large-scale projects?",
        answer: "Yes, for qualified commercial or industrial projects, we can manufacture custom lengths and custom color options. Please contact our technical sales desk via the Contact Page for consultations."
    }
];

export default function FAQPage() {
    const mainRef = useRef<HTMLDivElement>(null);
    const [searchQuery, setSearchQuery] = useState("");
    const [selectedCategory, setSelectedCategory] = useState("all");
    const [expandedIndex, setExpandedIndex] = useState<number | null>(null);

    useEffect(() => {
        // Hero Page Animations
        const ctx = gsap.context(() => {
            gsap.from(".faq-hero-badge", { y: 20, opacity: 0, delay: 0.2, duration: 1, ease: "power3.out" });
            gsap.from(".faq-hero-title", { y: 40, opacity: 0, delay: 0.4, duration: 1.2, ease: "power3.out" });
            gsap.from(".faq-hero-desc", { y: 25, opacity: 0, delay: 0.6, duration: 1.2, ease: "power3.out" });
        }, mainRef);
        return () => ctx.revert();
    }, []);

    const filteredFaqs = faqs.filter(faq => {
        const matchesCategory = selectedCategory === "all" || faq.category === selectedCategory;
        const matchesSearch = faq.question.toLowerCase().includes(searchQuery.toLowerCase()) || 
                              faq.answer.toLowerCase().includes(searchQuery.toLowerCase());
        return matchesCategory && matchesSearch;
    });

    const toggleAccordion = (index: number) => {
        setExpandedIndex(expandedIndex === index ? null : index);
    };

    const renderAnswer = (text: string) => {
        if (text.includes("•")) {
            const lines = text.split("\n");
            return (
                <ul className="list-disc pl-5 space-y-2 mt-2 font-sans text-zinc-500 text-sm">
                    {lines.map((line, idx) => (
                        <li key={idx} className="leading-relaxed">
                            {line.replace("•", "").trim()}
                        </li>
                    ))}
                </ul>
            );
        }
        if (text.includes("I. ") || text.includes("II. ")) {
            const lines = text.split("\n");
            return (
                <ol className="list-decimal pl-5 space-y-2 mt-2 font-sans text-zinc-500 text-sm">
                    {lines.map((line, idx) => {
                        const cleanLine = line.replace(/^\s*(?:[I|V|X]+)\.\s*/i, "").trim();
                        if (!cleanLine) return null;
                        return (
                            <li key={idx} className="leading-relaxed">
                                {cleanLine}
                            </li>
                        );
                    })}
                </ol>
            );
        }
        return (
            <p className="text-zinc-500 text-sm leading-relaxed font-sans">
                {text}
            </p>
        );
    };

    return (
        <main ref={mainRef} className="min-h-screen bg-white text-zinc-950 selection:bg-brand-accent selection:text-white">
            <Navbar />

            {/* HERO SECTION */}
            <section className="relative pt-32 pb-24 md:pt-48 md:pb-32 overflow-hidden bg-brand-dark min-h-[45vh] flex items-center">
                <div className="absolute inset-0 z-0">
                    <Image
                        src="/images/pexels9.webp"
                        alt="iRoof FAQ Background"
                        fill
                        className="object-cover opacity-45 mix-blend-overlay"
                        priority
                    />
                    <div className="absolute inset-0 bg-gradient-to-t from-brand-dark via-brand-dark/80 to-transparent" />
                </div>

                <div className="max-w-[1400px] mx-auto px-6 relative z-10 w-full text-center">
                    <div className="max-w-4xl mx-auto flex flex-col items-center">
                        <div className="faq-hero-badge flex items-center justify-center gap-4 mb-6 group">
                            <div className="h-[1.5px] w-8 md:w-12 bg-brand-accent group-hover:w-16 transition-all duration-700" />
                            <span className="text-[10px] md:text-[11px] font-semibold text-brand-accent uppercase tracking-[0.3em] md:tracking-[0.4em]">
                                FAQ Center
                            </span>
                            <div className="h-[1.5px] w-8 md:w-12 bg-brand-accent group-hover:w-16 transition-all duration-700" />
                        </div>
                        <h1 className="faq-hero-title text-4xl md:text-6xl lg:text-7xl font-semibold text-white tracking-tighter leading-[1.1] mb-6 font-heading">
                            How Can We <span className="text-brand-accent">Help You?</span>
                        </h1>
                        <p className="faq-hero-desc text-sm md:text-base text-zinc-300 max-w-2xl font-light leading-relaxed font-sans">
                            Find clear, detailed answers about iRoof's revolutionary ASA polymer roofing sheets, certifications, durability, and purchasing information.
                        </p>
                    </div>
                </div>
            </section>

            {/* BREADCRUMBS & CONTENT SECTION */}
            <section className="py-16 bg-white relative">
                <div className="max-w-[1400px] mx-auto px-6 mb-8">
                    <Breadcrumbs items={[{ label: "FAQ" }]} />
                </div>

                <div className="max-w-[1000px] mx-auto px-6">
                    {/* SEARCH & FILTER CONTROLS */}
                    <div className="flex flex-col md:flex-row items-center justify-between gap-6 mb-12 border-b border-zinc-100 pb-8">
                        {/* Search Input */}
                        {/* <div className="relative w-full md:max-w-md">
                            <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-400" />
                            <input
                                type="text"
                                placeholder="Search questions or keywords..."
                                value={searchQuery}
                                onChange={(e) => {
                                    setSearchQuery(e.target.value);
                                    setExpandedIndex(null); // Reset open accordion on search
                                }}
                                className="w-full pl-11 pr-4 py-3 rounded-xl border border-zinc-200 bg-zinc-50 text-sm focus:outline-none focus:ring-2 focus:ring-brand-accent/20 focus:border-brand-accent focus:bg-white transition-all text-zinc-800 placeholder-zinc-400 font-sans"
                            />
                        </div> */}

                        {/* Category Tabs */}
                        <div className="flex flex-wrap gap-2 w-full md:w-auto justify-start md:justify-end">
                            {faqCategories.map((cat) => (
                                <button
                                    key={cat.id}
                                    onClick={() => {
                                        setSelectedCategory(cat.id);
                                        setExpandedIndex(null); // Reset open accordion on category change
                                    }}
                                    className={`flex items-center gap-2 px-4 py-2.5 rounded-xl text-xs font-bold uppercase tracking-wider transition-all duration-300 ${
                                        selectedCategory === cat.id
                                            ? "bg-brand-accent text-white shadow-md shadow-brand-accent/15"
                                            : "bg-zinc-50 text-zinc-500 border border-zinc-200/50 hover:bg-zinc-100 hover:text-zinc-800"
                                    }`}
                                >
                                    {cat.icon}
                                    <span>{cat.name}</span>
                                </button>
                            ))}
                        </div>
                    </div>

                    {/* FAQ ACCORDION GRID */}
                    {filteredFaqs.length > 0 ? (
                        <div className="space-y-4">
                            {filteredFaqs.map((faq, idx) => {
                                const isExpanded = expandedIndex === idx;
                                return (
                                    <div
                                        key={idx}
                                        className={`border rounded-2xl bg-white overflow-hidden transition-all duration-500 ${
                                            isExpanded
                                                ? "border-brand-accent/30 shadow-lg shadow-brand-accent/5"
                                                : "border-zinc-200/80 hover:border-zinc-300"
                                        }`}
                                    >
                                        <button
                                            onClick={() => toggleAccordion(idx)}
                                            className="w-full px-6 md:px-8 py-5 md:py-6 flex items-center justify-between text-left focus:outline-none"
                                        >
                                            <span
                                                className={`text-sm md:text-md font-semibold tracking-tight transition-colors duration-300 font-heading ${
                                                    isExpanded ? "text-brand-accent" : "text-zinc-800"
                                                }`}
                                            >
                                                {faq.question}
                                            </span>
                                            <div
                                                className={`w-8 h-8 rounded-full flex items-center justify-center transition-all duration-500 shrink-0 ml-4 ${
                                                    isExpanded
                                                        ? "bg-brand-accent/10 text-brand-accent rotate-180"
                                                        : "bg-zinc-50 text-zinc-400 group-hover:bg-zinc-100"
                                                }`}
                                            >
                                                <ChevronDown className="w-4 h-4" />
                                            </div>
                                        </button>

                                        {/* Dynamic Expandable Height Container */}
                                        <div
                                            className={`transition-all duration-500 ease-in-out overflow-hidden`}
                                            style={{
                                                maxHeight: isExpanded ? "500px" : "0px",
                                                opacity: isExpanded ? 1 : 0
                                            }}
                                        >
                                            <div className="px-6 md:px-8 pb-6 md:pb-8 border-t border-zinc-100/80 pt-4 bg-zinc-50/50">
                                                {renderAnswer(faq.answer)}
                                            </div>
                                        </div>
                                    </div>
                                );
                            })}
                        </div>
                    ) : (
                        <div className="text-center py-16 bg-zinc-50 rounded-2xl border border-dashed border-zinc-200">
                            <HelpCircle className="w-12 h-12 text-zinc-300 mx-auto mb-4" />
                            <h3 className="text-md font-bold text-zinc-700 mb-1 font-heading">No questions found</h3>
                            <p className="text-xs text-zinc-400 font-sans">
                                We couldn't find any FAQs matching "{searchQuery}". Try using different terms.
                            </p>
                        </div>
                    )}
                </div>
            </section>

            <Footer />
        </main>
    );
}
