import React, { useState } from 'react';
import type { FC, KeyboardEvent } from 'react';
import { FiBox, FiHeart, FiInfo, FiMic, FiShoppingCart } from 'react-icons/fi';
import { GoLaw } from 'react-icons/go';
import { PiDotsSixThin } from 'react-icons/pi';

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

type ProductDetailsCardProps = {
  name: string;
  description: string;
  bullets: string[];
  price: number;
  currency?: string;
  imageUrl: string | File | null;
  inStock?: boolean;
  statusLabel?: string;
  likeCount?: number;
  isLiked?: boolean;
  textColor: string;
  buttonColor: string;
  cartIconColor: string;
  popupBorderColorLeft: string;
  popupBorderColorRight: string;
  showPrices?: boolean;
  showAddToCartButton?: boolean;
  onToggleLike?: (liked: boolean) => void;
  onAddToCart?: () => void;
  onShowSimilar?: () => void;
  onAskQuestion?: (question: string) => void;
};

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

const QuestionBar: FC<QuestionBarProps> = ({
  // placeholder,
  popupBorderColorLeft,
  popupBorderColorRight,
  onSubmit,
}) => {
  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 q = value.trim();
    if (!q) return;
    onSubmit?.(q);
    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 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 focus:bg-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 ProductDetailsCard: FC<ProductDetailsCardProps> = ({
  name,
  description,
  bullets,
  price,
  currency = 'USD',
  imageUrl,
  inStock = true,
  statusLabel = 'In stock',
  likeCount = 1,
  isLiked = false,
  buttonColor,
  cartIconColor,
  popupBorderColorLeft,
  popupBorderColorRight,
  textColor,
  showPrices = true,
  showAddToCartButton = true,
  onToggleLike,
  onAddToCart,
  onShowSimilar,
  onAskQuestion,
}) => {
  const displayPrice = `${currency} ${price.toFixed(2)}`;

  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)`,
  };

  const handleLikeClick = () => {
    onToggleLike?.(!isLiked);
  };

  return (
    <div className="flex items-center justify-center p-4 py-8">
      <section
        className="w-full max-w-lg rounded-[24px] border border-white/80 p-6 pb-5 shadow-md backdrop-blur"
        style={cardStyle}
      >
        <header className="mb-4 flex items-center justify-between">
          <div className="flex items-center gap-1.5 text-indigo-400">
            {imageUrl ? (
              <img
                src={
                  imageUrl
                    ? imageUrl instanceof File
                      ? URL.createObjectURL(imageUrl)
                      : imageUrl
                    : ''
                }
                alt="logo"
                className="w-5 h-5"
              />
            ) : (
              <TripleStarsIcon
                className="h-4 w-4"
                colorLeft={popupBorderColorLeft}
                colorRight={popupBorderColorRight}
              />
            )}
          </div>

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

          <div className="flex items-center gap-3 text-sm font-medium text-slate-500">
            <button
              type="button"
              onClick={handleLikeClick}
              className="flex items-center gap-1 rounded-full px-1.5 py-1 hover:bg-white/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-200"
              aria-pressed={isLiked}
              aria-label="Produse preferate"
            >
              <FiHeart
                className={`h-4 w-4 ${
                  isLiked
                    ? 'fill-fuchsia-500 text-fuchsia-500'
                    : 'text-slate-600'
                }`}
              />
              <span>{likeCount}</span>
            </button>

            <DismissIcon className="h-4 w-4 text-slate-400" />
          </div>
        </header>

        <article className="rounded-2xl p-5 border border-white/80 hover:!border-white">
          <div className="flex flex-col gap-5 md:flex-row md:items-start">
            <div className="relative flex-shrink-0">
              <div className="flex h-28 w-24 items-center justify-center rounded-3xl border border-slate-100 bg-slate-50/80 shadow-sm">
                <img
                  src={
                    imageUrl
                      ? imageUrl instanceof File
                        ? URL.createObjectURL(imageUrl)
                        : imageUrl
                      : ''
                  }
                  alt={name}
                  className="h-24 w-20 object-contain"
                />
              </div>
              <button
                type="button"
                onClick={handleLikeClick}
                className="absolute right-1.5 top-1.5 flex h-8 w-8 items-center justify-center rounded-full bg-white text-slate-700 shadow-md hover:bg-slate-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-200"
                aria-label={
                  isLiked ? 'Elimină din favorite' : 'Adaugă la favorite'
                }
                aria-pressed={isLiked}
              >
                <FiHeart
                  className={`h-4 w-4 ${
                    isLiked ? 'fill-fuchsia-500 text-fuchsia-500' : ''
                  }`}
                />
              </button>
            </div>

            <div className="flex-1">
              <div className="mb-2 flex flex-wrap items-center justify-between gap-3">
                <h1
                  className="text-[18px] font-semibold text-slate-900"
                  style={{ color: textColor }}
                >
                  {name}
                </h1>
                {inStock && (
                  <div className="flex items-center gap-2 text-[13px] font-medium text-emerald-600">
                    <span className="h-2 w-2 rounded-full bg-emerald-500" />
                    <span>{statusLabel}</span>
                  </div>
                )}
              </div>

              <p
                className="mb-3 text-xs leading-relaxed text-slate-400"
                style={{ color: textColor }}
              >
                {description}
              </p>

              <ul className="mb-4 space-y-1 text-xs font-semibold text-slate-700">
                {bullets.map(item => (
                  <li
                    key={item}
                    className="flex gap-2"
                    style={{ color: textColor }}
                  >
                    <span className="mt-[2px] text-base leading-none">•</span>
                    <span>{item}</span>
                  </li>
                ))}
              </ul>

              <div className="mt-3 flex items-end justify-between gap-4">
                <div className="flex-1" />
                <div className="flex flex-col items-end gap-4">
                  {showPrices && (
                    <div
                      className="text-[22px] py-2 font-bold tracking-tight text-slate-900"
                      style={{ color: textColor }}
                    >
                      {displayPrice}
                    </div>
                  )}
                  {showAddToCartButton && (
                    <button
                      type="button"
                      onClick={onAddToCart}
                      className="wbm-smart__bg-pink inline-flex items-center gap-2 rounded-lg px-4 py-2.5 text-[14px] font-semibold text-white shadow-md focus-visible:outline-none focus-visible:ring-2"
                      style={{ background: buttonColor, color: cartIconColor }}
                    >
                      <FiShoppingCart className="h-4 w-4" />
                      <span>Add to cart</span>
                    </button>
                  )}
                </div>
              </div>
            </div>
          </div>
        </article>

        <div className="pt-4 flex gap-2 overflow-x-auto no-scrollbar">
          {[
            { title: 'More Details', icon: <FiInfo className="h-3 w-3" /> },
            { title: 'Similar Products', icon: <FiBox className="h-3 w-3" /> },
            {
              title: 'Compare with other',
              icon: <GoLaw className="h-3 w-3" />,
            },
          ].map((item, key) => {
            return (
              <button
                key={key}
                type="button"
                onClick={onShowSimilar}
                className="!inline-flex wbm-smart__card items-center gap-2 rounded-2xl border border-white/80 bg-white/80 px-2 py-1 text-xs 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}
              >
                {item.icon}
                <span style={{ color: textColor }}>{item.title}</span>
              </button>
            );
          })}
        </div>

        <QuestionBar
          placeholder="Find anything..."
          popupBorderColorLeft={popupBorderColorLeft}
          popupBorderColorRight={popupBorderColorRight}
          onSubmit={onAskQuestion}
        />
      </section>
    </div>
  );
};
