import * as React from 'react';
import { AiOutlineArrowLeft, AiOutlineArrowRight } from 'react-icons/ai';

import type { IQuickAction } from '../../service/popup/popup.interface';

import { BlobVideo } from './BlobVideo';
import { AiShoppingAssistantCard } from './AiShoppingAssistantCard';
import { ProductDetailsCard } from './ProductDetailsCard';
import { LatestArrivalsSessionCard } from './LatestArrivalsSessionCard';

type TabDef = {
  id: string;
  label: string;
  subtitle?: string;
  badge?: string;
  render: () => React.ReactNode;
};

type IPreviewTabs = {
  tabs: TabDef[];
  initialIndex?: number;
  activeIndex?: number;
  activeIndexTick?: number;
  className?: string;
  title?: string;
  helper?: string;
};

export const PreviewTabs = ({
  tabs,
  initialIndex = 0,
  activeIndex,
  activeIndexTick,
  className = '',
  title = 'Preview',
  helper = 'Switch between modes to preview each widget variant',
}: IPreviewTabs) => {
  const [index, setIndex] = React.useState(
    Math.min(Math.max(initialIndex, 0), tabs.length - 1)
  );
  const listRef = React.useRef<HTMLDivElement | null>(null);

  React.useEffect(() => {
    if (
      activeIndex !== undefined &&
      activeIndex >= 0 &&
      activeIndex < tabs.length
    ) {
      setIndex(activeIndex);
    }
  }, [activeIndex, activeIndexTick, tabs.length]);

  const select = (i: number) =>
    setIndex(Math.min(Math.max(i, 0), tabs.length - 1));
  const onKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'ArrowRight') {
      e.preventDefault();
      select(index + 1);
    } else if (e.key === 'ArrowLeft') {
      e.preventDefault();
      select(index - 1);
    } else if (e.key === 'Home') {
      e.preventDefault();
      select(0);
    } else if (e.key === 'End') {
      e.preventDefault();
      select(tabs.length - 1);
    }
  };

  return (
    <section className={'w-full ' + className} aria-label={title}>
      <div className="flex items-start justify-between mb-4">
        <div>
          <h2 className="text-[15px] font-bold text-[#121212]">{title}</h2>
          <p className="mt-1 text-xs text-[#6b7280]">{helper}</p>
        </div>
        <div className="flex items-center gap-2.5 mt-1 flex-shrink-0">
          <div className="flex items-center gap-1.5">
            {tabs.map((_, dotIndex) => (
              <button
                key={dotIndex}
                type="button"
                onClick={() => select(dotIndex)}
                className={[
                  'rounded-full transition-all duration-300 cursor-pointer',
                  dotIndex === index ? 'w-5 h-[6px]' : 'w-[6px] h-[6px]',
                ].join(' ')}
                style={{
                  background:
                    dotIndex === index
                      ? 'linear-gradient(90deg, #7e4dff 0%, #ff81c4 100%)'
                      : '#d1d5db',
                }}
                aria-label={`Go to ${tabs[dotIndex]?.label}`}
              />
            ))}
          </div>
          <span className="text-xs text-[#9ca3af] font-medium whitespace-nowrap">
            Step {index + 1} of {tabs.length}
          </span>
        </div>
      </div>

      <div
        ref={listRef}
        role="tablist"
        aria-label="Preview modes"
        onKeyDown={onKeyDown}
        className="rounded-[14px] border border-[#e5e7eb] bg-white overflow-hidden"
      >
        <div className="flex">
          {tabs.map((t, i) => {
            const selected = i === index;
            const id = `tab-${t.id}`;
            const panelId = `panel-${t.id}`;
            const isFirst = i === 0;
            const isLast = i === tabs.length - 1;

            const rounding = isFirst
              ? 'rounded-l-[13px]'
              : isLast
                ? 'rounded-r-[13px]'
                : '';

            return (
              <button
                key={t.id}
                id={id}
                role="tab"
                aria-selected={selected}
                aria-controls={panelId}
                tabIndex={selected ? 0 : -1}
                onClick={() => select(i)}
                className={[
                  'relative flex-1 text-left px-4 py-3 transition-all duration-200',
                  rounding,
                  'focus:outline-none focus-visible:ring-2 focus-visible:ring-[#b77be7]',
                  selected ? 'bg-[#eef2ff]' : 'bg-white hover:bg-[#f9fafb]',
                  !isLast ? 'border-r border-[#e5e7eb]' : '',
                ].join(' ')}
              >
                {selected && (
                  <div className="absolute bottom-0 left-0 right-0 h-[2.5px] bg-[#3b82f6]" />
                )}
                <div className="flex items-center gap-2">
                  <span
                    className={[
                      'text-xs font-semibold',
                      selected ? 'text-[#1a56db]' : 'text-[#374151]',
                    ].join(' ')}
                  >
                    {t.label}
                  </span>
                  {t.badge && (
                    <span className="text-[10px] px-2 py-[1px] rounded-full bg-[#f3e8ff] text-[#7c3aed] font-semibold">
                      {t.badge}
                    </span>
                  )}
                </div>
                {t.subtitle && (
                  <div
                    className={[
                      'mt-[2px] text-[11px]',
                      selected ? 'text-[#6b8cef]' : 'text-[#9ca3af]',
                    ].join(' ')}
                  >
                    {t.subtitle}
                  </div>
                )}
              </button>
            );
          })}
        </div>
      </div>

      {tabs.map((t, i) => {
        const selected = i === index;
        const panelId = `panel-${t.id}`;
        const tabId = `tab-${t.id}`;

        return (
          <div
            key={t.id}
            id={panelId}
            role="tabpanel"
            aria-labelledby={tabId}
            hidden={!selected}
            className={[
              'relative mt-4 rounded-[16px] bg-[#f5f5f6]/70 p-4',
              'ring-1 ring-[#ebeaf3]',
              'transition-all duration-300',
              selected
                ? 'opacity-100 translate-y-0'
                : 'opacity-0 translate-y-1',
            ].join(' ')}
          >
            <div className="mb-3 flex items-center justify-between">
              <div className="text-xs text-[#6b7280]">
                <span className="font-semibold text-[#374151]">
                  Currently viewing:
                </span>{' '}
                {t.label}
                {t.subtitle ? (
                  <span className="ml-2 text-[#9ca3af]">• {t.subtitle}</span>
                ) : null}
              </div>
              <span className="inline-flex items-center gap-1 rounded-full bg-white px-2.5 py-1 text-[11px] font-medium text-[#6b7280] ring-1 ring-[#e5e7eb]">
                <span
                  className="inline-block w-1.5 h-1.5 rounded-full"
                  style={{
                    background:
                      'linear-gradient(90deg, #7e4dff 0%, #ff81c4 100%)',
                  }}
                />
                Mode {i + 1} of {tabs.length}
              </span>
            </div>

            <div className="rounded-sm bg-white max-w-full shadow-[0_1px_0_rgba(0,0,0,0.04)]">
              {selected ? t.render() : null}
            </div>
          </div>
        );
      })}

      <div className="mt-4 flex items-center justify-center gap-3">
        <button
          onClick={() => select(index - 1)}
          disabled={index === 0}
          className="flex h-8 w-8 items-center justify-center rounded-full border border-[#e5e7eb] bg-white text-[#6b7280] disabled:opacity-30 disabled:cursor-not-allowed hover:bg-[#f9fafb] hover:text-[#374151] transition-colors"
          aria-label="Previous preview mode"
        >
          <AiOutlineArrowLeft className="h-3.5 w-3.5" />
        </button>

        <div className="flex items-center gap-1.5">
          {tabs.map((t, dotIndex) => (
            <button
              key={dotIndex}
              type="button"
              onClick={() => select(dotIndex)}
              className={[
                'h-1.5 rounded-full transition-all duration-300 cursor-pointer',
                dotIndex === index ? 'w-6' : 'w-1.5',
              ].join(' ')}
              style={{
                background:
                  dotIndex === index
                    ? 'linear-gradient(90deg, #7e4dff 0%, #ff81c4 100%)'
                    : '#d1d5db',
              }}
              aria-label={`Go to ${t.label}`}
            />
          ))}
        </div>

        <button
          onClick={() => select(index + 1)}
          disabled={index === tabs.length - 1}
          className="flex h-8 w-8 items-center justify-center rounded-full border border-[#e5e7eb] bg-white text-[#6b7280] disabled:opacity-30 disabled:cursor-not-allowed hover:bg-[#f9fafb] hover:text-[#374151] transition-colors"
          aria-label="Next preview mode"
        >
          <AiOutlineArrowRight className="h-3.5 w-3.5" />
        </button>
      </div>
    </section>
  );
};

