'use client';

import { useState } from 'react';
import Link from 'next/link';
import {
  ChevronDown,
  Search,
  MessageCircle,
  Ticket,
  CreditCard,
  Users,
  MapPin,
  Wallet,
  ShieldCheck,
} from 'lucide-react';

interface FAQItem {
  question: string;
  answer: string;
}

interface FAQCategory {
  icon: React.ReactNode;
  title: string;
  items: FAQItem[];
}

const FAQ_CATEGORIES: FAQCategory[] = [
  {
    icon: <Ticket className="w-5 h-5" />,
    title: 'Booking',
    items: [
      {
        question: 'How do I book a ticket?',
        answer:
          'Go to the search page, enter your departure and destination stations, select a date, choose the number of passengers and your nationality, then tap Search. Pick a trip from the results, select your seats, fill in passenger details, and complete payment.',
      },
      {
        question: 'Can I book without creating an account?',
        answer:
          'Yes. Guest booking is fully supported — no account required. You can optionally create an account at the end of the booking flow to save your details for future trips.',
      },
      {
        question: 'What is the booking reference format?',
        answer:
          'Your booking reference is a 6-character alphanumeric code (e.g. A3F9KZ). It is shown on your confirmation screen and sent to your email or phone. Use it to look up your booking at any time via the Booking Lookup page.',
      },
      {
        question: 'Can I book a round trip?',
        answer:
          'Yes. Select "Round Trip" on the search form, choose both a departure and return date, and complete both legs in a single flow.',
      },
      {
        question: 'How far in advance can I book?',
        answer:
          'Tickets are available for booking up to the hold cutoff time before departure (typically 2 hours). Schedules are published in advance so you can plan ahead.',
      },
      {
        question: 'Can I save passenger details for future bookings?',
        answer:
          'Yes. When booking as a logged-in user you can save passenger profiles. On subsequent bookings you can select a saved passenger instead of re-entering their details.',
      },
    ],
  },
  {
    icon: <Users className="w-5 h-5" />,
    title: 'Passengers & Age-Based Pricing',
    items: [
      {
        question: 'How is the fare calculated?',
        answer:
          'The fare is calculated as: Base Fare × Distance + Insurance. The base fare depends on the seat class (Economy Regular, Economy Bed, or VIP Bed). Age-based rules then apply on top of this.',
      },
      {
        question: 'What are the passenger age categories?',
        answer:
          'Adults are passengers aged 5 years and above and pay 100% of the fare. Children are passengers under 5 years old — the first child per adult travels free, and any additional children pay the full fare.',
      },
      {
        question: 'How is a child\'s age determined?',
        answer:
          'Age is calculated automatically from the date of birth you enter for each passenger. Make sure to enter the correct date of birth so the right fare is applied.',
      },
    ],
  },
  {
    icon: <ShieldCheck className="w-5 h-5" />,
    title: 'Identity Verification (Verifayda)',
    items: [
      {
        question: 'What is Verifayda?',
        answer:
          'Verifayda is the Ethiopian government\'s national ID verification system. When you book as an Ethiopian national, your national ID is verified in real time to confirm your identity and retrieve your name and date of birth.',
      },
      {
        question: 'Is my national ID stored?',
        answer:
          'No. National ID numbers are not stored in our system. Verification happens in real time and only the confirmed passenger data (name, date of birth, nationality) is used for the booking.',
      },
      {
        question: 'What if I am not Ethiopian?',
        answer:
          'Non-Ethiopian passengers use their passport number instead. No Verifayda verification is required. Select your nationality on the search form and enter your passport details during the passenger information step.',
      },
      {
        question: 'What happens if verification fails?',
        answer:
          'If Verifayda verification is unsuccessful the booking cannot be completed for that passenger. Check that the national ID number is correct and try again. If the problem persists, contact support.',
      },
    ],
  },
  {
    icon: <MapPin className="w-5 h-5" />,
    title: 'Stations & Routes',
    items: [
      {
        question: 'How many stations does EDR serve?',
        answer:
          'EDR serves 21 stations along the Ethio-Djibouti Railway corridor, spanning from Addis Ababa in Ethiopia to Djibouti City in Djibouti.',
      },
      {
        question: 'Can I book a partial journey (not the full route)?',
        answer:
          'Yes. You can book between any two stations on the route. Fares are calculated based on the distance between your chosen origin and destination.',
      },
      {
        question: 'How do I find my nearest station?',
        answer:
          'On the search page, tap the From or To field and browse or search the full list of stations. Each station shows its code and country.',
      },
    ],
  },
  {
    icon: <CreditCard className="w-5 h-5" />,
    title: 'Payment',
    items: [
      {
        question: 'What payment methods are accepted?',
        answer:
          'We accept Telebirr, Waafi, D-Money, CBE Birr, and more. You can choose your preferred method at checkout.',
      },
      {
        question: 'Is my payment information secure?',
        answer:
          'Yes. All payments are processed through certified payment providers. Transactions are encrypted end-to-end.',
      },
    ],
  },
  {
    icon: <Ticket className="w-5 h-5" />,
    title: 'Tickets & Boarding',
    items: [
      {
        question: 'How do I get my ticket?',
        answer:
          'After payment is confirmed, your ticket is generated automatically. You can view and download it as a PDF from your booking detail page. A QR code and barcode are included for gate validation.',
      },
      {
        question: 'Do I need to print my ticket?',
        answer:
          'No. You can show your digital ticket (QR code) on your phone at the gate. Printed tickets are also accepted.',
      },
      {
        question: 'What do I need to board?',
        answer:
          'Present your ticket QR code and a valid ID (national ID or passport matching the passenger details on the booking) at the gate.',
      },
      {
        question: 'Can I look up a booking without an account?',
        answer:
          'Yes. Go to the Booking Lookup page and enter your booking reference and the phone number or email used when booking.',
      },
    ],
  },
  {
    icon: <Wallet className="w-5 h-5" />,
    title: 'Account & Profile',
    items: [
      {
        question: 'How do I create an account?',
        answer:
          'Tap Register on the login page and enter your email, phone number, full name, and a password. You will receive an OTP to verify your account.',
      },
      {
        question: 'I forgot my password. What do I do?',
        answer:
          'Tap "Forgot password" on the login page, enter your registered email, and follow the reset link sent to your inbox.',
      },
    ],
  },
];

