import React from 'react';
import type { ComponentConfig } from '@measured/puck';
import { Clock, DollarSign, Image as ImageIcon, Loader2, ArrowRight } from 'lucide-react';
import { usePublicServices, PublicService } from '../../../hooks/useBooking';

export interface ServicesProps {
  title: string;
  subtitle: string;
  layout: '1-column' | '2-columns' | '3-columns';
  cardStyle: 'horizontal' | 'vertical';
  padding: 'none' | 'small' | 'medium' | 'large' | 'xlarge';
  showDuration: boolean;
  showPrice: boolean;
  showDescription: boolean;
  showDeposit: boolean;
  buttonText: string;
  buttonStyle: 'primary' | 'secondary' | 'outline' | 'link';
  categoryFilter: string;
  maxServices: number;
}

const LAYOUT_CLASSES = {
  '1-column': 'grid-cols-1',
  '2-columns': 'grid-cols-1 md:grid-cols-2',
  '3-columns': 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
};

const PADDING_CLASSES = {
  none: 'p-0',
  small: 'p-4',
  medium: 'p-8',
  large: 'p-12',
  xlarge: 'p-16 md:p-20',
};

const BUTTON_STYLES = {
  primary: 'bg-indigo-600 text-white hover:bg-indigo-700',
  secondary: 'bg-gray-100 text-gray-900 hover:bg-gray-200 dark:bg-gray-700 dark:text-white dark:hover:bg-gray-600',
  outline: 'border-2 border-indigo-600 text-indigo-600 hover:bg-indigo-50 dark:border-indigo-400 dark:text-indigo-400 dark:hover:bg-indigo-900/20',
  link: 'text-indigo-600 hover:text-indigo-700 dark:text-indigo-400 dark:hover:text-indigo-300 underline-offset-2 hover:underline',
};

