import React, { useState } from 'react';
import type { ComponentConfig } from '@measured/puck';
import { ChevronDown } from 'lucide-react';
import {
  createDesignControlsFields,
  applyDesignControls,
  type DesignControlsProps,
} from '../../theme';

export interface FaqItem {
  question: string;
  answer: string;
}

export interface FAQAccordionProps extends DesignControlsProps {
  heading?: string;
  items: FaqItem[];
  expandBehavior: 'single' | 'multiple';
  variant: 'light' | 'dark';
}

function FaqAccordionInner({
  heading,
  items,
  expandBehavior,
  variant,
  ...designControls
}: FAQAccordionProps) {
  const [openIndices, setOpenIndices] = useState<number[]>([]);

  const applied = applyDesignControls(designControls);
  const isDark = variant === 'dark';

  const toggleItem = (index: number) => {
    if (expandBehavior === 'single') {
      setOpenIndices(openIndices.includes(index) ? [] : [index]);
    } else {
      setOpenIndices(
        openIndices.includes(index)
          ? openIndices.filter((i) => i !== index)
          : [...openIndices, index]
      );
    }
  };

  const isOpen = (index: number) => openIndices.includes(index);

  return (
    <section
      id={designControls.anchorId || undefined}
      className={`${applied.className} ${isDark ? 'bg-neutral-900' : ''}`}
      style={applied.style}
    >
      <div
        className={`${applied.containerClassName || 'max-w-3xl'} mx-auto px-4 sm:px-6 lg:px-8`}
      >
        {heading && (
          <h2
            className={`text-3xl font-bold text-center mb-12 ${
              isDark ? 'text-white' : 'text-neutral-900'
            }`}
          >
            {heading}
          </h2>
        )}
        {items && items.length > 0 && (
          <div className="space-y-4">
            {items.map((item, index) => (
            <div
              key={index}
              className={`rounded-lg overflow-hidden ${
                isDark
                  ? 'bg-neutral-800 border border-neutral-700'
                  : 'bg-white border border-neutral-200 shadow-sm'
              }`}
            >
              <button
                onClick={() => toggleItem(index)}
                className={`w-full flex items-center justify-between p-5 text-left transition-colors ${
                  isDark
                    ? 'hover:bg-neutral-750'
                    : 'hover:bg-neutral-50'
                }`}
              >
                <span
                  className={`font-medium pr-4 ${
                    isDark ? 'text-white' : 'text-neutral-900'
                  }`}
                >
                  {item.question}
                </span>
                <ChevronDown
                  className={`w-5 h-5 flex-shrink-0 transition-transform duration-200 ${
                    isDark ? 'text-neutral-400' : 'text-neutral-500'
                  } ${isOpen(index) ? 'rotate-180' : ''}`}
                />
              </button>
              <div
                className={`overflow-hidden transition-all duration-200 ${
                  isOpen(index) ? 'max-h-96' : 'max-h-0'
                }`}
              >
                <div className="px-5 pb-5">
                  <p
                    className={`whitespace-pre-wrap ${
                      isDark ? 'text-neutral-300' : 'text-neutral-600'
                    }`}
                  >
                    {item.answer}
                  </p>
                </div>
              </div>
            </div>
            ))}
          </div>
        )}
      </div>
    </section>
  );
}

const designControlFields = createDesignControlsFields();

export const FAQAccordion: ComponentConfig<FAQAccordionProps> = {
  label: 'FAQ Accordion',
  fields: {
    heading: {
      type: 'text',
      label: 'Heading (optional)',
    },
    items: {
      type: 'array',
      label: 'FAQ Items',
      arrayFields: {
        question: { type: 'text', label: 'Question' },
        answer: { type: 'textarea', label: 'Answer' },
      },
      getItemSummary: (item) => item.question || 'Question',
      defaultItemProps: {
        question: 'How do I get started?',
        answer: 'Getting started is easy! Simply sign up for a free account and follow the onboarding guide.',
      },
    },
    expandBehavior: {
      type: 'select',
      label: 'Expand Behavior',
      options: [
        { label: 'Single (accordion)', value: 'single' },
        { label: 'Multiple', value: 'multiple' },
      ],
    },
    variant: {
      type: 'select',
      label: 'Variant',
      options: [
        { label: 'Light', value: 'light' },
        { label: 'Dark', value: 'dark' },
      ],
    },
    // Design Controls
    padding: designControlFields.padding,
    backgroundVariant: designControlFields.backgroundVariant,
    gradientPreset: designControlFields.gradientPreset,
    contentMaxWidth: designControlFields.contentMaxWidth,
    hideOnMobile: designControlFields.hideOnMobile,
    hideOnTablet: designControlFields.hideOnTablet,
    hideOnDesktop: designControlFields.hideOnDesktop,
    anchorId: designControlFields.anchorId,
  },
  defaultProps: {
    heading: 'Frequently Asked Questions',
    items: [
      {
        question: 'First question goes here?',
        answer:
          'Add your answer to this question here.',
      },
      {
        question: 'Second question goes here?',
        answer:
          'Add your answer to this question here.',
      },
      {
        question: 'Third question goes here?',
        answer:
          'Add your answer to this question here.',
      },
    ],
    expandBehavior: 'single',
    variant: 'light',
    padding: 'xl',
    contentMaxWidth: 'normal',
  },
  render: FaqAccordionInner,
};

export default FAQAccordion;
