'use client';

import Image from 'next/image';
import Link from 'next/link';
import { useState, useEffect } from 'react';
import { CommonHeader } from '@/components/layout/CommonHeader';
import { Footer } from '@/components/layout/Footer';
import { cmsService, resolveImageUrl } from '@/services/cms.service';
import { FaqContent, FaqCategoryItem, FaqItem, CmsContentRecord } from '@/types/cms';

const defaultCategories: FaqCategoryItem[] = [
  { id: 'all', label: 'All Questions' },
  { id: 'agent', label: 'Agent Resources' },
  { id: 'buying', label: 'Buying a Home' },
  { id: 'selling', label: 'Selling a Home' },
  { id: 'platform', label: 'Platform & Account' },
];

const defaultFaqs: FaqItem[] = [
  {
    id: 1,
    icon: '/assets/icons/home-icon.svg',
    question: 'How do I update my listing status?',
    answer: 'To update your listing status, log in to your Agent Dashboard. Locate the property in your "Active Listings" tab, click the three-dot menu on the right, and select "Update Status." You can change it to Pending, Sold, or Temporarily Off Market. Changes are reflected immediately.',
    category: 'agent',
  },
  {
    id: 2,
    icon: '/assets/icons/wallet-icon.svg',
    question: 'What is the pre-approval process?',
    answer: 'The pre-approval process involves submitting your financial documents to a lender who will review your credit history, income, assets, and debts. Once approved, you\'ll receive a pre-approval letter stating how much you can borrow, which strengthens your position when making offers on properties.',
    category: 'buying',
  },
  {
    id: 3,
    icon: '/assets/icons/calendar-orange-icon.svg',
    question: 'How do I schedule an open house?',
    answer: 'To schedule an open house, navigate to your Agent Dashboard and select the property you want to showcase. Click on "Schedule Open House" and choose your preferred date and time. You can add details about the event and it will be automatically listed on the property page for potential buyers to see.',
    category: 'agent',
  },
  {
    id: 4,
    icon: '/assets/icons/reset-icon.svg',
    question: 'How do I reset my password?',
    answer: 'To reset your password, click on the "Login" button and then select "Forgot Password." Enter your registered email address and we\'ll send you a password reset link. Follow the link to create a new password. For security, the link expires after 24 hours.',
    category: 'platform',
  },
  {
    id: 5,
    icon: '/assets/icons/contact-icon.svg',
    question: 'How do I contact a listing agent directly?',
    answer: 'You can contact a listing agent by visiting the property page and clicking the "Contact Agent" button. You\'ll be able to send a message directly to the agent through our secure messaging system. Alternatively, you can call the agent using the phone number displayed on their profile.',
    category: 'buying',
  },
  {
    id: 6,
    icon: '/assets/icons/caution-icon.svg',
    question: 'What if I find inaccurate data on a listing?',
    answer: 'If you find inaccurate information on a listing, please use the "Report Issue" button on the property page. Describe the inaccuracy and our team will review and correct it within 24-48 hours. You can also contact the listing agent directly to request corrections.',
    category: 'platform',
  },
];

const defaultPageTitle = 'Frequently Asked Questions ?';
const defaultSupportTitle = 'Still Need Help ?';
const defaultSupportDescription = 'Our Support Team Is Available\nMon-Fri, 9am-6pm IST';

