import React, { useState } from 'react';
import type { FC, KeyboardEvent } from 'react';
import {
  FiArrowLeft,
  FiHeart,
  FiMic,
  FiShoppingCart,
  FiX,
} from 'react-icons/fi';
import { PiDotsSixThin } from 'react-icons/pi';

import DismissIcon from '../icons/DismissIcon';
import {
  DEFAULT_BLUE_RGB,
  DEFAULT_PINK_RGB,
  hexToRgb,
} from '../../utils/colors';
import TripleStarsIcon from '../icons/TripleStarsIcon';

type SessionProduct = {
  id: string;
  name: string;
  imageUrl: string | File | null;
  price: number;
  oldPrice?: number;
  currency?: string;
  liked?: boolean;
};

type LatestArrivalsSessionCardProps = {
  title?: string;
  introTitle?: string;
  introBody?: React.ReactNode;
  matchTitle?: string;
  suggestionText?: string[];
  products: SessionProduct[];
  favoritesCount?: number;
  textColor: string;
  buttonColor: string;
  cartIconColor: string;
  popupBorderColorLeft: string;
  popupBorderColorRight: string;
  showPrices?: boolean;
  showAddToCartButton?: boolean;
  onBack?: () => void;
  onToggleLikeProduct?: (id: string, liked: boolean) => void;
  onDislikeProduct?: (id: string) => void;
  onAddToCart?: (id: string) => void;
  onSuggestionClick?: () => void;
  onAsk?: (question: string) => void;
};

type ProductCardProps = {
  product: SessionProduct;
  textColor: string;
  buttonColor: string;
  popupBorderColorLeft: string;
  cartIconColor?: string;
  showPrices: boolean;
  showAddToCartButton: boolean;
  onToggleLike?: (id: string, liked: boolean) => void;
  onDislike?: (id: string) => void;
  onAddToCart?: (id: string) => void;
};

const ProductCard: FC<ProductCardProps> = ({
  product,
  onToggleLike,
  onDislike,
  onAddToCart,
  buttonColor,
  textColor,
  cartIconColor,
  popupBorderColorLeft,
  showPrices,
  showAddToCartButton,
}) => {
  const {
    id,
    name,
    imageUrl,
    price,
    oldPrice,
    currency = '$',
    liked,
  } = product;

  const formattedPrice = `${currency} ${price.toLocaleString(undefined, {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })}`;

  const formattedOldPrice =
    oldPrice != null
      ? `${currency} ${oldPrice.toLocaleString(undefined, {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        })}`
      : undefined;

  const handleLike = () => {
    onToggleLike?.(id, !liked);
  };

  const handleDislike = () => {
    onDislike?.(id);
  };

  const handleAddToCart = () => {
    onAddToCart?.(id);
  };

  const customStyles = {
    '--accent-pink-rgb': hexToRgb(popupBorderColorLeft || '') || '0, 0, 0',
  } as React.CSSProperties;

  return (
    <article
      className="wbm-smart__card relative w-44 flex flex-col flex-shrink-0 justify-between rounded-2xl bg-white/35 p-3 shadow-sm border border-white"
      style={customStyles}
    >
      {/* Image */}
      <div className="relative flex h-32 w-full items-center justify-center overflow-hidden rounded-2xl bg-slate-50">
        <img
          src={
            imageUrl
              ? imageUrl instanceof File
                ? URL.createObjectURL(imageUrl)
                : imageUrl
              : '/handbag.jpg'
          }
          alt={name}
          className="h-full w-full object-cover"
        />

        {/* Like */}
        <button
          type="button"
          onClick={handleLike}
          className="absolute left-1/2 top-2 flex h-8 w-8 -translate-x-1/2 items-center justify-center rounded-full text-slate-700 shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-200"
          aria-pressed={liked}
          style={{
            color: liked ? textColor : '#000000',
            background: liked ? buttonColor : '#FFFFFF',
          }}
        >
          <FiHeart
            className="h-4 w-4"
            style={{
              fill: liked ? '#FFFFFF' : undefined,
              color: liked ? buttonColor : textColor,
            }}
          />
        </button>

        {/* Dislike (X) */}
        <button
          type="button"
          onClick={handleDislike}
          className="absolute right-2 top-2 flex h-8 w-8 items-center justify-center rounded-full bg-white text-slate-600 shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-rose-200"
          style={{ color: textColor }}
        >
          <FiX className="h-4 w-4" />
        </button>
      </div>

      {/* Title */}
      <h3
        className="mt-3 line-clamp-2 text-[13px] font-medium leading-snug text-slate-900"
        style={{ color: textColor }}
      >
        {name}
      </h3>

      {/* Prices */}
      {showPrices && (
        <div className="mt-3 space-y-1">
          <p
            className="text-[18px] font-semibold tracking-tight text-slate-900"
            style={{ color: textColor }}
          >
            {formattedPrice}
          </p>
          {formattedOldPrice && (
            <p className="text-[13px] font-medium text-slate-400 line-through">
              {formattedOldPrice}
            </p>
          )}
        </div>
      )}

      {/* Add to cart */}
      {showAddToCartButton && (
        <button
          type="button"
          onClick={handleAddToCart}
          className="mt-3 inline-flex h-9 w-9 items-center justify-center rounded-lg bg-fuchsia-700 text-white shadow-md hover:bg-fuchsia-800 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-fuchsia-300"
          style={{ color: cartIconColor, background: buttonColor }}
        >
          <FiShoppingCart className="h-4 w-4" />
        </button>
      )}
    </article>
  );
};