export default function HelpPage() {
  const [openKeys, setOpenKeys] = useState<Set<string>>(new Set());
  const [searchTerm, setSearchTerm] = useState('');

  const toggle = (key: string) => {
    setOpenKeys((prev) => {
      const next = new Set(prev);
      next.has(key) ? next.delete(key) : next.add(key);
      return next;
    });
  };

  const query = searchTerm.trim().toLowerCase();
  const searchResults: { catTitle: string; item: FAQItem; key: string }[] = [];
  if (query) {
    FAQ_CATEGORIES.forEach((cat) => {
      cat.items.forEach((item, i) => {
        if (
          item.question.toLowerCase().includes(query) ||
          item.answer.toLowerCase().includes(query)
        ) {
          searchResults.push({ catTitle: cat.title, item, key: `search-${cat.title}-${i}` });
        }
      });
    });
  }

  return (
    <main className="min-h-screen bg-gray-50 dark:bg-gray-950">
      {/* Hero */}
      <section className="bg-gradient-to-br from-primary/90 to-primary/60 py-14 px-4 text-center">
        <h1 className="text-3xl md:text-4xl font-bold text-white mb-3">Help & FAQs</h1>
        <p className="text-white/80 text-base max-w-xl mx-auto">
          Find answers about booking, pricing, payments, and more.
        </p>
      </section>

      {/* Search */}
      <section className="bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-800 px-4 py-5">
        <div className="max-w-2xl mx-auto relative">
          <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
          <input
            type="text"
            placeholder="Search FAQs…"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-3 border-2 border-gray-200 dark:border-gray-700 rounded-xl bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder-gray-400 focus:outline-none focus:border-primary text-sm"
          />
        </div>
      </section>

      {/* Content */}
      <section className="px-4 py-10 max-w-3xl mx-auto">
        {query ? (
          searchResults.length > 0 ? (
            <div className="space-y-3">
              <p className="text-sm text-gray-500 dark:text-gray-400 mb-4">
                {searchResults.length} result{searchResults.length !== 1 ? 's' : ''} for &ldquo;{searchTerm}&rdquo;
              </p>
              {searchResults.map(({ catTitle, item, key }) => (
                <FAQRow
                  key={key}
                  question={item.question}
                  answer={item.answer}
                  badge={catTitle}
                  isOpen={openKeys.has(key)}
                  onToggle={() => toggle(key)}
                />
              ))}
            </div>
          ) : (
            <div className="text-center py-16 text-gray-400 dark:text-gray-500">
              <Search className="w-10 h-10 mx-auto mb-3 opacity-40" />
              <p className="text-sm">No results for &ldquo;{searchTerm}&rdquo;</p>
            </div>
          )
        ) : (
          <div className="space-y-10">
            {FAQ_CATEGORIES.map((cat) => (
              <div key={cat.title}>
                <div className="flex items-center gap-2 mb-4">
                  <span className="text-primary">{cat.icon}</span>
                  <h2 className="text-lg font-bold text-gray-900 dark:text-white">{cat.title}</h2>
                </div>
                <div className="space-y-2">
                  {cat.items.map((item, i) => {
                    const key = `${cat.title}-${i}`;
                    return (
                      <FAQRow
                        key={key}
                        question={item.question}
                        answer={item.answer}
                        isOpen={openKeys.has(key)}
                        onToggle={() => toggle(key)}
                      />
                    );
                  })}
                </div>
              </div>
            ))}
          </div>
        )}
      </section>

      {/* Contact CTA */}
      <section className="px-4 pb-16">
        <div className="max-w-xl mx-auto bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-2xl p-8 text-center shadow-sm">
          <div className="w-14 h-14 bg-primary rounded-xl flex items-center justify-center mx-auto mb-4">
            <MessageCircle className="w-7 h-7 text-white" />
          </div>
          <h2 className="text-xl font-bold text-gray-900 dark:text-white mb-2">Still need help?</h2>
          <p className="text-gray-500 dark:text-gray-400 text-sm mb-6">
            Our support team is available to assist you.
          </p>
          <Link
            href="/contact"
            className="inline-block px-8 py-3 bg-primary hover:bg-primary/90 text-white font-bold rounded-xl transition-colors text-sm"
          >
            Contact Support
          </Link>
        </div>
      </section>
    </main>
  );
}

