"use client";

import { useState } from "react";

import Button from "@/components/ui/Button";
import { cn } from "@/lib/utils";

interface SupportAction {
  label: string;
  icon?: React.ReactNode;
  onClick?: () => void;
}

interface FaqQuestion {
  question: string;
  answer?: string;
}

interface FaqCategory {
  title: string;
  questions?: FaqQuestion[];
  defaultOpen?: boolean;
}

interface SupportCenterProps {
  title?: string;
  actions?: SupportAction[];
  faqTitle?: string;
  categories?: FaqCategory[];
  className?: string;
}

const defaultActions: SupportAction[] = [
  {
    label: "Contact Us",
    icon: (
      <svg className="h-7 w-7 text-[#3B82F6]" viewBox="0 0 48 48" fill="none" aria-hidden="true">
        <path d="M12 32 28 6l8 5-14 25-10-4Z" fill="currentColor" />
        <path d="M9 36h15l-4 7H8l1-7Z" fill="#1E3A8A" />
        <path d="M15 26l10 4" stroke="white" strokeWidth="2" strokeLinecap="round" />
      </svg>
    ),
  },
  {
    label: "Messages",
    icon: (
      <svg className="h-7 w-7 text-[#3B82F6]" viewBox="0 0 48 48" fill="none" aria-hidden="true">
        <path d="M14 30 29 5l8 5-13 24-10-4Z" fill="currentColor" />
        <path d="M10 37h18l-5 7H9l1-7Z" fill="#1E3A8A" />
        <circle cx="34" cy="33" r="7" fill="#00AFC1" />
        <path d="M31 33h6M34 30v6" stroke="white" strokeWidth="2" strokeLinecap="round" />
      </svg>
    ),
  },
];

const defaultCategories: FaqCategory[] = [
  {
    title: "Ordering and Payments",
    defaultOpen: true,
    questions: [
      {
        question: "How do I save and manage my shipping address before payment?",
        answer: "Go to Shipping Address, add or edit your address, then choose the default address before checkout.",
      },
      {
        question: "I can't find my order in my account",
        answer: "Check that you are signed in with the same account used at checkout. If it still does not appear, contact support with your order ID.",
      },
      {
        question: "I can't find my order in my account",
        answer: "Some orders can take a few minutes to sync after payment. Refresh the page or check again later.",
      },
      {
        question: "How can I change my order details, such as shipping address, color, size, etc.?",
        answer: "You can request changes before the seller starts processing the order. Open the order details page and contact the seller or support.",
      },
    ],
  },
  {
    title: "Shipping and Delivery",
    questions: [
      {
        question: "How can I track my delivery?",
        answer: "Open your order details and check the delivery timeline. Tracking updates appear after the seller ships the item.",
      },
    ],
  },
  {
    title: "Returns",
    questions: [
      {
        question: "How do I request a return?",
        answer: "Open the order, choose request return, select the reason, and submit your request with photos if required.",
      },
    ],
  },
  {
    title: "Account Management",
    questions: [
      {
        question: "How do I update my profile information?",
        answer: "Go to Settings and update your profile, phone number, email, or saved addresses.",
      },
    ],
  },
  {
    title: "Refunds",
    questions: [
      {
        question: "When will I receive my refund?",
        answer: "Refunds are processed after the return is approved. Bank processing times may vary.",
      },
    ],
  },
  {
    title: "Rules and Policies",
    questions: [
      {
        question: "Where can I read marketplace policies?",
        answer: "You can find marketplace policies in the Rules and Policies section of the Support Center.",
      },
    ],
  },
];

export default function SupportCenter({
  title = "Support Center",
  actions = defaultActions,
  faqTitle = "FAQ",
  categories = defaultCategories,
  className,
}: SupportCenterProps) {
  const [openCategories, setOpenCategories] = useState(
    () => new Set(categories.filter((category) => category.defaultOpen).map((category) => category.title))
  );
  const [openQuestions, setOpenQuestions] = useState(new Set<string>());

  const toggleCategory = (title: string) => {
    setOpenCategories((current) => {
      const next = new Set(current);
      if (next.has(title)) {
        next.delete(title);
      } else {
        next.add(title);
      }
      return next;
    });
  };

  const toggleQuestion = (key: string) => {
    setOpenQuestions((current) => {
      const next = new Set(current);
      if (next.has(key)) {
        next.delete(key);
      } else {
        next.add(key);
      }
      return next;
    });
  };

  return (
    <section className={cn("w-full bg-white text-[#1f2440]", className)}>
      <h2 className="text-lg font-medium">{title}</h2>

      <div className="mt-5 grid gap-5 sm:grid-cols-2">
        {actions.map((action) => (
          <Button
            key={action.label}
            variant="ghost"
            onClick={action.onClick}
            className="h-16 rounded-md bg-gray-50 text-sm font-medium text-gray-900 hover:bg-gray-100"
            icon={action.icon}
          >
            {action.label}
          </Button>
        ))}
      </div>

      <h3 className="mt-8 text-base font-medium">{faqTitle}</h3>

      <div className="mt-4 space-y-4">
        {categories.map((category) => {
          const categoryOpen = openCategories.has(category.title);

          return (
            <section key={category.title}>
              <button
                type="button"
                onClick={() => toggleCategory(category.title)}
                className="flex h-14 w-full items-center gap-3 rounded-sm bg-gray-50 px-6 text-left text-sm font-medium text-gray-700"
              >
                <svg
                  className={cn("h-4 w-4 transition-transform", categoryOpen && "rotate-90")}
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  strokeWidth={2}
                >
                  <path strokeLinecap="round" strokeLinejoin="round" d="m9 5 7 7-7 7" />
                </svg>
                {category.title}
              </button>

              {categoryOpen && category.questions && (
                <div className="bg-white px-10 py-2">
                  {category.questions.map((item, index) => {
                    const questionKey = `${category.title}-${index}`;
                    const questionOpen = openQuestions.has(questionKey);

                    return (
                      <div key={questionKey} className="border-b border-gray-100 py-5 last:border-b-0">
                        <button
                          type="button"
                          onClick={() => toggleQuestion(questionKey)}
                          className="flex w-full items-center justify-between gap-4 text-left text-sm text-gray-900"
                        >
                          <span>{item.question}</span>
                          <span className="text-lg text-gray-500">{questionOpen ? "-" : "+"}</span>
                        </button>
                        {questionOpen && item.answer && (
                          <p className="mt-3 max-w-3xl text-sm leading-6 text-gray-500">{item.answer}</p>
                        )}
                      </div>
                    );
                  })}
                </div>
              )}
            </section>
          );
        })}
      </div>
    </section>
  );
}
