'use client';

import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Download, File, Image as ImageIcon, Film, Music, FileText, Code, Loader2 } from 'lucide-react';
import api from '@/lib/api';

interface FilePreviewProps {
  file: {
    name: string;
    path: string;
    size: number;
    mime_type: string;
  } | null;
  onClose: () => void;
}

export default function FilePreview({ file, onClose }: FilePreviewProps) {
  const [content, setContent] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    function handleKeyDown(e: KeyboardEvent) {
      if (e.key === 'Escape') onClose();
    }
    if (file) {
      window.addEventListener('keydown', handleKeyDown);
    }
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [file, onClose]);

  useEffect(() => {
    if (!file) return;

    const type = getPreviewType(file);
    if (type === 'text' || type === 'code') {
      if (file.size > 2 * 1024 * 1024) { // 2MB limit for text preview
        setError('File is too large to preview. Please download it.');
        return;
      }

      setLoading(true);
      setError(null);
      fetch(api.getDownloadUrl(file.path))
        .then((res) => {
          if (!res.ok) throw new Error('Failed to load file content');
          return res.text();
        })
        .then((text) => setContent(text))
        .catch((err) => setError(err.message))
        .finally(() => setLoading(false));
    }
  }, [file]);

  if (!file) return null;

  const previewType = getPreviewType(file);
  const downloadUrl = api.getDownloadUrl(file.path);

  return (
    <AnimatePresence>
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        className="fixed inset-0 z-[100] flex items-center justify-center p-4 sm:p-8"
        style={{ backgroundColor: 'rgba(0, 0, 0, 0.8)', backdropFilter: 'blur(8px)' }}
        onClick={onClose}
      >
        <motion.div
          initial={{ scale: 0.95, opacity: 0, y: 20 }}
          animate={{ scale: 1, opacity: 1, y: 0 }}
          exit={{ scale: 0.95, opacity: 0, y: 20 }}
          onClick={(e) => e.stopPropagation()}
          className="relative flex flex-col w-full max-w-5xl h-full max-h-[90vh] rounded-2xl overflow-hidden shadow-2xl"
          style={{ backgroundColor: 'var(--color-bg-elevated)', border: '1px solid var(--color-border)' }}
        >
          {/* Header */}
          <div className="flex items-center justify-between px-4 py-3 border-b shrink-0" style={{ borderColor: 'var(--color-border-subtle)', backgroundColor: 'var(--color-bg-secondary)' }}>
            <div className="flex items-center gap-3 min-w-0">
              {getIcon(previewType)}
              <span className="font-medium truncate" style={{ color: 'var(--color-text-primary)' }} title={file.name}>
                {file.name}
              </span>
              <span className="text-xs px-2 py-1 rounded-md" style={{ backgroundColor: 'var(--color-bg-tertiary)', color: 'var(--color-text-tertiary)' }}>
                {formatSize(file.size)}
              </span>
            </div>
            <div className="flex items-center gap-2 shrink-0">
              <a
                href={downloadUrl}
                download={file.name}
                target="_blank"
                rel="noreferrer"
                className="p-2 rounded-lg transition-colors hover:bg-white/10"
                style={{ color: 'var(--color-text-secondary)' }}
                title="Download"
              >
                <Download className="w-5 h-5" />
              </a>
              <button
                onClick={onClose}
                className="p-2 rounded-lg transition-colors hover:bg-white/10"
                style={{ color: 'var(--color-text-secondary)' }}
                title="Close (Esc)"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
          </div>

          {/* Content Area */}
          <div className="flex-1 overflow-auto flex items-center justify-center p-4 relative" style={{ backgroundColor: 'var(--color-bg-primary)' }}>
            {previewType === 'image' && (
              <img
                src={downloadUrl}
                alt={file.name}
                className="max-w-full max-h-full object-contain rounded-lg"
              />
            )}

            {previewType === 'video' && (
              <video
                src={downloadUrl}
                controls
                autoPlay
                className="max-w-full max-h-full rounded-lg outline-none"
              />
            )}

            {previewType === 'audio' && (
              <div className="w-full max-w-md p-6 rounded-xl text-center" style={{ backgroundColor: 'var(--color-bg-elevated)', border: '1px solid var(--color-border)' }}>
                <Music className="w-16 h-16 mx-auto mb-6" style={{ color: 'var(--color-accent)' }} />
                <h3 className="text-lg font-medium mb-4 truncate" style={{ color: 'var(--color-text-primary)' }}>{file.name}</h3>
                <audio src={downloadUrl} controls autoPlay className="w-full outline-none" />
              </div>
            )}

            {previewType === 'pdf' && (
              <iframe
                src={`${downloadUrl}#navpanes=0&view=FitH`}
                title={file.name}
                className="w-full h-full rounded-lg border-0 bg-white"
              />
            )}

            {(previewType === 'text' || previewType === 'code') && (
              <div className="absolute inset-0 p-4">
                {loading ? (
                  <div className="flex items-center justify-center h-full">
                    <Loader2 className="w-8 h-8 animate-spin" style={{ color: 'var(--color-accent)' }} />
                  </div>
                ) : error ? (
                  <div className="flex flex-col items-center justify-center h-full gap-2">
                    <p style={{ color: 'var(--color-danger)' }}>{error}</p>
                    <a
                      href={downloadUrl}
                      target="_blank"
                      rel="noreferrer"
                      className="px-4 py-2 mt-2 rounded-lg text-sm font-medium transition-opacity hover:opacity-90"
                      style={{ backgroundColor: 'var(--color-accent)', color: 'white' }}
                    >
                      Download File
                    </a>
                  </div>
                ) : (
                  <pre
                    className="w-full h-full p-4 overflow-auto text-sm rounded-lg"
                    style={{
                      fontFamily: 'var(--font-mono)',
                      backgroundColor: 'var(--color-bg-secondary)',
                      color: 'var(--color-text-primary)',
                      border: '1px solid var(--color-border-subtle)',
                    }}
                  >
                    {content}
                  </pre>
                )}
              </div>
            )}

            {previewType === 'unsupported' && (
              <div className="flex flex-col items-center justify-center gap-4 text-center">
                <File className="w-16 h-16" style={{ color: 'var(--color-text-tertiary)' }} />
                <div>
                  <h3 className="text-lg font-medium mb-1" style={{ color: 'var(--color-text-primary)' }}>No Preview Available</h3>
                  <p className="text-sm" style={{ color: 'var(--color-text-secondary)' }}>This file type cannot be previewed in the browser.</p>
                </div>
                <a
                  href={downloadUrl}
                  target="_blank"
                  rel="noreferrer"
                  className="flex items-center gap-2 px-6 py-2.5 mt-2 rounded-xl text-sm font-medium transition-opacity hover:opacity-90"
                  style={{ backgroundColor: 'var(--color-accent)', color: 'white', boxShadow: 'var(--shadow-glow)' }}
                >
                  <Download className="w-4 h-4" />
                  Download File
                </a>
              </div>
            )}
          </div>
        </motion.div>
      </motion.div>
    </AnimatePresence>
  );
}

