import { useEffect, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useBuildProgress, BuildProgress } from '@/hooks/useBuildProgress';
import { useBrowserNotifications } from '@/hooks/useBrowserNotifications';
import { useNotificationSounds } from '@/hooks/useNotificationSounds';
import { useUserPreferencesStore } from '@/stores/useUserPreferencesStore';
import { Progress } from '@/components/ui/progress';
import { Button } from '@/components/ui/button';
import { 
  Smartphone, 
  Apple, 
  CheckCircle2, 
  XCircle, 
  Loader2, 
  Download,
  X,
  Volume2,
  VolumeX
} from 'lucide-react';
import { useToast } from '@/hooks/use-toast';

interface BuildProgressPanelProps {
  className?: string;
}

const BuildProgressPanel = ({ className }: BuildProgressPanelProps) => {
  const { toast } = useToast();
  const { notifyBuildComplete, notifyBuildFailed, permission, requestPermission } = useBrowserNotifications();
  const { playCelebrate, playError } = useNotificationSounds();
  const { notifications, toggleNotification } = useUserPreferencesStore();
  const hasRequestedPermission = useRef(false);

  // Request notification permission on first build
  useEffect(() => {
    if (!hasRequestedPermission.current && permission === 'default') {
      hasRequestedPermission.current = true;
      requestPermission();
    }
  }, [permission, requestPermission]);
  
  const { activeBuilds, hasActiveBuilds, untrackBuild } = useBuildProgress({
    onComplete: (build) => {
      // Play sound if enabled
      if (notifications.soundEnabled) {
        playCelebrate();
      }
      
      // Send browser notification if enabled
      if (notifications.push && notifications.buildUpdates) {
        notifyBuildComplete(build.app_name);
      }
      
      toast({
        title: 'Build Complete! 🎉',
        description: `${build.app_name} (${build.platform.toUpperCase()}) is ready for download.`,
      });
    },
    onError: (build) => {
      // Play error sound if enabled
      if (notifications.soundEnabled) {
        playError();
      }
      
      // Send browser notification if enabled
      if (notifications.push && notifications.buildUpdates) {
        notifyBuildFailed(build.app_name, build.error_message);
      }
      
      toast({
        title: 'Build Failed',
        description: build.error_message || `Failed to build ${build.app_name}`,
        variant: 'destructive',
      });
    },
  });

  if (!hasActiveBuilds) {
    return null;
  }

  const getPlatformIcon = (platform: string) => {
    return platform === 'ios' ? (
      <Apple className="w-4 h-4" />
    ) : (
      <Smartphone className="w-4 h-4" />
    );
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'completed':
        return <CheckCircle2 className="w-4 h-4 text-accent" />;
      case 'failed':
        return <XCircle className="w-4 h-4 text-destructive" />;
      default:
        return <Loader2 className="w-4 h-4 animate-spin text-primary" />;
    }
  };

  return (
    <AnimatePresence>
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        exit={{ opacity: 0, y: 20 }}
        className={`fixed bottom-20 md:bottom-6 right-4 z-50 w-80 ${className}`}
      >
        <div className="glass-card rounded-xl p-4 shadow-2xl border border-primary/20">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <h4 className="font-display font-semibold text-sm text-foreground">
                Active Builds
              </h4>
              <Button
                variant="ghost"
                size="icon"
                className="h-6 w-6"
                onClick={() => toggleNotification('soundEnabled')}
                title={notifications.soundEnabled ? 'Mute sounds' : 'Enable sounds'}
              >
                {notifications.soundEnabled ? (
                  <Volume2 className="w-3.5 h-3.5 text-muted-foreground" />
                ) : (
                  <VolumeX className="w-3.5 h-3.5 text-muted-foreground" />
                )}
              </Button>
            </div>
            <span className="text-xs text-muted-foreground">
              {activeBuilds.length} in progress
            </span>
          </div>

          <div className="space-y-3 max-h-64 overflow-y-auto">
            {activeBuilds.map((build) => (
              <BuildItem
                key={build.id}
                build={build}
                onDismiss={() => untrackBuild(build.id)}
                getPlatformIcon={getPlatformIcon}
                getStatusIcon={getStatusIcon}
              />
            ))}
          </div>
        </div>
      </motion.div>
    </AnimatePresence>
  );
};

interface BuildItemProps {
  build: BuildProgress;
  onDismiss: () => void;
  getPlatformIcon: (platform: string) => React.ReactNode;
  getStatusIcon: (status: string) => React.ReactNode;
}

const BuildItem = ({ build, onDismiss, getPlatformIcon, getStatusIcon }: BuildItemProps) => {
  return (
    <motion.div
      layout
      initial={{ opacity: 0, scale: 0.95 }}
      animate={{ opacity: 1, scale: 1 }}
      exit={{ opacity: 0, scale: 0.95 }}
      className="bg-background/50 rounded-lg p-3 border border-border/50"
    >
      <div className="flex items-start justify-between mb-2">
        <div className="flex items-center gap-2">
          <div className="w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center">
            {getPlatformIcon(build.platform)}
          </div>
          <div>
            <p className="text-sm font-medium text-foreground truncate max-w-[160px]">
              {build.app_name}
            </p>
            <p className="text-xs text-muted-foreground uppercase">
              {build.platform}
            </p>
          </div>
        </div>
        <div className="flex items-center gap-1">
          {getStatusIcon(build.status)}
          {(build.status === 'completed' || build.status === 'failed') && (
            <Button
              variant="ghost"
              size="icon"
              className="h-5 w-5"
              onClick={onDismiss}
            >
              <X className="w-3 h-3" />
            </Button>
          )}
        </div>
      </div>

      <div className="space-y-1.5">
        <div className="flex items-center justify-between text-xs">
          <span className="text-muted-foreground truncate max-w-[180px]">
            {build.message}
          </span>
          <span className="text-foreground font-medium">{build.progress}%</span>
        </div>
        <Progress value={build.progress} className="h-1.5" />
      </div>

      {build.status === 'completed' && build.download_url && (
        <motion.div
          initial={{ opacity: 0, height: 0 }}
          animate={{ opacity: 1, height: 'auto' }}
          className="mt-2"
        >
          <Button
            variant="accent"
            size="sm"
            className="w-full h-7 text-xs"
            asChild
          >
            <a href={build.download_url} download>
              <Download className="w-3 h-3 mr-1" />
              Download
            </a>
          </Button>
        </motion.div>
      )}
    </motion.div>
  );
};

export default BuildProgressPanel;
