import React, { useState, useMemo, useCallback } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  MagnifyingGlassIcon,
  XMarkIcon,
  HashtagIcon,
} from "@heroicons/react/24/outline";

interface ShowStringListProps {
  strings: string[];
  title?: string;
  maxItems?: number;
  showSearch?: boolean;
  showNumbers?: boolean;
  className?: string;
  emptyMessage?: string;
  searchPlaceholder?: string;
  onItemClick?: (item: string, index: number) => void;
}

const ShowStringList: React.FC<ShowStringListProps> = ({
  strings = [],
  title,
  maxItems = 50,
  showSearch = true,
  showNumbers = true,
  className = "",
  emptyMessage = "هیچ آیتمی یافت نشد",
  searchPlaceholder = "جستجو...",
  onItemClick,
}) => {
  const [searchTerm, setSearchTerm] = useState("");
  const [isSearchFocused, setIsSearchFocused] = useState(false);

  const filteredStrings = useMemo(() => {
    if (!searchTerm.trim()) return strings.slice(0, maxItems);
    return strings
      .filter((str) => str.toLowerCase().includes(searchTerm.toLowerCase()))
      .slice(0, maxItems);
  }, [strings, searchTerm, maxItems]);

  const hasMoreItems = strings.length > maxItems;
  const hasSearchResults = searchTerm.trim() && filteredStrings.length > 0;

  const handleSearchChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      setSearchTerm(e.target.value);
    },
    []
  );

  const clearSearch = useCallback(() => {
    setSearchTerm("");
  }, []);

  const handleItemClick = useCallback(
    (item: string, index: number) => {
      onItemClick?.(item, index);
    },
    [onItemClick]
  );

  const itemVariants = {
    hidden: { opacity: 0, y: 8, scale: 0.9, filter: "blur(4px)" },
    visible: (i: number) => ({
      opacity: 1,
      y: 0,
      scale: 1,
      filter: "blur(0px)",
      transition: {
        delay: i * 0.03,
        duration: 0.4,
        ease: [0.16, 1, 0.3, 1],
        filter: { duration: 0.3 },
      },
    }),
    exit: {
      opacity: 0,
      y: -8,
      scale: 0.9,
      filter: "blur(4px)",
      transition: {
        duration: 0.25,
        ease: [0.4, 0, 1, 1],
      },
    },
    hover: {
      scale: 1.02,
      y: -2,
      transition: { duration: 0.2, ease: [0.16, 1, 0.3, 1] },
    },
    tap: {
      scale: 0.98,
      transition: { duration: 0.1 },
    },
  };

  const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: {
        staggerChildren: 0.03,
        delayChildren: 0.1,
      },
    },
  };

  if (!strings || strings.length === 0) {
    return (
      <div className={`text-center py-8 ${className}`}>
        <div className="text-gray-500 dark:text-gray-400 text-sm">
          {emptyMessage}
        </div>
      </div>
    );
  }

  return (
    <div className={`space-y-3 ${className}`}>
      {title && (
        <div className="flex items-center gap-2">
          <HashtagIcon className="w-4 h-4 text-primary-500" />
          <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300">
            {title}
          </h3>
          <span className="text-xs text-gray-500 dark:text-gray-400">
            ({strings.length})
          </span>
        </div>
      )}

      {showSearch && strings.length > 1 && (
        <div className="relative">
          <div className="relative">
            <MagnifyingGlassIcon className="absolute right-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              placeholder={searchPlaceholder}
              value={searchTerm}
              onChange={handleSearchChange}
              onFocus={() => setIsSearchFocused(true)}
              onBlur={() => setIsSearchFocused(false)}
              className={`w-full px-3 py-1.5 pr-10 text-sm border rounded-md transition-all duration-200 ${
                isSearchFocused
                  ? "border-primary-500 ring-1 ring-primary-500/30 shadow-sm"
                  : "border-gray-300 dark:border-gray-600"
              } bg-white dark:bg-dark-700 text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400 focus:outline-none`}
              aria-label="جستجو در لیست"
            />
            {searchTerm && (
              <button
                onClick={clearSearch}
                className="absolute left-2.5 top-1/2 transform -translate-y-1/2 p-0.5 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-full transition-colors"
                aria-label="پاک کردن جستجو"
              >
                <XMarkIcon className="w-3 h-3 text-gray-500" />
              </button>
            )}
          </div>
          {hasSearchResults && (
            <div className="mt-2 text-xs text-gray-600 dark:text-gray-400">
              {filteredStrings.length} نتیجه از {strings.length} آیتم
            </div>
          )}
        </div>
      )}

      <motion.div
        variants={containerVariants}
        initial="hidden"
        animate="visible"
        className="flex flex-wrap items-center gap-2"
      >
        <AnimatePresence mode="popLayout">
          {filteredStrings.map((str, index) => (
            <motion.button
              key={`${str}-${index}`}
              custom={index}
              variants={itemVariants}
              initial="hidden"
              animate="visible"
              exit="exit"
              whileHover="hover"
              whileTap="tap"
              onClick={() => handleItemClick(str, index)}
              className={`group inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium focus:outline-none focus:ring-2 focus:ring-primary-500/50 ${
                index % 2 === 0
                  ? "bg-gradient-to-r from-primary-100/80 to-primary-50/80 dark:from-dark-600/80 dark:to-dark-700/80 text-primary-700 dark:text-primary-300 border border-primary-200/50 dark:border-dark-500/50"
                  : "bg-gradient-to-r from-secondary-100/80 to-secondary-50/80 dark:from-dark-700/80 dark:to-dark-800/80 text-secondary-700 dark:text-secondary-300 border border-secondary-200/50 dark:border-dark-600/50"
              } hover:shadow-lg hover:border-opacity-100`}
              aria-label={`آیتم ${index + 1}: ${str}`}
            >
              {showNumbers && (
                <span className="flex-shrink-0 w-4 h-4 bg-white/60 dark:bg-black/30 rounded-full flex items-center justify-center text-[10px] font-bold">
                  {index + 1}
                </span>
              )}
              <span className="truncate max-w-[180px]" title={str}>
                {str}
              </span>
            </motion.button>
          ))}
        </AnimatePresence>
      </motion.div>

      {hasMoreItems && !searchTerm && (
        <div className="text-center">
          <span className="text-xs text-gray-500 dark:text-gray-400 bg-gray-100 dark:bg-gray-800 px-2 py-0.5 rounded-md">
            و {strings.length - maxItems} آیتم دیگر...
          </span>
        </div>
      )}

      {searchTerm && filteredStrings.length === 0 && (
        <div className="text-center py-6">
          <div className="text-gray-500 dark:text-gray-400 text-sm">
            هیچ نتیجه‌ای برای &quot;{searchTerm}&quot; یافت نشد
          </div>
        </div>
      )}
    </div>
  );
};

export default ShowStringList;