// --- Helpers ---

type PreviewType = 'image' | 'video' | 'audio' | 'text' | 'code' | 'pdf' | 'unsupported';

function getPreviewType(file: { name: string; mime_type: string }): PreviewType {
  const ext = file.name.split('.').pop()?.toLowerCase() || '';

  if (ext === 'pdf' || file.mime_type === 'application/pdf') return 'pdf';
  if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp'].includes(ext)) return 'image';
  if (['mp4', 'webm', 'ogg'].includes(ext)) return 'video'; // Only browser-supported videos
  if (['mp3', 'wav', 'flac', 'm4a', 'aac'].includes(ext)) return 'audio';
  if (['txt', 'md', 'csv', 'json', 'log'].includes(ext)) return 'text';
  if (['js', 'ts', 'jsx', 'tsx', 'html', 'css', 'go', 'py', 'rs', 'c', 'cpp', 'java', 'sh', 'yml', 'yaml', 'xml'].includes(ext)) return 'code';

  if (file.mime_type.startsWith('image/')) return 'image';
  if (file.mime_type.startsWith('video/')) return 'video';
  if (file.mime_type.startsWith('audio/')) return 'audio';
  if (file.mime_type.startsWith('text/')) return 'text';

  return 'unsupported';
}

function getIcon(type: PreviewType) {
  const props = { className: "w-5 h-5", style: { color: 'var(--color-text-secondary)' } };
  switch (type) {
    case 'image': return <ImageIcon {...props} />;
    case 'video': return <Film {...props} />;
    case 'audio': return <Music {...props} />;
    case 'text': return <FileText {...props} />;
    case 'code': return <Code {...props} />;
    default: return <File {...props} />;
  }
}

function formatSize(bytes: number): string {
  if (bytes === 0) return '0 B';
  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${units[i]}`;
}
