import React, { useState } from 'react';
import type { ComponentConfig } from '@measured/puck';
import { Play, X } from 'lucide-react';
import {
  createDesignControlsFields,
  applyDesignControls,
  type DesignControlsProps,
} from '../../theme';
import { buildSafeEmbedUrl, validateVideoEmbed } from '../../utils/videoEmbed';

export interface VideoEmbedProps extends DesignControlsProps {
  heading: string;
  text?: string;
  thumbnailImage: string;
  provider: 'youtube' | 'vimeo';
  videoId: string;
  variant: 'light' | 'dark';
}

const VideoEmbedRender: React.FC<VideoEmbedProps> = (props) => {
  const {
    heading,
    text,
    thumbnailImage,
    provider,
    videoId,
    variant,
    ...designControls
  } = props;

  const [isPlaying, setIsPlaying] = useState(false);
  const applied = applyDesignControls(designControls);
  const isDark = variant === 'dark';

  // Build safe embed URL
  let embedUrl = '';
  try {
    embedUrl = buildSafeEmbedUrl(provider, videoId);
  } catch {
    // Invalid video ID
  }

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

        <div className="relative aspect-video rounded-xl overflow-hidden shadow-2xl">
          {isPlaying && embedUrl ? (
            <div className="relative w-full h-full">
              <iframe
                src={`${embedUrl}?autoplay=1`}
                className="absolute inset-0 w-full h-full"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                allowFullScreen
                title="Video"
              />
              <button
                onClick={() => setIsPlaying(false)}
                className="absolute top-4 right-4 w-10 h-10 bg-black/50 rounded-full flex items-center justify-center text-white hover:bg-black/70 transition-colors"
                aria-label="Close video"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
          ) : (
            <button
              onClick={() => setIsPlaying(true)}
              className="relative w-full h-full group cursor-pointer"
              disabled={!embedUrl}
            >
              <img
                src={thumbnailImage}
                alt="Video thumbnail"
                className="w-full h-full object-cover"
              />
              <div className="absolute inset-0 bg-black/30 group-hover:bg-black/40 transition-colors" />
              <div className="absolute inset-0 flex items-center justify-center">
                <div className="w-20 h-20 bg-white/90 rounded-full flex items-center justify-center group-hover:scale-110 transition-transform shadow-lg">
                  <Play className="w-8 h-8 text-primary-600 ml-1" fill="currentColor" />
                </div>
              </div>
              {!embedUrl && (
                <div className="absolute bottom-4 left-4 right-4 bg-red-500/90 text-white text-sm px-4 py-2 rounded">
                  Invalid video configuration
                </div>
              )}
            </button>
          )}
        </div>
      </div>
    </section>
  );
};

const designControlFields = createDesignControlsFields();

export const VideoEmbed: ComponentConfig<VideoEmbedProps> = {
  label: 'Video',
  fields: {
    heading: {
      type: 'text',
      label: 'Heading',
    },
    text: {
      type: 'textarea',
      label: 'Description',
    },
    thumbnailImage: {
      type: 'text',
      label: 'Thumbnail Image URL',
    },
    provider: {
      type: 'select',
      label: 'Video Provider',
      options: [
        { label: 'YouTube', value: 'youtube' },
        { label: 'Vimeo', value: 'vimeo' },
      ],
    },
    videoId: {
      type: 'text',
      label: 'Video ID',
    },
    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,
    alignment: designControlFields.alignment,
    hideOnMobile: designControlFields.hideOnMobile,
    hideOnTablet: designControlFields.hideOnTablet,
    hideOnDesktop: designControlFields.hideOnDesktop,
    anchorId: designControlFields.anchorId,
  },
  defaultProps: {
    heading: 'Watch the video',
    text: 'Add a description for your video here.',
    thumbnailImage: 'https://placehold.co/800x450/1a1a2e/ffffff?text=Video+Thumbnail',
    provider: 'youtube',
    videoId: '',
    variant: 'light',
    padding: 'xl',
    contentMaxWidth: 'normal',
    alignment: 'center',
  },
  render: VideoEmbedRender,
};

export default VideoEmbed;
