import React, { useState, useEffect } from 'react';
import { Plus, Minus, HelpCircle, Mail } from 'lucide-react';
import { PrimaryCTAButton } from '../components/PrimaryCTAButton';
import { useNavigate } from 'react-router-dom';
import { useGetFaqsQuery, useGetFaqCategoriesQuery } from '../redux/services/faqApi';

interface FAQItemProps {
  question: string;
  answer: string;
  isOpen: boolean;
  onToggle: () => void;
  tags?: Array<{ tag_name: string; display_order: number }>;
}

interface FAQItemData {
  id: string;
  question: string;
  answer: string;
  content_status: string;
  content_category_xid: string;
  content_category: {
    id: string;
    category_name: string;
  };
  faq_tags: Array<{
    id: string;
    tag_name: string;
    display_order: number;
  }>;
  created_at: string;
  updated_at: string;
}

interface CategoryData {
  id: string;
  category_name: string;
  display_order: number;
  for_faq: boolean;
  for_blog: boolean;
}

const FAQItem: React.FC<FAQItemProps> = ({ question, answer, isOpen, onToggle, tags }) => {
  return (
    <div className="bg-white border border-gray-200 rounded-lg p-6 mb-4 transition-all duration-300 hover:shadow-md">
      <button
        onClick={onToggle}
        className="w-full text-left flex items-center justify-between"
      >
        <h3 className="text-h4 pr-4" style={{ color: 'var(--color-black)' }}>
          {question}
        </h3>
        <div className="flex-shrink-0 ml-4">
          {isOpen ? (
            <Minus
              className="w-5 h-5 transition-transform duration-200"
              style={{ color: 'var(--color-primary)' }}
            />
          ) : (
            <Plus
              className="w-5 h-5 transition-transform duration-200"
              style={{ color: 'var(--color-primary)' }}
            />
          )}
        </div>
      </button>

      <div
        className={`overflow-hidden transition-all duration-300 ease-out ${isOpen ? 'max-h-96 opacity-100 mt-4' : 'max-h-0 opacity-0'
          }`}
      >
        <p className="text-body-lg leading-relaxed mb-4" style={{ color: 'var(--color-black)' }}>
          {answer}
        </p>

        {/* Display tags if available */}
        {tags && tags.length > 0 && (
          <div className="flex flex-wrap gap-2 mt-3">
            {tags.map((tag, index) => (
              <span
                key={index}
                className="px-3 py-1 bg-gray-100 text-gray-600 rounded-full text-small"
              >
                {tag.tag_name}
              </span>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export function FAQ() {
  const [openItems, setOpenItems] = useState<string[]>([]);
  const [activeCategory, setActiveCategory] = useState<string>('all');
  const [filteredFaqs, setFilteredFaqs] = useState<FAQItemData[]>([]);
  const navigate = useNavigate();

  // Fetch FAQ categories
  const {
    data: categoriesResponse,
    isLoading: isLoadingCategories
  } = useGetFaqCategoriesQuery({
    limit: 100,
    offset: 0
  });

  // Fetch FAQs with publish status
  const {
    data: faqResponse,
    isLoading: isLoadingFaqs,
    isError,
    refetch
  } = useGetFaqsQuery({
    content_status: 'publish',
    limit: 20
  });

  // Filter categories to only those marked for FAQ
  const categories = [
    { id: 'all', label: 'All Questions' },
    ...(categoriesResponse?.data?.items
      ?.filter((category: CategoryData) => category.for_faq)
      .map((category: CategoryData) => ({
        id: category.id, // Use the actual category ID
        label: category.category_name,
        display_order: category.display_order
      }))
      .sort((a:any, b:any) => (a.display_order || 0) - (b.display_order || 0)) || [])
  ];

  // Filter FAQs based on active category
  useEffect(() => {
    if (faqResponse?.data?.items) {
      if (activeCategory === 'all') {
        setFilteredFaqs(faqResponse.data.items);
      } else {
        // Filter by content_category_xid using the actual category ID
        const filtered = faqResponse.data.items.filter(
          (item: FAQItemData) => item.content_category_xid === activeCategory
        );
        setFilteredFaqs(filtered);
      }
    }
  }, [activeCategory, faqResponse]);

  const toggleItem = (id: string) => {
    setOpenItems(prev =>
      prev.includes(id)
        ? prev.filter(i => i !== id)
        : [...prev, id]
    );
  };

  // Handle loading state
  if (isLoadingFaqs || isLoadingCategories) {
    return (
      <div style={{ backgroundColor: '#FFFFFF' }} className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto"></div>
          <p className="mt-4 text-gray-600">Loading FAQs...</p>
        </div>
      </div>
    );
  }

  // Handle error state
  if (isError) {
    return (
      <div style={{ backgroundColor: '#FFFFFF' }} className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <HelpCircle className="w-16 h-16 text-red-500 mx-auto mb-4" />
          <h2 className="text-h3 mb-2">Failed to load FAQs</h2>
          <p className="text-gray-600 mb-4">Please try again later</p>
          <PrimaryCTAButton
            text="Retry"
            onClick={() => refetch()}
            className="cta-text-black"
          />
        </div>
      </div>
    );
  }

  return (
    <div style={{ backgroundColor: '#FFFFFF' }} className="min-h-screen">
      {/* Header Section */}
      <section className="py-20 section-margin-x">
        <div className="max-w-4xl mx-auto">
          {/* Main Heading */}
          <h1 className="text-h1 mb-6" style={{ color: 'var(--color-black)' }}>
            FAQs
          </h1>

          {/* Description */}
          <p className="text-body-lg mb-8 leading-relaxed" style={{ color: 'var(--color-gray-muted)' }}>
            Everything you need to know about features, membership, and troubleshooting.
          </p>

          {/* Category Filter Tags - Only show if there are categories */}
          {categories.length > 1 && (
            <div className="flex flex-wrap gap-3 mb-8">
              {categories.map((category) => (
                <button
                  key={category.id}
                  onClick={() => setActiveCategory(category.id)}
                  className={`px-4 py-2 rounded-full text-small font-medium transition-all duration-200 ${activeCategory === category.id
                      ? 'text-white'
                      : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                    }`}
                  style={{
                    backgroundColor: activeCategory === category.id ? 'var(--color-primary)' : undefined,
                    color: activeCategory === category.id ? 'white' : undefined
                  }}
                >
                  {category.label}
                </button>
              ))}
            </div>
          )}
        </div>
      </section>

      {/* FAQ Section */}
      <section className="pb-20 section-margin-x">
        <div className="max-w-4xl mx-auto">
          {filteredFaqs.length > 0 ? (
            <div className="space-y-0">
              {filteredFaqs.map((faq) => (
                <FAQItem
                  key={faq.id}
                  question={faq.question}
                  answer={faq.answer}
                  // tags={faq.faq_tags} 
                  isOpen={openItems.includes(faq.id)}
                  onToggle={() => toggleItem(faq.id)}
                />
              ))}
            </div>
          ) : (
            <div className="text-center py-12">
              <HelpCircle className="w-16 h-16 text-gray-400 mx-auto mb-4" />
              <h3 className="text-h4 mb-2">No FAQs found</h3>
              <p className="text-gray-600">
                {activeCategory === 'all'
                  ? 'No published FAQs available at the moment.'
                  : 'No FAQs available in this category.'}
              </p>
            </div>
          )}
        </div>
      </section>

      {/* Contact Support Section */}
      <section className="py-16 section-margin-x">
        <div className="max-w-4xl mx-auto">
          <div className="bg-white border border-gray-200 rounded-xl p-8 text-center">
            <div className="w-16 h-16 mx-auto mb-6 rounded-full flex items-center justify-center" style={{ backgroundColor: 'var(--color-primary)' }}>
              <HelpCircle className="w-8 h-8" style={{ color: 'white' }} />
            </div>

            <h2 className="text-h3 mb-4" style={{ color: 'var(--color-black)' }}>
              Still have questions?
            </h2>

            <p className="text-body-lg mb-8 max-w-2xl mx-auto" style={{ color: 'var(--color-gray-muted)' }}>
              Can't find the answer you're looking for? Our support team is here to help you with any questions
              about our leadership development programs and services.
            </p>

            <div className="flex flex-col sm:flex-row gap-4 justify-center items-center">
              <PrimaryCTAButton
                text="Contact Support"
                onClick={() => navigate('/contact')}
                className="cta-text-black"
              />

              <a
                href="mailto:connect@leadershipcentre.in"
                className="flex items-center gap-2 px-6 py-3 text-body-lg transition-colors duration-200 hover:bg-gray-50 rounded-lg"
                style={{ color: 'var(--color-primary)' }}
              >
                <Mail className="w-5 h-5" />
                connect@leadershipcentre.in
              </a>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}