function FAQRow({
  question,
  answer,
  badge,
  isOpen,
  onToggle,
}: {
  question: string;
  answer: string;
  badge?: string;
  isOpen: boolean;
  onToggle: () => void;
}) {
  return (
    <div className="border-2 border-gray-200 dark:border-gray-700 rounded-xl overflow-hidden hover:border-primary/50 transition-colors">
      <button
        type="button"
        onClick={onToggle}
        className="w-full flex items-start justify-between gap-3 px-4 py-4 bg-white dark:bg-gray-800 text-left"
      >
        <div className="flex-1 min-w-0">
          {badge && (
            <span className="inline-block text-xs font-semibold text-primary bg-primary/10 rounded-full px-2 py-0.5 mb-1.5">
              {badge}
            </span>
          )}
          <p className="text-sm font-semibold text-gray-900 dark:text-white">{question}</p>
        </div>
        <ChevronDown
          className={`w-4 h-4 text-primary flex-shrink-0 mt-0.5 transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`}
        />
      </button>
      {isOpen && (
        <div className="px-4 py-4 bg-gray-50 dark:bg-gray-900 border-t border-gray-200 dark:border-gray-700 text-sm text-gray-600 dark:text-gray-300 leading-relaxed">
          {answer}
        </div>
      )}
    </div>
  );
}
