import React, { useEffect, useState } from 'react';
// import { Link } from 'react-router-dom';

import { IPopupData, IQuickAction } from '../../service/popup/popup.interface';
import { hexToRgba } from '../../utils/rgbaUtil';
import { savePopupData } from '../../service/popup/popup.service';
import { useAppStateContext } from '../../context/user.data.context';
// import Input from '../ui/Input';
import Banner from '../widgets/Banner';
import ErrorWrapper from '../alert/ErrorWrapper';
import Button from '../widgets/Button';

const SectionHeader = ({
  title,
  description,
}: {
  title: string;
  description: string;
}) => (
  <div className="mb-4">
    <h2 className="text-base font-semibold text-gray-900">{title}</h2>
    <p className="mt-1 text-sm text-gray-500">{description}</p>
  </div>
);

const CharCountTextarea = ({
  label,
  hint,
  value,
  maxLength,
  placeholder,
  rows,
  textSize,
  onChange,
}: {
  label: string;
  hint: string;
  value: string;
  maxLength: number;
  placeholder: string;
  rows?: number;
  textSize?: 'xs' | 'sm';
  onChange: (val: string) => void;
}) => {
  const len = value.length;
  const nearLimit = len >= maxLength * 0.85;
  const atLimit = len >= maxLength;
  const sizeClass = textSize === 'xs' ? 'text-xs' : 'text-sm';

  return (
    <div className="space-y-1.5">
      <p className="text-sm font-medium text-gray-900">{label}</p>
      <textarea
        placeholder={placeholder}
        value={value}
        maxLength={maxLength}
        rows={rows || 2}
        onChange={e => onChange(e.target.value)}
        className={`w-full rounded-lg border border-gray-200 bg-white px-3 py-2.5 ${sizeClass} text-gray-900 placeholder:text-gray-400 outline-none transition-colors hover:border-gray-300 focus:border-gray-400 focus:ring-1 focus:ring-gray-200 resize-y leading-relaxed`}
      />
      <div className="flex items-center justify-between">
        <p className="text-xs text-gray-500">{hint}</p>
        <span
          className={[
            'text-xs font-medium tabular-nums',
            atLimit
              ? 'text-red-500'
              : nearLimit
                ? 'text-amber-500'
                : 'text-gray-400',
          ].join(' ')}
        >
          {len}/{maxLength}
        </span>
      </div>
    </div>
  );
};

const VisualStateIcon = ({ type }: { type: string }) => {
  if (type === 'expanded') {
    return (
      <div className="relative h-12 w-7 rounded-sm border border-gray-200 bg-white">
        <div className="absolute top-1.5 left-1 right-1 h-1.5 rounded-[1px] bg-gray-100" />
      </div>
    );
  }
  if (type === 'partial') {
    return (
      <div className="relative h-12 w-7 rounded-sm border border-gray-200 bg-white">
        <div className="absolute bottom-1 right-1 h-3 w-4 rounded-[1px] bg-gray-100" />
      </div>
    );
  }

  return (
    <div className="relative h-12 w-7 rounded-sm border border-gray-200 bg-white">
      <div className="absolute bottom-1 right-1 h-2.5 w-2.5 rounded-full bg-gray-100" />
    </div>
  );
};

const VisualStateSelector = ({
  label,
  value,
  onChange,
}: {
  label: string;
  value: string;
  onChange: (val: string) => void;
}) => {
  const options = [
    { id: 'expanded', label: 'Expanded' },
    { id: 'partial', label: 'Partial' },
    { id: 'minimized', label: 'Minimized' },
  ];

  return (
    <div className="space-y-2">
      <p className="text-sm font-medium text-gray-900">{label}</p>
      <div className="grid grid-cols-3 gap-2">
        {options.map(opt => {
          const isActive = value === opt.id;

          return (
            <button
              key={opt.id}
              type="button"
              onClick={() => onChange(opt.id)}
              className={[
                'flex flex-col items-center gap-2 rounded-lg border py-3 px-2 transition-all',
                isActive
                  ? 'border-gray-900 bg-gray-50'
                  : 'border-gray-200 bg-white hover:border-gray-300',
              ].join(' ')}
            >
              <VisualStateIcon type={opt.id} />
              <span
                className={[
                  'text-xs font-medium',
                  isActive ? 'text-gray-900' : 'text-gray-500',
                ].join(' ')}
              >
                {opt.label}
              </span>
            </button>
          );
        })}
      </div>
    </div>
  );
};

