﻿import React, { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { ChevronDown, ChevronRight } from "lucide-react";

interface AccordionProps {
  title: React.ReactNode;
  content: React.ReactNode;
  defaultExpanded?: boolean;
  leftIcon?: React.ReactNode;
  rightActions?: React.ReactNode;
  className?: string;
  isOpen?: boolean;
  onToggle?: () => void;
  disabled?: boolean;
}

interface AccordionRowProps {
  title: React.ReactNode | ((isOpen: boolean) => React.ReactNode);
  count?: number;
  disabled?: boolean;
  content: React.ReactNode;
  defaultOpen?: boolean;
  indent?: boolean;
  hideIcon?: boolean;
  rightActions?: React.ReactNode;
  className?: string;
  isOpen?: boolean;
  onToggle?: () => void;
}

export const Accordion: React.FC<AccordionProps> = ({
  title,
  content,
  defaultExpanded = false,
  leftIcon,
  rightActions,
  className = "",
  isOpen: propsIsOpen,
  onToggle,
  disabled,
}) => {
  const [internalExpanded, setInternalExpanded] = useState(defaultExpanded);

  const isControlled = propsIsOpen !== undefined;
  const isExpanded = isControlled ? propsIsOpen : internalExpanded;

  const handleToggle = () => {
    if (isControlled && onToggle) {
      onToggle();
    } else if (!isControlled) {
      setInternalExpanded((prev) => !prev);
    }
  };

  return (
    <motion.div
      layout
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      className={`bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden mb-2 ${className} ${
        disabled ? "opacity-60 !cursor-not-allowed" : "cursor-pointer"
      }`}
    >
      {/* HEADER */}
      <div
        onClick={disabled ? undefined : handleToggle}
        className="p-3 flex items-center justify-between cursor-pointer group hover:bg-slate-50 transition-colors"
      >
        <div className="flex items-center gap-4">
          {leftIcon && (
            <div
              className={`p-3 rounded-xl ${
                isExpanded
                  ? "bg-brand-blue text-white shadow-md shadow-brand-blue/20"
                  : "bg-slate-100 text-slate-500"
              }`}
            >
              {leftIcon}
            </div>
          )}

          {/* TITLE SLOT */}
          <div>{title}</div>
        </div>

        <div className="flex items-center gap-2">
          {rightActions}

          {/* Chevron */}
          <div className="text-slate-400 group-hover:text-brand-blue transition-colors">
            {isExpanded ? (
              <ChevronDown size={20} />
            ) : (
              <ChevronRight size={20} />
            )}
          </div>
        </div>
      </div>

      {/* BODY / CONTENT */}
      <AnimatePresence initial={false}>
        {isExpanded && (
          <motion.div
            key="accordion-body"
            initial={{ opacity: 0, scaleY: 0.98 }}
            animate={{ opacity: 1, scaleY: 1 }}
            exit={{ opacity: 0, scaleY: 0.98 }}
            transition={{ duration: 0.2, ease: "easeOut" }}
            style={{ transformOrigin: "top" }}
          >
            <div className="p-4 pt-0 border-t border-slate-100 bg-slate-50/50">
              {content}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </motion.div>
  );
};

export const AccordionRow: React.FC<AccordionRowProps> = ({
  title,
  count,
  disabled = false,
  content,
  defaultOpen = false,
  indent = true,
  hideIcon = false,
  rightActions,
  className = "",
  isOpen: propsIsOpen,
  onToggle,
}) => {
  const [internalIsOpen, setInternalIsOpen] = useState(defaultOpen);

  const isControlled = propsIsOpen !== undefined;
  const isOpen = isControlled ? propsIsOpen : internalIsOpen;

  const handleToggle = () => {
    if (disabled) return;
    if (isControlled && onToggle) {
      onToggle();
    } else if (!isControlled) {
      setInternalIsOpen((prev) => !prev);
    }
  };

  return (
    <div className="mb-2 last:mb-0">
      {/* HEADER (DIV â€” not button!) */}
      <div
        role="button"
        aria-disabled={disabled}
        onClick={handleToggle}
        className={`w-full flex items-center justify-between p-3 pl-4 rounded-xl 
          hover:bg-slate-100 transition-colors 
          group ${
            disabled ? "opacity-60 cursor-not-allowed" : "cursor-pointer"
          } 
          ${className}`}
      >
        <div className="w-full flex items-center gap-3">
          {/* Chevron */}
          {!hideIcon && (
            <div
              className={`p-1.5 rounded-xl transition-colors ${
                isOpen
                  ? "bg-brand-blue/40 text-white"
                  : "bg-slate-100 text-slate-500 group-hover:text-slate-700"
              }`}
            >
              {isOpen ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
            </div>
          )}

          {/* Title */}
          <div className="w-full text-sm font-semibold text-slate-700">
            {typeof title === "function" ? title(isOpen) : title}
          </div>

          {/* Count */}
          {count !== undefined && (
            <span className="text-xs text-slate-400 bg-slate-100 px-2 py-0.5 rounded-full">
              {count}
            </span>
          )}
        </div>

        {/* Right Actions */}
        {rightActions && (
          <div className="flex items-center gap-2 pr-2">{rightActions}</div>
        )}
      </div>

      {/* EXPANDED SECTION */}
      <AnimatePresence initial={false}>
        {isOpen && (
          <motion.div
            key="content"
            initial={{ opacity: 0, scaleY: 0.95 }}
            animate={{ opacity: 1, scaleY: 1 }}
            exit={{ opacity: 0, scaleY: 0.95 }}
            transition={{ duration: 0.18, ease: "easeOut" }}
            style={{ transformOrigin: "top" }}
            className={`mt-1 ${
              indent
                ? "ml-4 pl-4 border-l border-slate-200"
                : ""
            }`}
          >
            {content}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
};

