'use client';

import { useEffect, useState } from 'react';
import { Check, Copy } from 'lucide-react';
import { useChatStore } from '@/lib/store/chat-store';

interface CopySuccessToastProps {
  message?: string;
  duration?: number;
  show: boolean;
  onClose: () => void;
}

/**
 * CopySuccessToast Component
 *
 * Success feedback toast for clipboard copy operations.
 * - Fixed position at bottom-center for mobile visibility
 * - Auto-dismiss after configurable duration (default 3 seconds)
 * - Confetti animation effect on mount
 * - Screen reader announcement for accessibility
 * - Haptic feedback on mobile devices
 *
 * @param message - Success message to display (default: "Copied to clipboard!")
 * @param duration - Auto-dismiss duration in ms (default: 3000)
 * @param show - Whether to show the toast
 * @param onClose - Callback when toast should close
 */
export function CopySuccessToast({
  message = 'Copied to clipboard!',
  duration = 3000,
  show,
  onClose,
}: CopySuccessToastProps) {
  const [isVisible, setIsVisible] = useState(show);
  const [confettiPieces, setConfettiPieces] = useState<Array<{
    id: number;
    x: number;
    y: number;
    color: string;
    rotation: number;
    velocityX: number;
    velocityY: number;
  }>>([]);

  // Trigger haptic feedback on mobile when toast appears
  useEffect(() => {
    if (show && 'vibrate' in navigator) {
      navigator.vibrate(50); // Short haptic burst
    }
  }, [show]);

  // Generate confetti pieces on mount
  useEffect(() => {
    if (show) {
      setIsVisible(true);

      const colors = ['#64748B', '#94A3B8', '#CBD5E1', '#E2E8F0']; // Slate colors for "Morning Mist" theme
      const pieces = Array.from({ length: 20 }, (_, i) => ({
        id: i,
        x: 50, // Center horizontally (percent)
        y: 50, // Center vertically (percent)
        color: colors[Math.floor(Math.random() * colors.length)],
        rotation: Math.random() * 360,
        velocityX: (Math.random() - 0.5) * 20,
        velocityY: (Math.random() - 1) * 20 - 5, // Upward bias
      }));
      setConfettiPieces(pieces);
    } else {
      setIsVisible(false);
    }
  }, [show]);

  // Auto-dismiss timer
  useEffect(() => {
    if (!show) return;

    const timer = setTimeout(() => {
      setIsVisible(false);
      // Allow exit animation to complete before calling onClose
      setTimeout(() => onClose(), 300);
    }, duration);

    return () => clearTimeout(timer);
  }, [show, duration, onClose]);

  // Animate confetti
  useEffect(() => {
    if (!isVisible || confettiPieces.length === 0) return;

    const animationFrame = requestAnimationFrame(() => {
      setConfettiPieces(prev =>
        prev.map(piece => ({
          ...piece,
          x: piece.x + piece.velocityX * 0.1,
          y: piece.y + piece.velocityY * 0.1,
          velocityY: piece.velocityY + 0.5, // Gravity
          rotation: piece.rotation + 5,
        }))
      );
    });

    return () => cancelAnimationFrame(animationFrame);
  }, [isVisible, confettiPieces]);

  if (!show && !isVisible) return null;

  return (
    <>
      {/* Live region for screen readers */}
      <div
        role="status"
        aria-live="polite"
        aria-atomic="true"
        className="sr-only"
      >
        {show ? message : ''}
      </div>

      {/* Confetti overlay */}
      {show && confettiPieces.length > 0 && (
        <div className="fixed inset-0 pointer-events-none z-50" aria-hidden="true">
          {confettiPieces.map(piece => (
            <div
              key={piece.id}
              className="absolute w-2 h-2"
              style={{
                left: `${piece.x}%`,
                top: `${piece.y}%`,
                backgroundColor: piece.color,
                transform: `rotate(${piece.rotation}deg)`,
                opacity: 0.8,
              }}
            />
          ))}
        </div>
      )}

      {/* Toast */}
      <div
        className={`
          fixed bottom-4 left-1/2 -translate-x-1/2 z-50
          px-4 py-3 bg-slate-800 text-white rounded-lg shadow-lg
          flex items-center gap-3
          transition-all duration-300 ease-out
          ${show && isVisible
            ? 'opacity-100 translate-y-0 scale-100'
            : 'opacity-0 translate-y-4 scale-95'
          }
        `}
        role="alert"
        aria-describedby="toast-message"
      >
        <Check className="w-5 h-5 text-green-400" aria-hidden="true" />
        <span id="toast-message" className="font-medium text-sm">
          {message}
        </span>
        <button
          onClick={() => {
            setIsVisible(false);
            setTimeout(() => onClose(), 300);
          }}
          className="ml-2 p-1 hover:bg-slate-700 rounded transition-colors"
          aria-label="Dismiss notification"
        >
          <Copy className="w-4 h-4" aria-hidden="true" />
        </button>
      </div>
    </>
  );
}

/**
 * Hook to manage toast state
 * Provides a simple interface for showing/hiding the success toast
 */
export function useCopySuccessToast() {
  const [show, setShow] = useState(false);
  const [message, setMessage] = useState('Copied to clipboard!');

  const showToast = (customMessage?: string) => {
    setMessage(customMessage || 'Copied to clipboard!');
    setShow(true);
  };

  const hideToast = () => {
    setShow(false);
  };

  return {
    show,
    message,
    showToast,
    hideToast,
  };
}