const ToggleGroup = ({
  options,
  value,
  onChange,
}: {
  options: { label: string; value: string }[];
  value: string;
  onChange: (val: string) => void;
}) => (
  <div className="inline-flex bg-gray-100 p-1 rounded-lg w-full sm:w-auto overflow-hidden">
    {options.map(option => {
      const isSelected = value === option.value;

      return (
        <button
          key={option.value}
          type="button"
          onClick={() => onChange(option.value)}
          className={`flex-1 sm:flex-none px-4 py-2 text-sm font-medium rounded-md transition-all duration-200 ${
            isSelected
              ? 'bg-white text-black shadow-sm ring-1 ring-gray-200'
              : 'text-gray-500 hover:text-gray-900 hover:bg-gray-200/50'
          }`}
        >
          {option.label}
        </button>
      );
    })}
  </div>
);

const CustomCheckbox = ({
  label,
  checked,
  onChange,
}: {
  label: string;
  checked: boolean;
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
}) => (
  <label className="flex cursor-pointer items-center gap-2">
    <input
      type="checkbox"
      checked={checked}
      onChange={onChange}
      className="h-4 w-4 rounded border-gray-300 text-gray-900 focus:ring-gray-900"
    />
    <span className="text-sm text-gray-700">{label}</span>
  </label>
);

type Props = {
  token: string | null;
  popup: IPopupData | null;
  popupBorderColorLeft: string;
  popupBorderColorRight: string;
  textColor: string;
  position: string;
  buttonColor: string;
  useStock: boolean;
  setUseStock: (useStock: boolean) => void;
  sourceVideo: string | null;
  setSourceVideo: (sourceVideo: string | null) => void;
  headerMessage: string | null;
  setHeaderMessage: (headerMessage: string) => void;
  expandedHeaderMessage: string | null;
  setExpandedHeaderMessage: (headerMessage: string) => void;
  cartIconColor: string;
  defaultState: string | null;
  setDefaultState: (state: string) => void;
  restoreOnNavigation: boolean;
  setRestoreOnNavigation: (restoreOnNavigation: boolean) => void;
  defaultStateMobile: string | null;
  setDefaultStateMobile: (state: string) => void;
  size: 'small' | 'medium' | 'big';
  setSize: (size: 'small' | 'medium' | 'big') => void;
  showPrices: boolean;
  setShowPrices: (showPrices: boolean) => void;
  showAddToCartButton: boolean;
  setShowAddToCartButton: (showAddToCartButton: boolean) => void;
  quickActions?: IQuickAction[];
};

type IErrors = {
  popupBorderColorLeft: boolean;
  popupBorderColorRight: boolean;
  textColor: boolean;
  buttonColor: boolean;
};