type IPreviewSection = {
  image: File | string | null;
  sourceVideo: string | null;
  headerMessage: string | null;
  expandedHeaderMessage: string | null;
  position: string;
  buttonColor: string;
  cartIconColor: string;
  textColor: string;
  popupBorderColorLeft: string;
  popupBorderColorRight: string;
  size?: 'small' | 'medium' | 'big';
  showPrices?: boolean;
  showAddToCartButton?: boolean;
  activeTabIndex?: number;
  activeTabTick?: number;
  blobExpanded?: boolean;
  blobSkipIntro?: boolean;
  quickActions?: IQuickAction[];
  onUpdateQuickAction?: (idx: number, patch: Partial<IQuickAction>) => void;
  onUploadQuickActionIcon?: (idx: number, file: File) => void;
  onSaveQuickActions?: (actions: IQuickAction[]) => Promise<void>;
  isUploadingIcon?: boolean;
  placeholders?: string[];
};

export const PreviewSection = ({
  image,
  headerMessage,
  expandedHeaderMessage,
  position,
  buttonColor,
  cartIconColor,
  textColor,
  popupBorderColorLeft,
  popupBorderColorRight,
  size = 'medium',
  showPrices = true,
  showAddToCartButton = true,
  activeTabIndex,
  activeTabTick,
  blobExpanded,
  blobSkipIntro,
  quickActions,
  onUpdateQuickAction,
  onUploadQuickActionIcon,
  onSaveQuickActions,
  isUploadingIcon,
  placeholders,
}: IPreviewSection) => {
  const tabs: TabDef[] = [
    {
      id: 'video',
      label: 'Quick Overview',
      subtitle: 'Quick Overview',
      render: () => (
        <AiShoppingAssistantCard
          textColor={textColor}
          buttonColor={buttonColor}
          image={image}
          popupBorderColorLeft={popupBorderColorLeft}
          popupBorderColorRight={popupBorderColorRight}
          expandedHeaderMessage={expandedHeaderMessage}
          headerMessage={headerMessage}
          quickActions={quickActions}
          onUpdateQuickAction={onUpdateQuickAction}
          onUploadQuickActionIcon={onUploadQuickActionIcon}
          onSaveQuickActions={onSaveQuickActions}
          isUploadingIcon={isUploadingIcon}
          placeholders={placeholders}
        />
      ),
    },
    {
      id: 'ask',
      label: 'Ask the Product',
      subtitle: 'Smart Q&A',
      render: () => (
        <BlobVideo
          image={image}
          position={position}
          popupBorderColorLeft={popupBorderColorLeft}
          popupBorderColorRight={popupBorderColorRight}
          size={size}
          expanded={blobExpanded}
          skipIntro={blobSkipIntro}
        />
      ),
    },
    {
      id: 'single',
      label: 'Single Product',
      subtitle: 'Handpicked pick',
      render: () => (
        <ProductDetailsCard
          name="Classic Everyday Handbag"
          description="Elevate your daily style with this timeless handbag. Designed for both functionality and elegance, it offers ample space for your essentials while adding a sophisticated touch to any outfit."
          bullets={[
            'Versatile design suitable for work or casual wear',
            'Spacious interior with organized compartments',
            'Durable materials with a high-quality finish',
          ]}
          price={42}
          imageUrl={image}
          buttonColor={buttonColor}
          textColor={textColor}
          cartIconColor={cartIconColor}
          popupBorderColorLeft={popupBorderColorLeft}
          popupBorderColorRight={popupBorderColorRight}
          showPrices={showPrices}
          showAddToCartButton={showAddToCartButton}
        />
      ),
    },
    {
      id: 'active',
      label: 'Active Widget',
      subtitle: 'Live Recommendations',
      render: () => (
        <LatestArrivalsSessionCard
          textColor={textColor}
          buttonColor={buttonColor}
          cartIconColor={cartIconColor}
          popupBorderColorLeft={popupBorderColorLeft}
          popupBorderColorRight={popupBorderColorRight}
          showPrices={showPrices}
          showAddToCartButton={showAddToCartButton}
          products={[
            {
              id: 'svs',
              name: 'SVS Ultra Evolution Tower – Black Oak – Outlet – 1721',
              price: 1399.99,
              oldPrice: 1499.99,
              currency: '$',
              imageUrl: image,
              liked: true,
            },
            {
              id: 'pixel',
              name: 'Google Pixel 9 Pro',
              price: 899,
              oldPrice: 943.95,
              currency: '$',
              imageUrl: image,
            },
            {
              id: 'skirt',
              name: 'Verona Linen Wrap Skirt',
              price: 99,
              oldPrice: 124,
              currency: '$',
              imageUrl: image,
            },
          ]}
          suggestionText={[
            'Compare SVS Ultra Evolution Tower',
            'Black Oak',
            'Outlet',
            '1721 with Google Pixel 9 Pro.',
          ]}
        />
      ),
    },
  ];

  return (
    <PreviewTabs
      tabs={tabs}
      title="Preview your shopping assistant"
      helper="Switch between modes to see how the assistant appears as a pill, a video preview, and product-focused widgets."
      activeIndex={activeTabIndex}
      activeIndexTick={activeTabTick}
    />
  );
};
