import { motion, AnimatePresence } from "motion/react";
import { useEffect } from "react";

interface ChatHistoryItem {
  id: string;
  title: string;
  date: string;
  lastMessage: string;
}

interface ChatHistoryModalProps {
  isOpen: boolean;
  onClose: () => void;
  isLoading?: boolean;
  historyItems: ChatHistoryItem[];
  onSelectChat: (chatId: string) => void;
}

const modalStyles = {
  overlay: {
    backgroundColor: "rgba(0, 0, 0, 0.72)",
  },
  container: {
    backgroundImage:
      "linear-gradient(180deg, rgba(46, 27, 61, 0.95) 0%, rgba(35, 24, 62, 0.98) 100%), linear-gradient(120deg, #7c3aed 0%, #f97316 58%, #facc15 100%)",
    backgroundOrigin: "border-box",
    backgroundClip: "padding-box, border-box",
    border: "0.5px solid transparent",
    boxShadow:
      "0 -7px 20px rgba(7, 0, 18, 0.4), 0 10px 22px rgba(5, 2, 12, 0.35), inset 0 1px 0 rgba(255, 255, 255, 0.16), inset 0 -2px 0 rgba(12, 7, 27, 0.62)",
    backdropFilter: "blur(14px)",
    WebkitBackdropFilter: "blur(14px)",
  },
  chatItem: {
    background: "rgba(255, 255, 255, 0.07)",
    border: "1px solid rgba(255, 255, 255, 0.12)",
    boxShadow: "0 8px 18px rgba(8, 4, 20, 0.24), inset 0 1px 0 rgba(255,255,255,0.1)",
  },
  closeButton: {
    background:
      "linear-gradient(145deg, rgba(240, 110, 168, 0.95) 0%, rgba(201, 87, 156, 0.94) 52%, rgba(138, 79, 207, 0.93) 100%)",
    boxShadow: "0 0 16px rgba(240, 110, 168, 0.32), inset 0 1px 0 rgba(255,255,255,0.22)",
    border: "1px solid rgba(255, 189, 228, 0.5)",
  },
};

export function ChatHistoryModal({
  isOpen,
  onClose,
  isLoading = false,
  historyItems,
  onSelectChat,
}: ChatHistoryModalProps) {
  // Close on Escape key
  useEffect(() => {
    const handleEsc = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    if (isOpen) {
      window.addEventListener("keydown", handleEsc);
      return () => window.removeEventListener("keydown", handleEsc);
    }
  }, [isOpen, onClose]);

  return (
    <AnimatePresence>
      {isOpen && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="fixed inset-0 z-[100] flex items-center justify-center p-3"
          style={modalStyles.overlay}
          onClick={onClose}
        >
          <motion.div
            initial={{ opacity: 0, y: 14 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: 10 }}
            onClick={(e) => e.stopPropagation()}
            className="flex w-full max-w-md min-h-0 flex-col overflow-hidden rounded-3xl"
            style={{ ...modalStyles.container, maxHeight: "min(78dvh, 620px)" }}
          >
            {/* Header */}
            <div className="border-b px-5 py-4" style={{ borderColor: "rgba(255, 255, 255, 0.12)" }}>
              <h3
                className="text-center text-base font-extrabold text-[#FBE7F5]"
                style={{ textShadow: "0 2px 8px rgba(255, 119, 202, 0.3)" }}
              >
                تاریخچه گفتگوها
              </h3>
            </div>

            {/* Content */}
            <div
              className="min-h-0 flex-1 overflow-y-auto px-4 py-4"
              style={{
                maxHeight:
                  "calc(100dvh - env(safe-area-inset-top, 0px) - env(safe-area-inset-bottom, 0px) - 180px)",
                scrollbarWidth: "none",
                msOverflowStyle: "none",
              }}
            >
              {isLoading ? (
                <div className="flex h-40 items-center justify-center">
                  <div className="text-center">
                    <div className="mx-auto mb-3 h-10 w-10 animate-spin rounded-full border-4 border-[#ffd6f0]/30 border-t-[#ff79cf]" />
                    <p className="text-xs font-bold text-[#FBE7F5]">در حال بارگذاری...</p>
                  </div>
                </div>
              ) : historyItems.length === 0 ? (
                <div className="flex h-40 items-center justify-center text-center">
                  <p className="text-sm font-bold text-[#F2DFF0]/72">تاریخچه‌ای پیدا نشد</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {historyItems.map((chat, index) => (
                    <motion.button
                      key={chat.id}
                      initial={{ opacity: 0, y: 8 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: index * 0.05, duration: 0.2 }}
                      whileTap={{ scale: 0.95 }}
                      onClick={() => {
                        onClose();
                        onSelectChat(chat.id);
                      }}
                      className="w-full rounded-2xl p-3.5 text-right"
                      style={modalStyles.chatItem}
                    >
                      <div className="flex items-start justify-between gap-2">
                        <h4 className="line-clamp-1 text-sm font-bold text-[#FBE7F5]">
                          {chat.title}
                        </h4>
                        <span className="h-2 w-2 shrink-0 rounded-full bg-[#ff78c6]" />
                      </div>
                      {!!chat.lastMessage && (
                        <p className="mt-1 line-clamp-1 text-xs text-[#F2DFF0]/74">
                          {chat.lastMessage}
                        </p>
                      )}
                      <p className="mt-1 text-[11px] text-[#F2DFF0]/62">{chat.date}</p>
                      <div className="mt-2 h-px w-full bg-white/8" />
                    </motion.button>
                  ))}
                </div>
              )}
            </div>

            {/* Footer */}
            <div
              className="border-t px-5 pb-[calc(env(safe-area-inset-bottom,0px)+12px)] pt-3"
              style={{ borderColor: "rgba(255, 255, 255, 0.12)" }}
            >
              <motion.button
                whileTap={{ scale: 0.96 }}
                onClick={onClose}
                className="w-full rounded-full py-3 text-sm font-bold text-white"
                style={modalStyles.closeButton}
              >
                بستن
              </motion.button>
            </div>
          </motion.div>
        </motion.div>
      )}
      <style>{`
        .min-h-0.flex-1.overflow-y-auto::-webkit-scrollbar {
          display: none;
        }
      `}</style>
    </AnimatePresence>
  );
}
