"use client";

import { useEffect, useMemo, useState } from "react";
import {
  Card,
  CardBody,
  Accordion,
  AccordionItem,
  Input,
  Chip,
  Spacer,
} from "@heroui/react";
import {
  AnimatePresence,
  MotionConfig,
  motion,
  useReducedMotion,
} from "framer-motion";
import { MotionTitle } from "./MotionTitle";
import { MotionContent } from "./MotionContent";
import { DEFAULT_FAQ, DEFAULT_PRESETS } from "./data";
import type { FaqProps } from "./types";

export default function FAQ({
  data = DEFAULT_FAQ,
  presets = DEFAULT_PRESETS,
  stagger = 0.1,
  baseDelay = 0.05,
  enableWhileInView = false,
}: FaqProps) {
  const [term, setTerm] = useState("");
  const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
  const prefersReduced = useReducedMotion();
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  const filtered = useMemo(() => {
    const t = term.trim().toLowerCase();
    if (!t) return data;
    return data.filter((item) =>
      (item.q + " " + item.a + " " + (item.tags?.join(" ") ?? ""))
        .toLowerCase()
        .includes(t),
    );
  }, [term, data]);

  const containerProps = enableWhileInView
    ? {
        initial: "hidden",
        whileInView: "show",
        viewport: { once: true, margin: "-100px" },
      }
    : { initial: "hidden", animate: "show" };

  return (
    <MotionConfig reducedMotion="user">
      <section className="space-y-3" id="faq" dir="rtl">
        <Card shadow="sm" className="border rounded-2xl">
          <CardBody className="grid md:grid-cols-[1fr,auto] gap-3 items-center">
            <Input
              value={term}
              onValueChange={setTerm}
              placeholder="ابحث في الأسئلة… (مثال: النقل، الفحص البيطري)"
              radius="lg"
              classNames={{ inputWrapper: "h-12" }}
            />
            <div className="flex gap-2 flex-wrap">
              {presets.map((p) => (
                <Chip
                  key={p}
                  onClick={() => setTerm(p)}
                  variant="flat"
                  color="success"
                  className="cursor-pointer"
                >
                  {p}
                </Chip>
              ))}
            </div>
          </CardBody>
        </Card>

        <motion.div
          {...containerProps}
          variants={{
            hidden: { opacity: 0 },
            show: {
              opacity: 1,
              transition: {
                staggerChildren: stagger,
                delayChildren: baseDelay,
              },
            },
          }}
          className="space-y-2"
        >
          <Accordion
            selectionMode="single"
            selectedKeys={selectedKeys}
            onSelectionChange={(keys) =>
              setSelectedKeys(new Set(keys as Set<string>))
            }
            itemClasses={{
              base: "rounded-2xl  bg-white overflow-hidden will-change-transform",
              title: "font-bold text-slate-900",
              trigger:
                "px-4 py-3 min-h-0 data-[focus-visible=true]:outline-none transition-all hover:bg-slate-50 active:scale-[0.998]",
              content: "px-0 pb-0 pt-0",
              indicator: "ms-2",
            }}
            className="space-y-2 border-none [&_.heroui-accordion-item]:border-0"
          >
            {filtered.map((item, i) => {
              const isOpen = (selectedKeys as Set<string>).has(item.q);
              const delay = prefersReduced ? 0 : baseDelay + i * stagger;

              return (
                <AccordionItem
                  key={item.q}
                  aria-label={item.q}
                  title={
                    <MotionTitle delay={delay} mounted={mounted}>
                      <span className="text-primary text-[14px]">{item.q}</span>
                    </MotionTitle>
                  }
                >
                  <AnimatePresence initial={false}>
                    {isOpen && (
                      <MotionContent>
                        <motion.div
                          layout
                          initial={{ background: "rgba(255,255,255,0)" }}
                          animate={{
                            background:
                              "linear-gradient(180deg, rgba(248,250,252,1) 0%, rgba(255,255,255,0) 100%)",
                          }}
                          exit={{ background: "rgba(255,255,255,0)" }}
                          className="rounded-xl"
                        >
                          <p className="leading-8 text-slate-700 px-2 pt-3">
                            {item.a}
                          </p>
                        </motion.div>
                      </MotionContent>
                    )}
                  </AnimatePresence>
                </AccordionItem>
              );
            })}
          </Accordion>
        </motion.div>
      </section>
    </MotionConfig>
  );
}
