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

export interface TestimonialItem {
  quote: string;
  name: string;
  title?: string;
  avatar?: string;
  rating?: 1 | 2 | 3 | 4 | 5;
}

export interface TestimonialsProps extends DesignControlsProps {
  heading?: string;
  items: TestimonialItem[];
  layout: 'carousel' | 'stacked';
  showRating: boolean;
}

const TestimonialsRender: React.FC<TestimonialsProps> = (props) => {
  const { heading, items = [], layout, showRating, ...designControls } = props;
  const [currentIndex, setCurrentIndex] = useState(0);

  const applied = applyDesignControls(designControls);

  const itemCount = items?.length || 0;

  const nextSlide = () => {
    if (itemCount > 0) {
      setCurrentIndex((prev) => (prev + 1) % itemCount);
    }
  };

  const prevSlide = () => {
    if (itemCount > 0) {
      setCurrentIndex((prev) => (prev - 1 + itemCount) % itemCount);
    }
  };

  const renderTestimonial = (item: TestimonialItem, index: number) => (
    <div
      key={index}
      className="bg-white rounded-xl shadow-md p-6 sm:p-8"
    >
      <Quote className="w-10 h-10 text-primary-200 mb-4" />
      {showRating && item.rating && (
        <div className="flex gap-1 mb-4">
          {Array.from({ length: 5 }).map((_, i) => (
            <Star
              key={i}
              className={`w-5 h-5 ${
                i < item.rating!
                  ? 'text-yellow-400 fill-yellow-400'
                  : 'text-neutral-300'
              }`}
            />
          ))}
        </div>
      )}
      <blockquote className="text-lg text-neutral-700 mb-6 italic">
        "{item.quote}"
      </blockquote>
      <div className="flex items-center gap-4">
        {item.avatar ? (
          <img
            src={item.avatar}
            alt={item.name}
            className="w-12 h-12 rounded-full object-cover"
          />
        ) : (
          <div className="w-12 h-12 rounded-full bg-primary-100 flex items-center justify-center">
            <span className="text-primary-600 font-semibold text-lg">
              {item.name.charAt(0).toUpperCase()}
            </span>
          </div>
        )}
        <div>
          <p className="font-semibold text-neutral-900">{item.name}</p>
          {item.title && (
            <p className="text-sm text-neutral-600">{item.title}</p>
          )}
        </div>
      </div>
    </div>
  );

  return (
    <section
      id={designControls.anchorId || undefined}
      className={applied.className}
      style={applied.style}
    >
      <div
        className={`${applied.containerClassName || 'max-w-7xl'} mx-auto px-4 sm:px-6 lg:px-8`}
      >
        {heading && (
          <h2
            className={`text-3xl font-bold text-center mb-12 ${applied.textClassName || 'text-neutral-900'}`}
          >
            {heading}
          </h2>
        )}

        {layout === 'carousel' ? (
          <div className="relative">
            <div className="overflow-hidden">
              <div
                className="flex transition-transform duration-300"
                style={{ transform: `translateX(-${currentIndex * 100}%)` }}
              >
                {items.map((item, index) => (
                  <div key={index} className="w-full flex-shrink-0 px-4">
                    <div className="max-w-2xl mx-auto">
                      {renderTestimonial(item, index)}
                    </div>
                  </div>
                ))}
              </div>
            </div>
            {itemCount > 1 && (
              <>
                <button
                  onClick={prevSlide}
                  className="absolute left-0 top-1/2 -translate-y-1/2 -translate-x-4 w-10 h-10 bg-white rounded-full shadow-lg flex items-center justify-center hover:bg-neutral-50 transition-colors"
                  aria-label="Previous testimonial"
                >
                  <ChevronLeft className="w-5 h-5 text-neutral-600" />
                </button>
                <button
                  onClick={nextSlide}
                  className="absolute right-0 top-1/2 -translate-y-1/2 translate-x-4 w-10 h-10 bg-white rounded-full shadow-lg flex items-center justify-center hover:bg-neutral-50 transition-colors"
                >
                  <ChevronRight className="w-5 h-5 text-neutral-600" />
                </button>
              </>
            )}
            {itemCount > 1 && (
              <div className="flex justify-center gap-2 mt-6">
                {items.map((_, index) => (
                  <button
                    key={index}
                    onClick={() => setCurrentIndex(index)}
                    className={`w-2 h-2 rounded-full transition-colors ${
                      index === currentIndex ? 'bg-primary-600' : 'bg-neutral-300'
                    }`}
                    aria-label={`Go to testimonial ${index + 1}`}
                  />
                ))}
              </div>
            )}
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {items.map((item, index) => renderTestimonial(item, index))}
          </div>
        )}
      </div>
    </section>
  );
};

const designControlFields = createDesignControlsFields();

export const Testimonials: ComponentConfig<TestimonialsProps> = {
  label: 'Testimonials',
  fields: {
    heading: {
      type: 'text',
      label: 'Heading (optional)',
    },
    items: {
      type: 'array',
      label: 'Testimonials',
      arrayFields: {
        quote: { type: 'textarea', label: 'Quote' },
        name: { type: 'text', label: 'Name' },
        title: { type: 'text', label: 'Title/Company' },
        avatar: { type: 'text', label: 'Avatar URL' },
        rating: {
          type: 'select',
          label: 'Rating',
          options: [
            { label: '5 Stars', value: 5 },
            { label: '4 Stars', value: 4 },
            { label: '3 Stars', value: 3 },
            { label: '2 Stars', value: 2 },
            { label: '1 Star', value: 1 },
          ],
        },
      },
      defaultItemProps: {
        quote: 'This product has been amazing for our team!',
        name: 'John Doe',
        title: 'CEO, Company',
        rating: 5,
      },
    },
    layout: {
      type: 'select',
      label: 'Layout',
      options: [
        { label: 'Carousel', value: 'carousel' },
        { label: 'Stacked Grid', value: 'stacked' },
      ],
    },
    showRating: {
      type: 'radio',
      label: 'Show Rating Stars',
      options: [
        { label: 'Yes', value: true },
        { label: 'No', value: false },
      ],
    },
    // 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: 'What people are saying',
    items: [
      {
        quote: 'Add your first testimonial here.',
        name: 'Customer Name',
        title: 'Title or Company',
        rating: 5,
      },
      {
        quote: 'Add your second testimonial here.',
        name: 'Customer Name',
        title: 'Title or Company',
        rating: 5,
      },
      {
        quote: 'Add your third testimonial here.',
        name: 'Customer Name',
        title: 'Title or Company',
        rating: 5,
      },
    ],
    layout: 'carousel',
    showRating: true,
    padding: 'xl',
    contentMaxWidth: 'wide',
  },
  render: TestimonialsRender,
};

export default Testimonials;