type SessionInputBarProps = {
  placeholder: string;
  onSubmit?: (val: string) => void;
  popupBorderColorLeft?: string;
  popupBorderColorRight?: string;
};

const SessionInputBar: FC<SessionInputBarProps> = ({
  // placeholder,
  onSubmit,
  popupBorderColorLeft,
  popupBorderColorRight,
}) => {
  const [value, setValue] = useState('');

  const customStyles = {
    '--accent-pink-rgb':
      hexToRgb(popupBorderColorLeft || '') || DEFAULT_PINK_RGB,
    '--accent-blue-rgb':
      hexToRgb(popupBorderColorRight || '') || DEFAULT_BLUE_RGB,
  } as React.CSSProperties;

  const handleSubmit = () => {
    const trimmed = value.trim();
    if (!trimmed) return;
    onSubmit?.(trimmed);
    setValue('');
  };

  const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleSubmit();
    }
  };

  return (
    <div className="py-2 pt-4">
      <div
        className="wbm-smart__custom-background rounded-xl p-0.5"
        style={customStyles}
      >
        <div className="w-full flex items-center gap-3 rounded-xl bg-white px-3 py-2.5 shadow-sm backdrop-blur-sm">
          <FiMic className="h-4 w-4 flex-shrink-0 text-slate-400" />
          <div className="relative flex-1">
            <input
              className="h-6 w-full rounded-xl border border-transparent bg-white focus:bg-white pl-1 pr-10 text-[13px] text-slate-700 placeholder:text-slate-400 focus:border-none focus:outline-none focus:ring-0 focus:ring-white"
              placeholder="Find something"
              value={value}
              onChange={e => setValue(e.target.value)}
              onKeyDown={handleKeyDown}
            />
            <button
              type="button"
              onClick={handleSubmit}
              className="absolute right-0 top-1/2 flex h-7 w-7 -translate-y-1/2 items-center justify-center rounded-full bg-white"
            >
              <TripleStarsIcon
                colorLeft={popupBorderColorLeft}
                colorRight={popupBorderColorRight}
              />
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export const LatestArrivalsSessionCard: FC<LatestArrivalsSessionCardProps> = ({
  title = 'Latest arrivals',
  // introTitle = "Latest arrivals",
  introBody,
  matchTitle = 'New arrivals match your broad interests.',
  suggestionText,
  products,
  favoritesCount = 3,
  buttonColor,
  textColor,
  popupBorderColorLeft,
  popupBorderColorRight,
  cartIconColor,
  showPrices = true,
  showAddToCartButton = true,
  onBack,
  onToggleLikeProduct,
  onDislikeProduct,
  onAddToCart,
  onSuggestionClick,
  onAsk,
}) => {
  const customStyles = {
    '--accent-pink-rgb': hexToRgb(popupBorderColorLeft || '') || '0, 0, 0',
  } as React.CSSProperties;

  const leftRgb = hexToRgb(popupBorderColorLeft || '');
  const rightRgb = hexToRgb(popupBorderColorRight || '');

  const cardStyle: React.CSSProperties = {
    background: `linear-gradient(
        to bottom,
        rgba(${leftRgb}, 0.12) 0%,
        rgba(${leftRgb}, 0.12) 40%,
        rgba(${rightRgb}, 0.18) 100%
      )`,
    backdropFilter: 'blur(12px)',
    boxShadow: `0 25px 50px -12px rgba(${rightRgb}, 0.35)`,
  };

  return (
    <div className="flex items-center justify-center p-4">
      <section
        className="flex h-[680px] w-full max-w-md flex-col rounded-[24px] border border-white/80 p-4 shadow-md backdrop-blur"
        style={cardStyle}
      >
        {/* Top bar */}
        <header className="flex items-center justify-between gap-3">
          {/* Back */}
          <button
            type="button"
            onClick={onBack}
            className="inline-flex items-center gap-2 rounded-full bg-white/80 px-3 py-1.5 text-[13px] font-medium text-slate-700 shadow-sm hover:bg-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-200"
          >
            <FiArrowLeft className="h-4 w-4" />
            <span>Back</span>
          </button>

          {/* Handle */}
          <div className="flex items-center gap-1.5 text-sm font-medium text-slate-500">
            <PiDotsSixThin className="h-4 w-4" />
          </div>

          {/* Favorites + minimize */}
          <div className="flex items-center gap-4 text-sm text-slate-600">
            <div className="flex items-center gap-1">
              <FiHeart className="h-4 w-4" />
              <span className="text-[13px] font-medium">{favoritesCount}</span>
            </div>
            <DismissIcon className="h-4 w-4 text-slate-400" />
          </div>
        </header>

        {/* Scrollable content */}
        <div className="mt-4 flex-1 overflow-y-auto pr-1">
          {/* Title */}
          <h1
            className="pb-2 text-sm font-bold text-slate-900"
            style={{ color: textColor }}
          >
            {title}
          </h1>

          {/* Message bubble */}
          <div className="rounded-2xl bg-white/35 px-4 py-4 shadow-sm border border-white">
            {introBody ? (
              introBody
            ) : (
              <>
                <p
                  className="mb-3 text-[13px] leading-relaxed text-slate-700"
                  style={{ color: textColor }}
                >
                  We have some wonderful new arrivals that just came in! Are you
                  looking for something in tech, fashion, or perhaps a home
                  accessory?
                </p>
                <p
                  className="text-[13px] leading-relaxed text-slate-700"
                  style={{ color: textColor }}
                >
                  For example, we recently added the{' '}
                  <strong>Google Pixel 9 Pro</strong>, which offers cutting-edge
                  AI and camera features. If you&apos;re looking for fashion,
                  the elegant <strong>Verona Linen Wrap Skirt</strong> is a
                  beautiful new piece designed for graceful movement. We also
                  have the stylish <strong>Leather Wallet Organizer</strong> for
                  keeping your essentials secure and accessible.
                </p>
              </>
            )}
          </div>

          {/* Match title */}
          <p
            className="mt-6 mb-3 text-[14px] font-semibold text-slate-900"
            style={{ color: textColor }}
          >
            {matchTitle}
          </p>

          {/* Product carousel */}
          <div className="-mx-1 mb-4">
            <div className="flex gap-3 overflow-x-auto px-1 pb-2 no-scrollbar">
              {products.map(p => (
                <ProductCard
                  key={p.id}
                  product={p}
                  onToggleLike={onToggleLikeProduct}
                  onDislike={onDislikeProduct}
                  onAddToCart={onAddToCart}
                  buttonColor={buttonColor}
                  textColor={textColor}
                  cartIconColor={cartIconColor}
                  popupBorderColorLeft={popupBorderColorLeft}
                  showPrices={showPrices}
                  showAddToCartButton={showAddToCartButton}
                />
              ))}
            </div>
          </div>

          {/* Suggestion chip */}
          <div className="flex flex-wrap gap-2 pb-5">
            {suggestionText &&
              suggestionText.map((suggestion, key) => {
                return (
                  <button
                    key={key}
                    type="button"
                    onClick={onSuggestionClick}
                    className="!inline-flex wbm-smart__card items-center gap-2 rounded-2xl border border-white/80 bg-white/80 px-4 py-2 text-[14px] font-medium text-slate-800 shadow-sm backdrop-blur-sm hover:-translate-y-0.5 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-200"
                    style={customStyles}
                  >
                    {suggestion}
                  </button>
                );
              })}
          </div>
        </div>

        {/* Sticky bottom input */}
        <SessionInputBar
          placeholder="Find something new to try..."
          onSubmit={onAsk}
          popupBorderColorLeft={popupBorderColorLeft}
          popupBorderColorRight={popupBorderColorRight}
        />
      </section>
    </div>
  );
};
