import React, { useState } from "react";
import { Link } from "react-router-dom";

interface FAQItem {
  question: string;
  answer: string | React.ReactNode;
}

interface FAQSection {
  title: string;
  items: FAQItem[];
}

const FAQ: React.FC = () => {
  const [openSections, setOpenSections] = useState<{ [key: string]: boolean }>({
    earnings: true, // Open earnings section by default
  });
  const [openQuestions, setOpenQuestions] = useState<{
    [key: string]: boolean;
  }>({});

  const toggleSection = (sectionId: string) => {
    setOpenSections((prev) => ({ ...prev, [sectionId]: !prev[sectionId] }));
  };

  const toggleQuestion = (questionId: string) => {
    setOpenQuestions((prev) => ({ ...prev, [questionId]: !prev[questionId] }));
  };

  const faqSections: { id: string; section: FAQSection }[] = [
    {
      id: "earnings",
      section: {
        title: "Earnings & Fees",
        items: [
          {
            question: "How much does it cost to list items on the platform?",
            answer:
              "Listing items is completely free! We only charge a Community Upkeep Fee when your item is successfully rented.",
          },
          {
            question: "What is the Community Upkeep Fee?",
            answer: (
              <div>
                <p>
                  We charge a <strong>10% Community Upkeep Fee</strong> on
                  rental amounts to keep Village Share running!
                </p>
                <p className="mb-2">This fee covers:</p>
                <ul className="mb-3">
                  <li>Platform maintenance and improvements</li>
                  <li>Customer support for renters and owners</li>
                  <li>Secure payment processing</li>
                  <li>Trust and safety features</li>
                </ul>
                <div className="bg-light rounded p-3 mb-3">
                  <h6 className="text-primary mb-2">Example Calculation</h6>
                  <div className="d-flex justify-content-between mb-1">
                    <span>Rental amount:</span>
                    <span className="fw-bold">$100.00</span>
                  </div>
                  <div className="d-flex justify-content-between mb-1">
                    <span>Community Upkeep Fee (10%):</span>
                    <span className="text-danger">-$10.00</span>
                  </div>
                  <hr className="my-2" />
                  <div className="d-flex justify-content-between">
                    <span className="fw-bold">You earn:</span>
                    <span className="fw-bold text-success">$90.00</span>
                  </div>
                </div>
                <p className="small text-muted">
                  <strong>Payout Timeline:</strong> Earnings are transferred
                  immediately when the rental is marked complete. Funds
                  typically reach your bank within 2-7 business days. Make sure
                  your Stripe account is set up to receive payouts.
                </p>
              </div>
            ),
          },
          {
            question: "When will I receive my earnings?",
            answer: (
              <div>
                <p>The payout process has three stages:</p>
                <div className="bg-light rounded p-3 mb-3">
                  <div className="d-flex align-items-start mb-3">
                    <span className="badge bg-success me-2">1</span>
                    <div>
                      <strong>Transfer Initiated</strong>
                      <span className="text-success ms-2">(Immediate)</span>
                      <p className="mb-0 small text-muted">
                        When the rental is marked complete, we immediately
                        transfer your earnings to your Stripe account.
                      </p>
                    </div>
                  </div>
                  <div className="d-flex align-items-start mb-3">
                    <span className="badge bg-success me-2">2</span>
                    <div>
                      <strong>Funds in Stripe</strong>
                      <span className="text-success ms-2">(Instant)</span>
                      <p className="mb-0 small text-muted">
                        The transfer appears in your Stripe dashboard right
                        away.
                      </p>
                    </div>
                  </div>
                  <div className="d-flex align-items-start">
                    <span className="badge bg-primary me-2">3</span>
                    <div>
                      <strong>Funds in Your Bank</strong>
                      <span className="text-primary ms-2">
                        (2-7 business days)
                      </span>
                      <p className="mb-0 small text-muted">
                        Stripe automatically deposits funds to your bank
                        account. Timing depends on your bank and Stripe's payout
                        schedule.
                      </p>
                    </div>
                  </div>
                </div>
                <p className="small text-muted mb-0">
                  <strong>Note:</strong> If you haven't completed Stripe
                  onboarding, payouts are held until you finish setup. Once
                  complete, all pending payouts are processed immediately.
                </p>
              </div>
            ),
          },
          {
            question: "Why is my payout still pending?",
            answer: (
              <div>
                <p>A payout may show as "pending" for a few reasons:</p>
                <ul>
                  <li>
                    <strong>Rental not yet complete:</strong> The owner needs to
                    mark the rental as complete before the payout is initiated.
                  </li>
                  <li>
                    <strong>Stripe onboarding incomplete:</strong> You need to
                    finish setting up your Stripe account. Visit your{" "}
                    <Link to="/earnings">Earnings Dashboard</Link> to complete
                    setup.
                  </li>
                  <li>
                    <strong>Processing:</strong> Payouts are initiated
                    immediately but may take a moment to process.
                  </li>
                </ul>
                <p className="small text-muted mb-0">
                  If a payout fails for any reason, we automatically retry daily
                  until it succeeds.
                </p>
              </div>
            ),
          },
          {
            question: "How do I set up my account to receive payments?",
            answer: (
              <div>
                <p>
                  To receive payments, you need to connect a Stripe account:
                </p>
                <ol>
                  <li>
                    Go to your <Link to="/earnings">Earnings Dashboard</Link>
                  </li>
                  <li>
                    Click on "Set Up Earnings" or "Connect Stripe Account"
                  </li>
                  <li>Follow the Stripe onboarding process</li>
                  <li>
                    Provide your bank account details and required information
                  </li>
                </ol>
                <p>
                  Once your Stripe account is verified, you'll automatically
                  receive payouts for completed rentals.
                </p>
              </div>
            ),
          },
          {
            question: "Can I see a breakdown of my earnings?",
            answer: (
              <div>
                Yes! Visit your <Link to="/earnings">Earnings Dashboard</Link>{" "}
                to see:
                <ul>
                  <li>Total earnings across all rentals</li>
                  <li>
                    Pending earnings (rentals completed but not yet paid out)
                  </li>
                  <li>
                    Completed payouts (money already sent to your account)
                  </li>
                  <li>Detailed earnings history for each rental</li>
                </ul>
              </div>
            ),
          },
        ],
      },
    },
    {
      id: "renting",
      section: {
        title: "For Renters",
        items: [
          {
            question: "How do I rent an item?",
            answer: (
              <div>
                <ol>
                  <li>
                    Browse available items on the{" "}
                    <Link to="/items">Items page</Link>
                  </li>
                  <li>Click on an item to view details</li>
                  <li>Select your desired rental dates and times</li>
                  <li>Choose pickup or in-place use (if available)</li>
                  <li>Review the cost and submit your rental request</li>
                  <li>Wait for the owner to accept your request</li>
                  <li>Once accepted, you'll receive a confirmation email</li>
                </ol>
              </div>
            ),
          },
          {
            question: "What payment methods are accepted?",
            answer:
              "We accept all major credit and debit cards through our secure payment processor, Stripe. Payment is processed when the owner accepts your rental request.",
          },
          {
            question: "Can I cancel a rental?",
            answer:
              "You can request to cancel a rental by contacting the item owner through the messaging system. Cancellation policies and refunds are determined by the owner.",
          },
          {
            question: "What if an item is damaged during my rental?",
            answer:
              "If an item is damaged during your rental period, you may be responsible for repair or replacement costs up to the replacement value listed on the item. We recommend taking photos before and after use and communicating any issues immediately with the owner.",
          },
          {
            question: "How do I contact the item owner?",
            answer: (
              <div>
                You can message the item owner through our{" "}
                <Link to="/messages">messaging system</Link>. Once you've
                submitted a rental request or are actively renting an item,
                you'll have access to direct messaging with the owner.
              </div>
            ),
          },
        ],
      },
    },
    {
      id: "listing",
      section: {
        title: "For Owners",
        items: [
          {
            question: "What items can I list for rent?",
            answer:
              "You can list most items including tools, equipment, recreational gear, electronics, and more. Items must be in good working condition and safe to use. Prohibited items include weapons, hazardous materials, and illegal items.",
          },
          {
            question: "How do I create a listing?",
            answer: (
              <div>
                <ol>
                  <li>
                    Click <Link to="/create-item">"List an Item"</Link> in the
                    navigation
                  </li>
                  <li>Upload photos of your item (up to 5 images)</li>
                  <li>Provide a clear title and detailed description</li>
                  <li>Set your location and delivery options</li>
                  <li>Define your availability hours</li>
                  <li>Set your pricing (hourly, daily, weekly, or monthly)</li>
                  <li>Add any rules or requirements</li>
                  <li>Submit your listing for review</li>
                </ol>
              </div>
            ),
          },
          {
            question: "How do I set my pricing?",
            answer:
              "When creating or editing a listing, you can set prices for different time periods (hour, day, week, or month). The platform will show you exactly how much you'll earn after the 10% Community Upkeep Fee. You can also use Advanced Pricing to offer multiple pricing tiers.",
          },
          {
            question: "Can I edit my listing after it's published?",
            answer: (
              <div>
                Yes! Go to <Link to="/owning">My Listings</Link>, find your
                item, and click "Edit" to update details, pricing, availability,
                or photos at any time.
              </div>
            ),
          },
          {
            question: "How do I manage rental requests?",
            answer: (
              <div>
                Visit your <Link to="/owning">My Listings</Link> page to see
                pending rental requests. You can accept or decline requests
                based on your availability and preferences.
              </div>
            ),
          },
        ],
      },
    },
    {
      id: "account",
      section: {
        title: "Account & Settings",
        items: [
          {
            question: "How do I create an account?",
            answer:
              'Click "Sign Up" in the top navigation and create an account using your email address or Google account. You\'ll need to verify your email address to complete registration.',
          },
          {
            question: "How do I update my profile?",
            answer: (
              <div>
                Go to your <Link to="/profile">Profile page</Link> to update
                your name, email, phone number, profile picture, and bio.
              </div>
            ),
          },
          {
            question: "Is my personal information secure?",
            answer:
              "Yes, we take security seriously. All payment processing is handled by Stripe, a PCI-compliant payment processor. Your financial information is encrypted and never stored on our servers.",
          },
          {
            question: "How do I delete my account?",
            answer:
              "To delete your account, please contact our support team. Note that you must complete or cancel all active rentals before account deletion.",
          },
        ],
      },
    },
    {
      id: "safety",
      section: {
        title: "Safety & Trust",
        items: [
          {
            question: "How does the platform ensure safety?",
            answer: (
              <div>
                We maintain safety through:
                <ul>
                  <li>User verification and profile reviews</li>
                  <li>Secure payment processing through Stripe</li>
                  <li>Direct messaging for clear communication</li>
                  <li>Replacement cost protection for owners</li>
                  <li>Community guidelines and terms of service</li>
                </ul>
              </div>
            ),
          },
          {
            question: "What if I have a dispute with another user?",
            answer:
              "We encourage users to communicate directly to resolve issues. If you cannot reach a resolution, please contact our support team with details about the dispute.",
          },
          {
            question: "Are items insured?",
            answer:
              "The platform does not provide insurance. Owners should consider their own insurance coverage for their items. Renters may be liable for damage up to the replacement cost listed on the item.",
          },
        ],
      },
    },
  ];

  return (
    <div className="container mt-4 mb-5">
      <div className="row justify-content-center">
        <div className="col-lg-10">
          <div className="text-center mb-5">
            <h1 className="display-4">Frequently Asked Questions</h1>
            <p className="lead text-muted">
              Find answers to common questions about using our platform
            </p>
          </div>

          {faqSections.map(({ id, section }) => (
            <div key={id} className="card mb-3">
              <div className="card-header bg-primary text-white">
                <button
                  className="btn btn-link text-white text-decoration-none w-100 text-start p-0"
                  onClick={() => toggleSection(id)}
                >
                  <h5 className="mb-0">
                    {section.title}
                    <span className="float-end">
                      {openSections[id] ? "▼" : "▶"}
                    </span>
                  </h5>
                </button>
              </div>

              {openSections[id] && (
                <div className="card-body">
                  {section.items.map((item, index) => {
                    const questionId = `${id}-${index}`;
                    return (
                      <div key={questionId} className="mb-3">
                        <button
                          className="btn btn-link text-decoration-none w-100 text-start p-0"
                          onClick={() => toggleQuestion(questionId)}
                        >
                          <h6 className="text-dark mb-2">
                            {openQuestions[questionId] ? "▼" : "▶"}{" "}
                            {item.question}
                          </h6>
                        </button>

                        {openQuestions[questionId] && (
                          <div className="ms-4 text-muted">{item.answer}</div>
                        )}

                        {index < section.items.length - 1 && <hr />}
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          ))}

          <div className="card bg-light mt-5">
            <div className="card-body text-center">
              <h5>Still have questions?</h5>
              <p className="text-muted">
                Can't find what you're looking for? We're here to help!
              </p>
              <Link to="/contact" className="btn btn-primary">
                Contact Support
              </Link>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default FAQ;