// Horizontal card layout (image on left)
function HorizontalServiceCard({
  service,
  showDuration,
  showPrice,
  showDescription,
  showDeposit,
  buttonText,
  buttonStyle,
}: {
  service: PublicService;
  showDuration: boolean;
  showPrice: boolean;
  showDescription: boolean;
  showDeposit: boolean;
  buttonText: string;
  buttonStyle: keyof typeof BUTTON_STYLES;
}) {
  const hasImage = service.photos && service.photos.length > 0;
  const priceDisplay = service.price_cents ? (service.price_cents / 100).toFixed(2) : '0.00';
  const hasDeposit = service.deposit_amount_cents && service.deposit_amount_cents > 0;
  const depositDisplay = hasDeposit ? `$${(service.deposit_amount_cents! / 100).toFixed(2)}` : null;

  return (
    <div className="relative overflow-hidden rounded-xl border-2 border-gray-200 dark:border-gray-700 hover:border-indigo-300 dark:hover:border-indigo-600 hover:shadow-lg transition-all duration-200 group bg-white dark:bg-gray-800">
      <div className="flex h-full min-h-[160px]">
        {hasImage && (
          <div className="w-1/3 bg-gray-100 dark:bg-gray-700 relative flex-shrink-0">
            <img
              src={service.photos![0]}
              alt={service.name}
              className="absolute inset-0 w-full h-full object-cover"
            />
          </div>
        )}
        <div className={`${hasImage ? 'w-2/3' : 'w-full'} p-5 flex flex-col justify-between`}>
          <div>
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white group-hover:text-indigo-600 dark:group-hover:text-indigo-400 transition-colors">
              {service.name}
            </h3>
            {showDescription && service.description && (
              <p className="mt-1.5 text-sm text-gray-500 dark:text-gray-400 line-clamp-2">
                {service.description}
              </p>
            )}
          </div>

          <div className="mt-4 space-y-3">
            {/* Duration and Price */}
            <div className="flex items-center justify-between text-sm">
              {showDuration && (
                <div className="flex items-center text-gray-600 dark:text-gray-400">
                  <Clock className="w-4 h-4 mr-1.5" />
                  {service.duration} mins
                </div>
              )}
              {showPrice && (
                <div className="flex items-center font-semibold text-gray-900 dark:text-white">
                  <DollarSign className="w-4 h-4" />
                  {priceDisplay}
                </div>
              )}
            </div>

            {/* Deposit info */}
            {showDeposit && hasDeposit && depositDisplay && (
              <div className="text-xs text-indigo-600 dark:text-indigo-400 font-medium">
                Deposit required: {depositDisplay}
              </div>
            )}

            {/* Book button */}
            {buttonText && (
              <a
                href={`/book?service=${service.id}`}
                className={`inline-flex items-center justify-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${BUTTON_STYLES[buttonStyle]}`}
              >
                {buttonText}
                <ArrowRight className="w-4 h-4" />
              </a>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// Vertical card layout (image on top)
function VerticalServiceCard({
  service,
  showDuration,
  showPrice,
  showDescription,
  showDeposit,
  buttonText,
  buttonStyle,
}: {
  service: PublicService;
  showDuration: boolean;
  showPrice: boolean;
  showDescription: boolean;
  showDeposit: boolean;
  buttonText: string;
  buttonStyle: keyof typeof BUTTON_STYLES;
}) {
  const hasImage = service.photos && service.photos.length > 0;
  const priceDisplay = service.price_cents ? (service.price_cents / 100).toFixed(2) : '0.00';
  const hasDeposit = service.deposit_amount_cents && service.deposit_amount_cents > 0;
  const depositDisplay = hasDeposit ? `$${(service.deposit_amount_cents! / 100).toFixed(2)}` : null;

  return (
    <div className="relative overflow-hidden rounded-xl border-2 border-gray-200 dark:border-gray-700 hover:border-indigo-300 dark:hover:border-indigo-600 hover:shadow-lg transition-all duration-200 group bg-white dark:bg-gray-800 flex flex-col">
      {/* Image */}
      {hasImage ? (
        <div className="aspect-[4/3] bg-gray-100 dark:bg-gray-700 relative">
          <img
            src={service.photos![0]}
            alt={service.name}
            className="absolute inset-0 w-full h-full object-cover"
          />
        </div>
      ) : (
        <div className="aspect-[4/3] bg-gray-100 dark:bg-gray-700 flex items-center justify-center">
          <ImageIcon className="w-12 h-12 text-gray-300 dark:text-gray-600" />
        </div>
      )}

      {/* Content */}
      <div className="p-5 flex flex-col flex-1">
        <div className="flex-1">
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white group-hover:text-indigo-600 dark:group-hover:text-indigo-400 transition-colors">
            {service.name}
          </h3>
          {showDescription && service.description && (
            <p className="mt-1.5 text-sm text-gray-500 dark:text-gray-400 line-clamp-2">
              {service.description}
            </p>
          )}
        </div>

        <div className="mt-4 space-y-3">
          {/* Duration and Price */}
          <div className="flex items-center justify-between text-sm">
            {showDuration && (
              <div className="flex items-center text-gray-600 dark:text-gray-400">
                <Clock className="w-4 h-4 mr-1.5" />
                {service.duration} mins
              </div>
            )}
            {showPrice && (
              <div className="flex items-center font-semibold text-gray-900 dark:text-white">
                <DollarSign className="w-4 h-4" />
                {priceDisplay}
              </div>
            )}
          </div>

          {/* Deposit info */}
          {showDeposit && hasDeposit && depositDisplay && (
            <div className="text-xs text-indigo-600 dark:text-indigo-400 font-medium">
              Deposit required: {depositDisplay}
            </div>
          )}

          {/* Book button */}
          {buttonText && (
            <a
              href={`/book?service=${service.id}`}
              className={`inline-flex items-center justify-center gap-2 w-full px-4 py-2 rounded-lg text-sm font-medium transition-colors ${BUTTON_STYLES[buttonStyle]}`}
            >
              {buttonText}
              <ArrowRight className="w-4 h-4" />
            </a>
          )}
        </div>
      </div>
    </div>
  );
}

export const Services: ComponentConfig<ServicesProps> = {
  label: 'Services',
  fields: {
    title: {
      type: 'text',
      label: 'Title',
    },
    subtitle: {
      type: 'text',
      label: 'Subtitle',
    },
    layout: {
      type: 'select',
      label: 'Layout',
      options: [
        { label: '1 Column', value: '1-column' },
        { label: '2 Columns', value: '2-columns' },
        { label: '3 Columns', value: '3-columns' },
      ],
    },
    cardStyle: {
      type: 'select',
      label: 'Card Style',
      options: [
        { label: 'Horizontal (Image Left)', value: 'horizontal' },
        { label: 'Vertical (Image Top)', value: 'vertical' },
      ],
    },
    padding: {
      type: 'select',
      label: 'Padding',
      options: [
        { label: 'None', value: 'none' },
        { label: 'Small', value: 'small' },
        { label: 'Medium', value: 'medium' },
        { label: 'Large', value: 'large' },
        { label: 'Extra Large', value: 'xlarge' },
      ],
    },
    showDuration: {
      type: 'radio',
      label: 'Show Duration',
      options: [
        { label: 'Yes', value: true },
        { label: 'No', value: false },
      ],
    },
    showPrice: {
      type: 'radio',
      label: 'Show Price',
      options: [
        { label: 'Yes', value: true },
        { label: 'No', value: false },
      ],
    },
    showDescription: {
      type: 'radio',
      label: 'Show Description',
      options: [
        { label: 'Yes', value: true },
        { label: 'No', value: false },
      ],
    },
    showDeposit: {
      type: 'radio',
      label: 'Show Deposit Info',
      options: [
        { label: 'Yes', value: true },
        { label: 'No', value: false },
      ],
    },
    buttonText: {
      type: 'text',
      label: 'Button Text (leave empty to hide)',
    },
    buttonStyle: {
      type: 'select',
      label: 'Button Style',
      options: [
        { label: 'Primary', value: 'primary' },
        { label: 'Secondary', value: 'secondary' },
        { label: 'Outline', value: 'outline' },
        { label: 'Link', value: 'link' },
      ],
    },
    categoryFilter: {
      type: 'text',
      label: 'Category Filter (optional)',
    },
    maxServices: {
      type: 'number',
      label: 'Max Services to Show (0 = all)',
    },
  },
  defaultProps: {
    title: 'Our Services',
    subtitle: 'Choose from our range of professional services',
    layout: '2-columns',
    cardStyle: 'horizontal',
    padding: 'medium',
    showDuration: true,
    showPrice: true,
    showDescription: true,
    showDeposit: true,
    buttonText: 'Book Now',
    buttonStyle: 'primary',
    categoryFilter: '',
    maxServices: 0,
  },
  render: (props) => {
    return <ServicesDisplay {...props} />;
  },
};

// Separate component that can use hooks
function ServicesDisplay({
  title,
  subtitle,
  layout,
  cardStyle,
  padding,
  showDuration,
  showPrice,
  showDescription,
  showDeposit,
  buttonText,
  buttonStyle,
  categoryFilter,
  maxServices,
}: ServicesProps) {
  const { data: services, isLoading, error } = usePublicServices();

  // Filter and limit services
  let displayServices = services || [];
  if (categoryFilter && displayServices.length > 0) {
    displayServices = displayServices.filter((s) =>
      s.name.toLowerCase().includes(categoryFilter.toLowerCase())
    );
  }
  if (maxServices > 0) {
    displayServices = displayServices.slice(0, maxServices);
  }

  const layoutClass = LAYOUT_CLASSES[layout] || LAYOUT_CLASSES['2-columns'];
  const paddingClass = PADDING_CLASSES[padding] || PADDING_CLASSES['medium'];
  const CardComponent = cardStyle === 'vertical' ? VerticalServiceCard : HorizontalServiceCard;

  // Loading state
  if (isLoading) {
    return (
      <div className={paddingClass}>
        {(title || subtitle) && (
          <div className="text-center mb-8">
            {title && (
              <h2 className="text-2xl md:text-3xl font-bold text-gray-900 dark:text-white">
                {title}
              </h2>
            )}
            {subtitle && (
              <p className="mt-2 text-gray-500 dark:text-gray-400">
                {subtitle}
              </p>
            )}
          </div>
        )}
        <div className="flex justify-center items-center py-12">
          <Loader2 className="w-8 h-8 animate-spin text-indigo-600" />
        </div>
      </div>
    );
  }

  // Error state
  if (error) {
    return (
      <div className={paddingClass}>
        {(title || subtitle) && (
          <div className="text-center mb-8">
            {title && (
              <h2 className="text-2xl md:text-3xl font-bold text-gray-900 dark:text-white">
                {title}
              </h2>
            )}
            {subtitle && (
              <p className="mt-2 text-gray-500 dark:text-gray-400">
                {subtitle}
              </p>
            )}
          </div>
        )}
        <div className="text-center py-12 text-gray-500 dark:text-gray-400">
          Unable to load services
        </div>
      </div>
    );
  }

  // Empty state
  if (displayServices.length === 0) {
    return (
      <div className={paddingClass}>
        {(title || subtitle) && (
          <div className="text-center mb-8">
            {title && (
              <h2 className="text-2xl md:text-3xl font-bold text-gray-900 dark:text-white">
                {title}
              </h2>
            )}
            {subtitle && (
              <p className="mt-2 text-gray-500 dark:text-gray-400">
                {subtitle}
              </p>
            )}
          </div>
        )}
        <div className="text-center py-12">
          <ImageIcon className="w-16 h-16 mx-auto text-gray-300 dark:text-gray-600 mb-4" />
          <p className="text-gray-500 dark:text-gray-400">
            No services available at this time.
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className={paddingClass}>
      {/* Header */}
      {(title || subtitle) && (
        <div className="text-center mb-10">
          {title && (
            <h2 className="text-2xl md:text-3xl font-bold text-gray-900 dark:text-white">
              {title}
            </h2>
          )}
          {subtitle && (
            <p className="mt-2 text-gray-500 dark:text-gray-400 max-w-2xl mx-auto">
              {subtitle}
            </p>
          )}
        </div>
      )}

      {/* Services Grid */}
      <div className={`grid ${layoutClass} gap-6`}>
        {displayServices.map((service) => (
          <CardComponent
            key={service.id}
            service={service}
            showDuration={showDuration}
            showPrice={showPrice}
            showDescription={showDescription}
            showDeposit={showDeposit}
            buttonText={buttonText}
            buttonStyle={buttonStyle}
          />
        ))}
      </div>
    </div>
  );
}

export default Services;
