"use client";
import Image from "next/image";
import React, { useState, useEffect } from "react";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion";
import Link from "next/link";
import axios from "axios";
import { backendUrl } from "@/utils/axios";

const DEFAULT_IMAGE = "/sidhi-mala/Designer_30.png"; // Default image

const FaqCard = ({ params }) => {
  const [faq, setFaq] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchFaq = async () => {
      try {
        const response = await axios.get(
          `${backendUrl}/products/faq/${params.id}/`
        );
        setFaq(response.data);
      } catch (err) {
        setError("Failed to fetch FAQs. Please try again later.");
      } finally {
        setLoading(false);
      }
    };

    fetchFaq();
  }, [params.id]);

  if (loading) {
    return <p className="text-center text-xl mt-10">Loading FAQs...</p>;
  }

  if (error) {
    return <p className="text-center text-red-600 mt-10">{error}</p>;
  }

  if (!faq || faq.length === 0) {
    return <p className="text-center text-xl mt-10">No FAQs available.</p>;
  }

  const hasImage = faq.some((item) => item.image !== null);
  const imageToShow = hasImage
    ? `${backendUrl}${faq.find((item) => item.image !== null).image}`
    : DEFAULT_IMAGE;
  return (
    <div className="min-h-screen sm:block hidden bg-[#FFFFFF]">
      <h1 className="sm:pt-14 pb-8 font-serif mt-4 sm:text-6xl text-2xl text-zinc-800 text-center">
        Frequently Asked Questions
      </h1>
      <div className="min-h-[80%] flex">
        <Image
          src={imageToShow}
          height={600}
          width={400}
          alt="FAQ Image"
          className="h-[550px] w-[550px] ml-14"
        />
        <div className="flex-1 p-8">
          {faq.map((item, index) => (
            <Accordion type="single" collapsible className="w-full" key={index}>
              <AccordionItem value={item.question}>
                <AccordionTrigger className="text-xl mb-5 font-semibold text-zinc-900 hover:no-underline">
                  {item.question}
                </AccordionTrigger>
                <AccordionContent className="text-zinc-700">
                  {item.answer}
                </AccordionContent>
              </AccordionItem>
            </Accordion>
          ))}
        </div>
      </div>
      <div className="h-[30vh] sm:block hidden m-9">
        <h2 className="my-6 text-2xl font-semibold w-[350px]">
          Quick Answers to Some Frequently Asked Questions.
        </h2>
        <Link href={"/pages/contact"}>
          <button className="px-4 py-4 border font-semibold border-black">
            Get Support
          </button>
        </Link>
      </div>
    </div>
  );
};

export default FaqCard;
