import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Camera as CameraIcon, Video, VideoOff, ChevronRight, Eye, Settings, AlertCircle } from 'lucide-react';
import { cn } from '../../lib/utils';
import { VideoPlayer } from './VideoPlayer';
import { useNavigate } from 'react-router-dom';

interface Camera {
    id: string;
    name: string;
    slug: string;
    streamKey: string;
    location?: string;
    status: 'ONLINE' | 'OFFLINE' | 'IDLE' | 'STREAMING' | 'ERROR';
    manufacturer?: string;
    room?: {
        id: string;
        name: string;
        code: string;
        type: string;
    };
}

interface CameraWidgetProps {
    cameras?: Camera[];
    maxVisible?: number;
    onCameraClick?: (camera: Camera) => void;
}

/**
 * Dashboard widget showing camera grid with live previews
 */
export function CameraWidget({ cameras = [], maxVisible = 4, onCameraClick }: CameraWidgetProps) {
    const navigate = useNavigate();
    const [selectedCamera, setSelectedCamera] = useState<Camera | null>(null);
    const [showModal, setShowModal] = useState(false);

    const visibleCameras = cameras.slice(0, maxVisible);
    const remainingCount = cameras.length - maxVisible;

    const handleCameraClick = (camera: Camera) => {
        if (onCameraClick) {
            onCameraClick(camera);
        } else {
            setSelectedCamera(camera);
            setShowModal(true);
        }
    };

    const getStatusColor = (status: Camera['status']) => {
        switch (status) {
            case 'ONLINE':
            case 'STREAMING':
                return 'bg-emerald-500';
            case 'IDLE':
                return 'bg-amber-500';
            case 'OFFLINE':
                return 'bg-gray-400';
            case 'ERROR':
                return 'bg-red-500';
            default:
                return 'bg-gray-400';
        }
    };

    const getStatusText = (status: Camera['status']) => {
        switch (status) {
            case 'STREAMING':
                return 'Live';
            case 'IDLE':
                return 'Ready';
            default:
                return status.charAt(0) + status.slice(1).toLowerCase();
        }
    };

    return (
        <>
            <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                className={cn(
                    "overflow-hidden rounded-2xl",
                    "bg-white dark:bg-zinc-900/80",
                    "border border-gray-200 dark:border-zinc-700/50",
                    "shadow-sm dark:shadow-xl"
                )}
            >
                {/* Header */}
                <div className="p-5 pb-4 flex items-center justify-between border-b border-gray-100 dark:border-zinc-800">
                    <div className="flex items-center gap-3">
                        <div className="p-2.5 rounded-xl bg-purple-100 dark:bg-purple-500/20 text-purple-600 dark:text-purple-400">
                            <Video size={20} />
                        </div>
                        <div>
                            <h3 className="text-sm font-bold text-gray-900 dark:text-white tracking-wide">
                                Security Cameras
                            </h3>
                            <p className="text-xs text-gray-500 dark:text-zinc-500">
                                {cameras.filter(c => c.status !== 'OFFLINE').length} of {cameras.length} online
                            </p>
                        </div>
                    </div>
                    <button
                        onClick={() => navigate('/cameras')}
                        className="flex items-center gap-1 text-xs text-gray-400 hover:text-emerald-500 dark:text-zinc-500 dark:hover:text-emerald-400 transition-colors"
                    >
                        View All
                        <ChevronRight size={14} />
                    </button>
                </div>

                {/* Camera Grid */}
                {cameras.length === 0 ? (
                    <div className="p-8 text-center">
                        <CameraIcon className="w-12 h-12 text-gray-300 dark:text-zinc-700 mx-auto mb-3" />
                        <p className="text-sm text-gray-500 dark:text-zinc-500">No cameras configured</p>
                        <button
                            onClick={() => navigate('/settings/cameras')}
                            className="mt-3 text-xs text-emerald-600 dark:text-emerald-400 hover:underline"
                        >
                            Add Camera
                        </button>
                    </div>
                ) : (
                    <div className="p-4 grid grid-cols-2 gap-3">
                        {visibleCameras.map((camera) => (
                            <motion.button
                                key={camera.id}
                                whileHover={{ scale: 1.02 }}
                                whileTap={{ scale: 0.98 }}
                                onClick={() => handleCameraClick(camera)}
                                className={cn(
                                    "relative aspect-video rounded-xl overflow-hidden cursor-pointer transition-all",
                                    "bg-gray-100 dark:bg-zinc-800",
                                    "border border-gray-200 dark:border-zinc-700",
                                    "hover:border-emerald-500/50 hover:shadow-lg hover:shadow-emerald-500/10"
                                )}
                            >
                                {/* Placeholder/Thumbnail */}
                                <div className="absolute inset-0 flex items-center justify-center">
                                    {camera.status === 'OFFLINE' || camera.status === 'ERROR' ? (
                                        <VideoOff className="w-8 h-8 text-gray-400 dark:text-zinc-600" />
                                    ) : (
                                        <CameraIcon className="w-8 h-8 text-gray-400 dark:text-zinc-600" />
                                    )}
                                </div>

                                {/* Status Badge */}
                                <div className="absolute top-2 left-2 flex items-center gap-1.5 px-2 py-0.5 bg-black/60 rounded-full">
                                    <div className={cn("w-1.5 h-1.5 rounded-full", getStatusColor(camera.status))} />
                                    <span className="text-[10px] font-medium text-white">
                                        {getStatusText(camera.status)}
                                    </span>
                                </div>

                                {/* Camera Name */}
                                <div className="absolute bottom-0 left-0 right-0 p-2 bg-gradient-to-t from-black/80 to-transparent">
                                    <p className="text-xs font-medium text-white truncate">{camera.name}</p>
                                    {camera.room && (
                                        <p className="text-[10px] text-gray-300 truncate">{camera.room.name}</p>
                                    )}
                                </div>

                                {/* View Overlay */}
                                <div className="absolute inset-0 bg-emerald-500/0 hover:bg-emerald-500/10 transition-colors flex items-center justify-center opacity-0 hover:opacity-100">
                                    <div className="p-2 bg-white/20 rounded-full backdrop-blur-sm">
                                        <Eye size={16} className="text-white" />
                                    </div>
                                </div>
                            </motion.button>
                        ))}
                    </div>
                )}

                {/* More cameras indicator */}
                {remainingCount > 0 && (
                    <div className="px-4 pb-4">
                        <button
                            onClick={() => navigate('/cameras')}
                            className="w-full py-2 text-center text-xs text-gray-500 dark:text-zinc-500 hover:text-emerald-600 dark:hover:text-emerald-400 border border-dashed border-gray-200 dark:border-zinc-700 rounded-lg transition-colors"
                        >
                            +{remainingCount} more camera{remainingCount > 1 ? 's' : ''}
                        </button>
                    </div>
                )}
            </motion.div>

            {/* Video Modal */}
            {showModal && selectedCamera && (
                <div
                    className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-sm"
                    onClick={() => setShowModal(false)}
                >
                    <motion.div
                        initial={{ opacity: 0, scale: 0.9 }}
                        animate={{ opacity: 1, scale: 1 }}
                        className="relative w-full max-w-4xl mx-4"
                        onClick={(e) => e.stopPropagation()}
                    >
                        {/* Header */}
                        <div className="flex items-center justify-between mb-3">
                            <div>
                                <h2 className="text-lg font-bold text-white">{selectedCamera.name}</h2>
                                {selectedCamera.location && (
                                    <p className="text-sm text-gray-400">{selectedCamera.location}</p>
                                )}
                            </div>
                            <button
                                onClick={() => setShowModal(false)}
                                className="p-2 text-gray-400 hover:text-white transition-colors"
                            >
                                <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>

                        {/* Video Player */}
                        <VideoPlayer
                            streamKey={selectedCamera.streamKey}
                            className="aspect-video"
                            showControls
                            autoPlay
                        />

                        {/* Camera Info */}
                        <div className="mt-3 flex items-center justify-between text-sm text-gray-400">
                            <div className="flex items-center gap-4">
                                {selectedCamera.manufacturer && (
                                    <span>{selectedCamera.manufacturer}</span>
                                )}
                                {selectedCamera.room && (
                                    <span>{selectedCamera.room.name}</span>
                                )}
                            </div>
                            <span className="text-xs">Stream: {selectedCamera.streamKey}</span>
                        </div>
                    </motion.div>
                </div>
            )}
        </>
    );
}

export default CameraWidget;
