import React, { useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Battery, BatteryLow, BatteryMedium, BatteryFull, Sparkles } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useADHDMode } from '../providers/ADHDModeProvider';

interface EnergyCheckInProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onComplete?: (level: string) => void;
}

type EnergyLevel = 'low' | 'medium' | 'high';

const energyLevels: { id: EnergyLevel; icon: React.ComponentType<{ className?: string }>; color: string }[] = [
  { id: 'low', icon: BatteryLow, color: 'text-red-500 bg-red-500/10 border-red-500/30 hover:bg-red-500/20' },
  { id: 'medium', icon: BatteryMedium, color: 'text-yellow-500 bg-yellow-500/10 border-yellow-500/30 hover:bg-yellow-500/20' },
  { id: 'high', icon: BatteryFull, color: 'text-green-500 bg-green-500/10 border-green-500/30 hover:bg-green-500/20' },
];

export function EnergyCheckIn({ open, onOpenChange, onComplete }: EnergyCheckInProps) {
  const { t } = useTranslation();
  const { settings } = useADHDMode();
  const queryClient = useQueryClient();

  const [selectedLevel, setSelectedLevel] = useState<EnergyLevel | null>(null);
  const [notes, setNotes] = useState('');

  const logMutation = useMutation({
    mutationFn: async ({ energyLevel, notes }: { energyLevel: string; notes?: string }) => {
      const res = await fetch('/api/energy/log', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ energyLevel, notes }),
      });
      if (!res.ok) throw new Error('Failed to log energy');
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/api/user'] });
      onComplete?.(selectedLevel!);
      onOpenChange(false);
      setSelectedLevel(null);
      setNotes('');
    },
  });

  const handleSubmit = () => {
    if (!selectedLevel) return;
    logMutation.mutate({ energyLevel: selectedLevel, notes: notes || undefined });
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Battery className="h-5 w-5 text-primary" />
            {t('adhd.energy.title')}
          </DialogTitle>
          <DialogDescription>
            {t('adhd.energy.description')}
          </DialogDescription>
        </DialogHeader>

        <div className="py-4">
          {/* Energy level selection */}
          <div className="grid grid-cols-3 gap-3 mb-6">
            {energyLevels.map((level) => {
              const Icon = level.icon;
              const isSelected = selectedLevel === level.id;

              return (
                <motion.button
                  key={level.id}
                  whileHover={{ scale: settings.reducedAnimations ? 1 : 1.02 }}
                  whileTap={{ scale: settings.reducedAnimations ? 1 : 0.98 }}
                  onClick={() => setSelectedLevel(level.id)}
                  className={`
                    flex flex-col items-center gap-2 p-4 rounded-xl border-2
                    transition-all duration-200
                    ${level.color}
                    ${isSelected ? 'ring-2 ring-offset-2 ring-primary' : ''}
                    ${settings.largerTargets ? 'min-h-[100px]' : 'min-h-[80px]'}
                  `}
                >
                  <Icon className="h-8 w-8" />
                  <span className="font-medium text-sm">
                    {t(`adhd.energy.levels.${level.id}`)}
                  </span>
                </motion.button>
              );
            })}
          </div>

          {/* Energy-based suggestions */}
          <AnimatePresence>
            {selectedLevel && (
              <motion.div
                initial={{ opacity: 0, height: 0 }}
                animate={{ opacity: 1, height: 'auto' }}
                exit={{ opacity: 0, height: 0 }}
                className="mb-4"
              >
                <div className="bg-muted/50 rounded-lg p-4">
                  <div className="flex items-start gap-2">
                    <Sparkles className="h-4 w-4 text-primary mt-0.5" />
                    <div>
                      <p className="font-medium text-sm mb-1">
                        {t(`adhd.energy.suggestions.${selectedLevel}.title`)}
                      </p>
                      <p className="text-xs text-muted-foreground">
                        {t(`adhd.energy.suggestions.${selectedLevel}.description`)}
                      </p>
                    </div>
                  </div>
                </div>
              </motion.div>
            )}
          </AnimatePresence>

          {/* Optional notes */}
          <div className="mb-4">
            <label className="text-sm font-medium mb-2 block">
              {t('adhd.energy.notesLabel')} <span className="text-muted-foreground">({t('common.optional')})</span>
            </label>
            <Textarea
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              placeholder={t('adhd.energy.notesPlaceholder')}
              rows={2}
              className="resize-none"
            />
          </div>

          {/* Submit button */}
          <Button
            onClick={handleSubmit}
            disabled={!selectedLevel || logMutation.isPending}
            className={`w-full ${settings.largerTargets ? 'h-12' : 'h-10'}`}
          >
            {logMutation.isPending ? t('common.saving') : t('adhd.energy.submit')}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
