import React, { useState, useEffect } from 'react';
import { Calendar as CalendarIcon, ChevronDown, X, CalendarDays } from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuSeparator,
} from '@/components/ui/dropdown-menu';
import { cn } from '@/lib/utils';
import { motion, AnimatePresence } from 'framer-motion';

const STORAGE_KEY = 'erp_selected_period';

const PeriodFilter = ({ value, onChange }) => {
  const [isCustomOpen, setIsCustomOpen] = useState(false);
  const [tempStart, setTempStart] = useState('');
  const [tempEnd, setTempEnd] = useState('');
  const [error, setError] = useState('');

  // Initialize from localStorage on mount
  useEffect(() => {
    try {
      const saved = localStorage.getItem(STORAGE_KEY);
      if (saved) {
        const parsed = JSON.parse(saved);
        onChange(parsed);
      }
    } catch (e) {
      console.error('Failed to load period from storage', e);
    }
  }, []);

  // Save to localStorage whenever value changes
  useEffect(() => {
    if (value) {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(value));
    }
  }, [value]);

  // Initialize temp dates when opening custom modal
  useEffect(() => {
    if (isCustomOpen && typeof value === 'object' && value.id === 'custom') {
      setTempStart(value.start);
      setTempEnd(value.end);
    }
  }, [isCustomOpen, value]);

  const periods = [
    { id: 'today', label: "Aujourd'hui" },
    { id: 'week', label: "Cette semaine" },
    { id: 'month', label: "Ce mois-ci" },
    { id: 'quarter', label: "Ce trimestre" },
    { id: 'year', label: "Cette année" },
    { id: 'all', label: "Tout" },
  ];

  const handleValueChange = (newValue) => {
    if (newValue === 'custom') {
      setIsCustomOpen(true);
      setError('');
    } else {
      onChange(newValue);
    }
  };

  const handleCustomSubmit = () => {
    if (!tempStart || !tempEnd) {
      setError('Veuillez sélectionner les deux dates');
      return;
    }
    if (new Date(tempStart) > new Date(tempEnd)) {
      setError('La date de début doit être avant la date de fin');
      return;
    }
    
    onChange({ id: 'custom', start: tempStart, end: tempEnd });
    setIsCustomOpen(false);
    setError('');
  };

  const handleClose = () => {
    setIsCustomOpen(false);
    setError('');
    setTempStart('');
    setTempEnd('');
  };

  const formatDate = (dateStr) => {
    if (!dateStr) return '';
    const d = new Date(dateStr);
    return d.toLocaleDateString('fr-FR', { day: 'numeric', month: 'short' });
  };

  const getLabel = () => {
    if (typeof value === 'object' && value.id === 'custom') {
      return `${formatDate(value.start)} - ${formatDate(value.end)}`;
    }
    return periods.find(p => p.id === value)?.label || "Période";
  };

  const isCustomActive = typeof value === 'object' && value.id === 'custom';

  return (
    <>
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <button className={cn(
            "inline-flex items-center justify-center gap-2 px-3 py-2 text-sm font-medium border rounded-xl transition-all shadow-sm",
            isCustomActive
              ? "bg-[#007E45]/10 border-[#007E45] text-[#007E45]" 
              : "bg-white dark:bg-gray-950 border-gray-200 dark:border-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-900"
          )}>
            <CalendarIcon className="w-4 h-4 opacity-70" />
            <span className="hidden sm:inline truncate max-w-[150px]">{getLabel()}</span>
            <ChevronDown className="w-3.5 h-3.5 opacity-50" />
          </button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" className="w-[200px] bg-white dark:bg-gray-950 border-gray-200 dark:border-gray-800 rounded-xl">
          <DropdownMenuRadioGroup 
            value={typeof value === 'string' ? value : 'custom'} 
            onValueChange={handleValueChange}
          >
            {periods.map((period) => (
              <DropdownMenuRadioItem 
                key={period.id} 
                value={period.id} 
                className="cursor-pointer rounded-lg"
              >
                {period.label}
              </DropdownMenuRadioItem>
            ))}
            <DropdownMenuSeparator />
            <DropdownMenuRadioItem 
              value="custom" 
              className="cursor-pointer font-medium text-[#007E45] rounded-lg"
            >
              <CalendarDays className="w-4 h-4 mr-2" />
              Personnalisé...
            </DropdownMenuRadioItem>
          </DropdownMenuRadioGroup>
        </DropdownMenuContent>
      </DropdownMenu>

      {/* Custom Range Modal */}
      <AnimatePresence>
        {isCustomOpen && (
          <motion.div 
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm"
            onClick={handleClose}
          >
            <motion.div 
              initial={{ opacity: 0, scale: 0.95, y: 10 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: 10 }}
              transition={{ type: 'spring', damping: 25, stiffness: 300 }}
              className="bg-white dark:bg-gray-950 rounded-2xl shadow-2xl w-full max-w-sm border border-gray-200 dark:border-gray-800 overflow-hidden"
              onClick={(e) => e.stopPropagation()}
            >
              {/* Header */}
              <div className="px-6 py-4 flex justify-between items-center border-b border-gray-100 dark:border-gray-800">
                <h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                  <CalendarDays className="w-5 h-5 text-[#007E45]" />
                  Période personnalisée
                </h3>
                <button 
                  onClick={handleClose}
                  className="p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
                >
                  <X className="w-4 h-4" />
                </button>
              </div>
              
              {/* Content */}
              <div className="p-6 space-y-5">
                {/* Error Message */}
                {error && (
                  <motion.div 
                    initial={{ opacity: 0, y: -10 }}
                    animate={{ opacity: 1, y: 0 }}
                    className="p-3 text-sm bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 rounded-xl border border-red-100 dark:border-red-800 flex items-center gap-2"
                  >
                    <div className="w-1.5 h-1.5 rounded-full bg-red-500 flex-shrink-0" />
                    {error}
                  </motion.div>
                )}
                
                {/* Date Inputs */}
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <label className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                      Date de début
                    </label>
                    <input 
                      type="date" 
                      value={tempStart}
                      onChange={(e) => {
                        setTempStart(e.target.value);
                        setError('');
                      }}
                      className={cn(
                        "w-full px-3 py-2.5 bg-white dark:bg-gray-900 border rounded-xl outline-none transition-all text-sm",
                        "border-gray-200 dark:border-gray-700",
                        "focus:ring-2 focus:ring-[#007E45]/20 focus:border-[#007E45]",
                        "dark:text-white dark:[color-scheme:dark]"
                      )}
                    />
                  </div>
                  <div className="space-y-2">
                    <label className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                      Date de fin
                    </label>
                    <input 
                      type="date" 
                      value={tempEnd}
                      onChange={(e) => {
                        setTempEnd(e.target.value);
                        setError('');
                      }}
                      className={cn(
                        "w-full px-3 py-2.5 bg-white dark:bg-gray-900 border rounded-xl outline-none transition-all text-sm",
                        "border-gray-200 dark:border-gray-700",
                        "focus:ring-2 focus:ring-[#007E45]/20 focus:border-[#007E45]",
                        "dark:text-white dark:[color-scheme:dark]"
                      )}
                    />
                  </div>
                </div>

                {/* Actions */}
                <div className="flex gap-3 pt-2">
                  <button 
                    onClick={handleClose}
                    className="flex-1 px-4 py-2.5 border border-gray-200 dark:border-gray-700 rounded-xl text-gray-600 dark:text-gray-300 font-medium hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
                  >
                    Annuler
                  </button>
                  <button 
                    onClick={handleCustomSubmit}
                    className="flex-1 px-4 py-2.5 bg-[#007E45] text-white rounded-xl font-medium hover:bg-[#006838] transition-colors shadow-lg shadow-green-900/20"
                  >
                    Appliquer
                  </button>
                </div>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
};

export default PeriodFilter;