import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { X, Palette, Loader2, Check } from 'lucide-react';
import { useBodyScrollLock } from '../hooks/useBodyScrollLock';
import type { UserPreferences } from '../types';
import { COLOR_SCHEMES } from '../types';

interface PreferencesModalProps {
  isOpen: boolean;
  onClose: () => void;
  preferences: UserPreferences;
  onSave: (prefs: UserPreferences) => Promise<void>;
  onPreview: (schemeId: string) => void;
  saving: boolean;
}

export const PreferencesModal: React.FC<PreferencesModalProps> = ({
  isOpen,
  onClose,
  preferences,
  onSave,
  onPreview,
  saving,
}) => {
  useBodyScrollLock(isOpen);
  const [localPrefs, setLocalPrefs] = useState<UserPreferences>(preferences);

  useEffect(() => {
    if (isOpen) {
      setLocalPrefs(preferences);
    }
  }, [isOpen, preferences]);

  if (!isOpen) return null;

  const handleColorSelect = (schemeId: string) => {
    setLocalPrefs(prev => ({ ...prev, colorScheme: schemeId }));
    onPreview(schemeId);
  };

  const handleSave = async () => {
    await onSave(localPrefs);
    onClose();
  };

  const handleClose = () => {
    onPreview(preferences.colorScheme);
    onClose();
  };

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
      onClick={handleClose}
    >
      <motion.div
        initial={{ scale: 0.9, opacity: 0 }}
        animate={{ scale: 1, opacity: 1 }}
        exit={{ scale: 0.9, opacity: 0 }}
        className="bg-white rounded-2xl max-w-lg w-full shadow-xl max-h-[90vh] overflow-hidden flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="p-6 border-b border-gray-100 flex items-center justify-between bg-white">
          <div className="flex items-center gap-3 text-gray-900">
            <div className="p-2 bg-gray-100 rounded-xl">
              <Palette size={24} />
            </div>
            <div>
              <h2 className="text-xl font-black">Color Scheme</h2>
              <p className="text-sm text-gray-500">Customize your theme</p>
            </div>
          </div>
          <button
            onClick={handleClose}
            className="p-2 hover:bg-gray-100 rounded-xl transition text-gray-400 hover:text-gray-600"
          >
            <X size={24} />
          </button>
        </div>

        <div className="p-6 overflow-y-auto flex-1 bg-gray-50">
          <div className="grid grid-cols-4 gap-3">
            {COLOR_SCHEMES.map((scheme) => (
              <button
                key={scheme.id}
                onClick={() => handleColorSelect(scheme.id)}
                className={`relative aspect-square rounded-xl transition-all ${
                  localPrefs.colorScheme === scheme.id
                    ? 'ring-2 ring-offset-2 ring-gray-800 scale-105'
                    : 'hover:scale-105'
                }`}
                style={{ background: `linear-gradient(135deg, ${scheme.primary} 0%, ${scheme.primaryDarker} 100%)` }}
                title={scheme.name}
              >
                {localPrefs.colorScheme === scheme.id && (
                  <div className="absolute inset-0 flex items-center justify-center">
                    <Check size={24} className="text-white drop-shadow-lg" />
                  </div>
                )}
              </button>
            ))}
          </div>
          <p className="text-sm text-gray-500 mt-3 text-center">
            {COLOR_SCHEMES.find(s => s.id === localPrefs.colorScheme)?.name || 'Select a color'}
          </p>
        </div>

        <div className="p-6 border-t border-gray-100 flex gap-3">
          <button
            onClick={handleClose}
            className="flex-1 py-3 rounded-xl font-bold border-2 border-gray-200 text-gray-600 hover:bg-gray-50 transition"
          >
            Cancel
          </button>
          <button
            onClick={handleSave}
            disabled={saving}
            className="flex-1 py-3 rounded-xl font-bold bg-theme-primary text-white hover:bg-theme-primary/90 transition disabled:opacity-50 flex items-center justify-center gap-2"
          >
            {saving ? (
              <>
                <Loader2 size={20} className="animate-spin" />
                Saving...
              </>
            ) : (
              'Save'
            )}
          </button>
        </div>
      </motion.div>
    </motion.div>
  );
};