export default function FAQPage() {
  const [activeCategory, setActiveCategory] = useState('all');
  const [expandedFaq, setExpandedFaq] = useState<number | null>(1);

  const [pageTitle, setPageTitle] = useState(defaultPageTitle);
  const [categories, setCategories] = useState<FaqCategoryItem[]>(defaultCategories);
  const [faqs, setFaqs] = useState<FaqItem[]>(defaultFaqs);
  const [supportTitle, setSupportTitle] = useState(defaultSupportTitle);
  const [supportDescription, setSupportDescription] = useState(defaultSupportDescription);

  useEffect(() => {
    async function loadCmsContent() {
      try {
        const records: CmsContentRecord[] = await cmsService.getPageContent('faq');
        const faqRecord = records.find((r) => r.sectionKey === 'faqContent');
        if (faqRecord) {
          const content = faqRecord.content as FaqContent;
          if (content.pageTitle) {
            setPageTitle(content.pageTitle);
          }
          if (content.categories && content.categories.length > 0) {
            // Always prepend "All Questions" category
            const hasAll = content.categories.some((c) => c.id === 'all');
            const cmsCategories = hasAll ? content.categories : [{ id: 'all', label: 'All Questions' }, ...content.categories];
            setCategories(cmsCategories);
          }
          if (content.faqs && content.faqs.length > 0) {
            // Resolve S3 keys for FAQ icons
            for (const faq of content.faqs) {
              if (faq.icon) {
                faq.icon = await resolveImageUrl(faq.icon);
              }
            }
            setFaqs(content.faqs);
            setExpandedFaq(content.faqs[0]?.id ?? null);
          }
          if (content.supportTitle) {
            setSupportTitle(content.supportTitle);
          }
          if (content.supportDescription) {
            setSupportDescription(content.supportDescription);
          }
        }
      } catch {
        // Keep defaults on error
      }
    }
    loadCmsContent();
  }, []);

  const filteredFaqs = activeCategory === 'all'
    ? faqs
    : faqs.filter(faq => faq.category === activeCategory);

  const toggleFaq = (id: number) => {
    setExpandedFaq(expandedFaq === id ? null : id);
  };

  return (
    <div className="min-h-screen bg-white flex flex-col">
      {/* Header */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 w-full">
        <CommonHeader />
      </div>

      {/* Main Content */}
      <main className="flex-1 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-8 w-full">
        <div className="flex flex-col lg:flex-row gap-8">
          {/* Categories Sidebar */}
          <div className="lg:w-[280px] flex-shrink-0">
            <div className="border border-[#00293d]/10 rounded-[15px] overflow-hidden shadow-sm">
              {/* Sidebar Header */}
              <div className="p-4 border-b border-[#00293d]/10">
                <h2 className="font-fractul font-bold text-[20px] text-[#00293d]">
                  Categories
                </h2>
              </div>

              {/* Category Items */}
              <div className="p-2">
                {categories.map((category) => (
                  <button
                    key={category.id}
                    onClick={() => setActiveCategory(category.id)}
                    className={`w-full px-4 py-3 flex items-center justify-between text-left transition-colors rounded-[7px] ${
                      activeCategory === category.id
                        ? 'bg-[#e58625] text-white'
                        : 'text-[#00293d] hover:bg-gray-50'
                    }`}
                  >
                    <span className={`${activeCategory === category.id ? 'font-fractul font-bold' : 'font-serif'} text-[14px]`}>
                      {category.label}
                    </span>
                    {activeCategory === category.id && (
                      <Image
                        src="/assets/icons/chevron-right-icon.svg"
                        alt=""
                        width={12}
                        height={12}
                        className="brightness-0 invert"
                      />
                    )}
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* FAQ Content */}
          <div className="flex-1">
            {/* Title */}
            <h1 className="font-fractul font-bold text-[24px] text-[#00293d] mb-6">
              {pageTitle}
            </h1>

            {/* FAQ Accordion */}
            <div className="space-y-4">
              {filteredFaqs.map((faq) => (
                <div
                  key={faq.id}
                  className={`border border-[#00293d]/10 rounded-[15px] overflow-hidden transition-shadow ${
                    expandedFaq === faq.id ? 'shadow-md' : ''
                  }`}
                >
                  <button
                    onClick={() => toggleFaq(faq.id)}
                    className="w-full px-6 py-5 flex items-center gap-4 text-left"
                  >
                    {faq.icon && (
                      faq.icon.startsWith('/') ? (
                        <Image
                          src={faq.icon}
                          alt=""
                          width={32}
                          height={32}
                        />
                      ) : (
                        <img
                          src={faq.icon}
                          alt=""
                          width={32}
                          height={32}
                          className="w-8 h-8 object-contain"
                        />
                      )
                    )}
                    <span className="flex-1 font-fractul font-semibold text-[20px] text-[#00293d]">
                      {faq.question}
                    </span>
                    <Image
                      src="/assets/icons/chevron-down-icon.svg"
                      alt=""
                      width={20}
                      height={20}
                      className={`transition-transform duration-200 flex-shrink-0 ${
                        expandedFaq === faq.id ? 'rotate-180' : ''
                      }`}
                    />
                  </button>

                  {expandedFaq === faq.id && (
                    <div className="px-6 pb-5">
                      <p className="font-serif text-[20px] text-[#00293d] leading-relaxed pl-12">
                        {faq.answer}
                      </p>
                    </div>
                  )}
                </div>
              ))}
            </div>

            {/* Still Need Help Section */}
            <div className="mt-8 border border-[#00293d]/10 rounded-[15px] p-8">
              <div className="flex flex-col lg:flex-row items-start lg:items-center justify-between gap-6">
                <div>
                  <h3 className="font-fractul font-bold text-[20px] text-[#00293d] mb-2">
                    {supportTitle}
                  </h3>
                  <p className="font-serif text-[20px] text-[#00293d] whitespace-pre-line">
                    {supportDescription}
                  </p>
                </div>

                <div className="flex flex-col gap-3">
                  <Link
                    href="/support/chat"
                    className="flex items-center justify-center gap-2 w-[174px] h-[51px] border border-[#00293d] rounded-[7px] font-fractul text-[16px] text-[#00293d] hover:bg-gray-50 transition-colors"
                  >
                    <Image
                      src="/assets/icons/chat-orange-icon.svg"
                      alt=""
                      width={22}
                      height={22}
                    />
                    Start Live Chat
                  </Link>
                  <a
                    href="mailto:support@requesn.com"
                    className="flex items-center justify-center gap-2 w-[174px] h-[51px] border border-[#00293d] rounded-[7px] font-fractul text-[16px] text-[#00293d] hover:bg-gray-50 transition-colors"
                  >
                    <Image
                      src="/assets/icons/email-orange-icon.svg"
                      alt=""
                      width={22}
                      height={22}
                    />
                    Email Support
                  </a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </main>

      {/* Footer */}
      <Footer />
    </div>
  );
}