const CustomizationSettings = ({
  popup,
  buttonColor,
  cartIconColor,
  popupBorderColorLeft,
  popupBorderColorRight,
  textColor,
  useStock,
  position,
  setUseStock,
  sourceVideo,
  // setSourceVideo,
  expandedHeaderMessage,
  headerMessage,
  setExpandedHeaderMessage,
  setHeaderMessage,
  defaultState,
  restoreOnNavigation,
  setDefaultState,
  setRestoreOnNavigation,
  defaultStateMobile,
  setDefaultStateMobile,
  setShowAddToCartButton,
  setShowPrices,
  setSize,
  showAddToCartButton,
  showPrices,
  size,
  quickActions,
}: Props) => {
  const { user, completeOnboardingStep } = useAppStateContext();
  const [loading, setLoading] = useState<boolean>(false);
  const [success, setSuccess] = useState<boolean>(false);
  const [apiError, setApiError] = useState<string | null>(null);

  const allowedPlans = ['SCALING', 'HYPER_SCALING'];
  const planKey = (user?.plan ?? '').toString().toUpperCase();
  const hasAllowedPlan = allowedPlans.includes(planKey);
  const videoBlocked = !hasAllowedPlan;

  useEffect(() => {
    if (apiError || success) {
      const timer: NodeJS.Timeout = setTimeout(() => {
        setApiError(null);
        setSuccess(false);
      }, 3000);

      return () => clearTimeout(timer);
    }
  }, [success, apiError]);

  const saveSettings = async (): Promise<void> => {
    try {
      const validation: IErrors = {
        popupBorderColorLeft: popupBorderColorLeft.length === 0,
        popupBorderColorRight: popupBorderColorRight.length === 0,
        textColor: textColor.length === 0,
        buttonColor: buttonColor.length === 0,
      };

      if (
        validation.popupBorderColorLeft ||
        validation.popupBorderColorRight ||
        validation.textColor ||
        validation.buttonColor
      ) {
        return;
      }

      setLoading(true);

      const sanitizedSourceVideo = videoBlocked
        ? null
        : sourceVideo?.trim() || null;

      const response = await savePopupData({
        color: hexToRgba(textColor),
        secondary_color: hexToRgba(buttonColor),
        settings: {
          cart_icon_color: cartIconColor,
          text_color: textColor,
          button_color: buttonColor,
          gradient_colors: [popupBorderColorLeft, popupBorderColorRight],
          restore_on_navigation: restoreOnNavigation,
          size: size,
          show_prices: showPrices,
          show_add_to_cart_button: showAddToCartButton,
          quick_actions: quickActions,
        },
        position: position,
        header_message: popup?.header_message || 'Keep browsing to unlock',
        unlocked_popup_message:
          popup?.unlocked_popup_message || 'Premium Recommendations Unlocked',
        expanded_header_message: popup?.expanded_header_message,
        buy_now_button_message: popup?.buy_now_button_message || 'Add to cart',
        locked_popup_message:
          popup?.locked_popup_message || 'Keep browsing to unlock',
        toggle_button_message: popup?.toggle_button_message || 'Discover',
        search_more_message:
          popup?.search_more_message ||
          "Keep exploring! We'll have more personalized picks for you soon.",
        like_button_message: popup?.like_button_message || 'like',
        dislike_button_message: popup?.dislike_button_message || 'dislike',
        loading_message: popup?.loading_message || 'Reveal Secret Deals!',
        come_back_button_message:
          popup?.come_back_button_message || 'Come back for more',
        in_stock_message: popup?.in_stock_message || 'In stock',
        link_copied_message: popup?.link_copied_message || 'Link copied',
        engagement_messages: {
          expanded_header_message: expandedHeaderMessage?.slice(0, 130),
          header_message: headerMessage?.slice(0, 90),
        },
        source_video: sanitizedSourceVideo,
        use_stock: useStock || true,
        default_state: defaultState || ('minimized' as any),
        default_state_mobile: defaultStateMobile || ('minimized' as any),
      });

      setLoading(false);

      if (response?.success) {
        setSuccess(true);
        completeOnboardingStep('customize');
      }
    } catch (error) {
      setLoading(false);
      setApiError(String(error));
    }
  };

  return (
    <div className="space-y-8 pb-6">
      {/* Messaging Section */}
      <section className="bg-white p-5 rounded-lg border border-gray-200 shadow-sm">
        <SectionHeader
          title="Messaging"
          description="The greeting text visitors see when interacting with your widget."
        />
        <div className="space-y-5">
          <CharCountTextarea
            label="Header message"
            hint="Shows on the minimized pill — keep it short."
            value={headerMessage || ''}
            maxLength={90}
            placeholder="Hi! How can I help?"
            rows={4}
            textSize="xs"
            onChange={setHeaderMessage}
          />
          <CharCountTextarea
            label="Expanded message"
            hint="Shown when a shopper opens the full widget."
            value={expandedHeaderMessage || ''}
            maxLength={130}
            placeholder="Ask me anything, from gift ideas to the latest arrivals, and I'll find exactly what you need."
            rows={3}
            onChange={setExpandedHeaderMessage}
          />
        </div>
      </section>

      {/* Widget States & Sizing Section */}
      <section className="bg-white p-5 rounded-lg border border-gray-200 shadow-sm">
        <SectionHeader
          title="Widget States & Sizing"
          description="How the widget appears when a shopper first lands on your store."
        />
        <div className="space-y-5">
          <VisualStateSelector
            label="Desktop default state"
            value={defaultState || 'minimized'}
            onChange={setDefaultState}
          />
          <VisualStateSelector
            label="Mobile default state"
            value={defaultStateMobile || 'minimized'}
            onChange={setDefaultStateMobile}
          />
          <div className="space-y-1.5">
            <p className="text-sm font-medium text-gray-900">Popup size</p>
            <ToggleGroup
              value={size || 'medium'}
              onChange={val => setSize(val as any)}
              options={[
                { label: 'Small', value: 'small' },
                { label: 'Medium', value: 'medium' },
                { label: 'Big', value: 'big' },
              ]}
            />
          </div>
        </div>
      </section>

      {/* Shopping Features Section */}
      <section className="bg-white p-5 rounded-lg border border-gray-200 shadow-sm">
        <SectionHeader
          title="Shopping Features"
          description="Toggle what shoppers can see and do inside the widget."
        />
        <div className="space-y-5">
          <div>
            <p className="text-sm font-medium text-gray-900">Product display</p>
            <div className="mt-3 space-y-3">
              <CustomCheckbox
                label="Show product prices"
                checked={showPrices}
                onChange={e => setShowPrices(e.target.checked)}
              />
              <CustomCheckbox
                label="Show 'Add to cart' button"
                checked={showAddToCartButton}
                onChange={e => setShowAddToCartButton(e.target.checked)}
              />
              <CustomCheckbox
                label="Only recommend in-stock products"
                checked={useStock}
                onChange={e => setUseStock(e.target.checked)}
              />
            </div>
          </div>
          <div>
            <p className="text-sm font-medium text-gray-900">Navigation</p>
            <div className="mt-3">
              <CustomCheckbox
                label="Remember widget state across pages"
                checked={restoreOnNavigation}
                onChange={e => setRestoreOnNavigation(e.target.checked)}
              />
            </div>
          </div>
        </div>
      </section>

      {/* Onboarding Video Section */}
      {/* <section className="overflow-hidden rounded-lg border border-gray-200 bg-white shadow-sm">
        <header className="flex items-center justify-between border-b border-gray-100 bg-gray-50/50 px-5 py-4">
          <div>
            <h2 className="text-sm font-semibold text-gray-900">
              Onboarding Video
            </h2>
            <p className="mt-0.5 text-xs text-gray-500">
              Embed a short YouTube video to welcome shoppers and boost
              engagement.
            </p>
          </div>
          {videoBlocked && (
            <span className="inline-flex items-center gap-1 rounded bg-gray-200/60 px-2.5 py-1 text-[10px] font-semibold tracking-wider text-gray-600 uppercase">
              <svg
                viewBox="0 0 20 20"
                fill="currentColor"
                className="h-3 w-3"
                aria-hidden="true"
              >
                <path
                  fillRule="evenodd"
                  d="M10 1a4.5 4.5 0 00-4.5 4.5V9H5a2 2 0 00-2 2v6a2 2 0 002 2h10a2 2 0 002-2v-6a2 2 0 00-2-2h-.5V5.5A4.5 4.5 0 0010 1zm3 8V5.5a3 3 0 10-6 0V9h6z"
                  clipRule="evenodd"
                />
              </svg>
              Premium
            </span>
          )}
        </header>

        <div className="p-5">
          {videoBlocked ? (
            <div className="flex flex-col items-center justify-center rounded-md border border-dashed border-gray-300 bg-gray-50 py-8 text-center">
              <div className="mb-3 flex h-10 w-10 items-center justify-center rounded-full bg-white shadow-sm ring-1 ring-inset ring-gray-200">
                <svg
                  className="h-5 w-5 text-gray-400"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"
                  />
                </svg>
              </div>
              <p className="text-sm font-medium text-gray-900">
                Upgrade to embed videos
              </p>
              <p className="mt-1 max-w-sm text-xs text-gray-500">
                Scaling or Hyper-Scaling plan is required to use the onboarding
                video feature.
              </p>
              <Link to="/pricing" className="mt-4">
                <Button className="rounded-md bg-gray-900 px-5 py-2 text-xs font-medium text-white transition-colors hover:bg-gray-800">
                  View Plans
                </Button>
              </Link>
            </div>
          ) : (
            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-900">
                YouTube Video ID
              </label>
              <Input
                placeholder="e.g. dQw4w9WgXcQ"
                value={sourceVideo || ''}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                  setSourceVideo(e.target.value)
                }
              />
              <p className="text-xs text-gray-500">
                Extract the ID from your URL. Example: youtube.com/watch?v=
                <strong className="font-semibold text-gray-900">
                  VIDEO_ID
                </strong>
              </p>
            </div>
          )}
        </div>
      </section> */}

      {/* Action Area */}
      <div className="pt-2">
        {apiError && (
          <div className="pb-4">
            <ErrorWrapper error={apiError} />
          </div>
        )}

        {success && (
          <div className="pb-4">
            <Banner type="success" open={success} setOpen={setSuccess}>
              Settings saved successfully.
            </Banner>
          </div>
        )}

        <Button
          type="button"
          onClick={saveSettings}
          isLoading={loading}
          disabled={loading}
          className="w-full py-3.5 px-5 text-base font-medium bg-slate-900 text-white flex justify-center items-center"
        >
          Save Settings
        </Button>
      </div>
    </div>
  );
};

export default CustomizationSettings;
