import React from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  Globe, 
  FileText, 
  Image as ImageIcon, 
  File, 
  Eye, 
  MoreVertical, 
  Edit3, 
  Share2, 
  Trash2, 
  Lock, 
  ExternalLink, 
  Download, 
  Clock, 
  AlertCircle,
  BookOpen
} from 'lucide-react';
import type { Asset } from '../../../types/assets';
import type { User } from '../../../types/auth';
import { axiosInstance } from '../../../services/axios';

interface AssetCardProps {
  asset: Asset;
  user: User | null;
  activeMenuId: string | null;
  setActiveMenuId: (id: string | null) => void;
  onViewDetails: (asset: Asset) => void;
  onEdit: (asset: Asset) => void;
  onShare: (asset: Asset) => void;
  onDelete: (assetId: string) => void;
  onOpenViewer: (asset: Asset) => void;
  onDownload: (asset: Asset) => void;
  onRequestDownload: (asset: Asset) => void;
  isSelected?: boolean;
  onToggleSelect?: (assetId: string) => void;
  isExpanded?: boolean;
  onToggleExpand?: () => void;
}

export const AssetCard: React.FC<AssetCardProps> = ({
  asset,
  user,
  activeMenuId,
  setActiveMenuId,
  onViewDetails,
  onEdit,
  onShare,
  onDelete,
  onOpenViewer,
  onDownload,
  onRequestDownload,
  isSelected = false,
  onToggleSelect,
  isExpanded = false,
  onToggleExpand
}) => {
  const isMenuOpen = activeMenuId === asset.id;
  const canDirectDownload = user?.role === 'ADMIN' || asset.isDownloadable || asset.downloadRequests?.[0]?.status === 'APPROVED';
  const requestStatus = asset.downloadRequests?.[0]?.status;

  const formatBytes = (bytes: number, decimals = 2) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
  };

  const getAssetIcon = (type: string) => {
    if (type === 'case_study') return BookOpen;
    if (type === 'url') return Globe;
    if (type.includes('pdf')) return FileText;
    if (type.includes('image') || type.includes('png') || type.includes('jpg')) return ImageIcon;
    return File;
  };

  const isRenderable = (type: string, url: string) => {
    const isOffice = type.includes('word') || type.includes('presentation') || type.includes('sheet') || 
                     url.toLowerCase().endsWith('.docx') || url.toLowerCase().endsWith('.doc') || 
                     url.toLowerCase().endsWith('.pptx') || url.toLowerCase().endsWith('.ppt') || 
                     url.toLowerCase().endsWith('.xlsx') || url.toLowerCase().endsWith('.xls');
    return type === 'url' || type.includes('pdf') || type.includes('image') || type.includes('png') || type.includes('jpg') || isOffice;
  };

  const getFullAssetUrl = (url: string) => {
    let resolvedUrl = url;
    if (!url.startsWith('http')) {
      const backendBase = axiosInstance.defaults.baseURL || '/api/v1';
      const relativeHost = backendBase.replace('/api/v1', '');
      resolvedUrl = relativeHost.startsWith('/') || relativeHost === ''
        ? `${window.location.origin}${relativeHost}${url}`
        : `${relativeHost}${url}`;
    }

    const currentOrigin = window.location.origin;
    const isCurrentOriginLocal = currentOrigin.includes('localhost') || currentOrigin.includes('127.0.0.1');
    if (!isCurrentOriginLocal && (resolvedUrl.includes('localhost') || resolvedUrl.includes('127.0.0.1'))) {
      resolvedUrl = resolvedUrl.replace(/https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?/, currentOrigin);
    }

    return resolvedUrl;
  };

  const Icon = getAssetIcon(asset.type);

  const isImage = asset.type.includes('image') || asset.type.includes('png') || asset.type.includes('jpg') || asset.url.match(/\.(png|jpe?g|gif|svg|webp)$/i);
  const isPdf = asset.type.includes('pdf') || asset.url.toLowerCase().endsWith('.pdf');
  const isWord = asset.type.includes('word') || asset.url.toLowerCase().endsWith('.docx') || asset.url.toLowerCase().endsWith('.doc');
  const isPresentation = asset.type.includes('presentation') || asset.url.toLowerCase().endsWith('.pptx') || asset.url.toLowerCase().endsWith('.ppt');
  const isSpreadsheet = asset.type.includes('sheet') || asset.url.toLowerCase().endsWith('.xlsx') || asset.url.toLowerCase().endsWith('.xls') || asset.url.toLowerCase().endsWith('.csv');
  
  const hasBanner = isImage || (asset.type === 'case_study' && !!asset.thumbnailUrl);
  const bannerSrc = (asset.type === 'case_study' && asset.thumbnailUrl) ? asset.thumbnailUrl : asset.url;

  return (
    <motion.div 
      layout
      transition={{ type: "spring", stiffness: 320, damping: 28 }}
      onClick={(e) => {
        const target = e.target as HTMLElement;
        if (target.closest('button') || target.closest('a') || target.closest('input') || target.closest('.toggle-expand-btn')) {
          return;
        }
        onViewDetails(asset);
      }}
      className={`group bg-ink-0 border rounded-xl p-4 transition-all duration-300 flex flex-col justify-between cursor-pointer min-h-[410px] ${
        isExpanded 
          ? 'absolute z-20 top-0 left-0 right-0 h-auto shadow-2xl border-ink-300 bg-ink-0'
          : 'relative w-full h-full border-ink-200 hover:border-ink-300 hover:shadow-md hover:-translate-y-0.5'
      } ${isSelected ? 'border-ink-900 ring-1 ring-ink-900 bg-ink-50/30' : ''}`}
    >
      <div className="flex-grow flex flex-col">
        {/* Visual Thumbnail Area */}
        <div className="w-full h-36 bg-ink-50 border border-ink-200 rounded-lg mb-3 flex items-center justify-center overflow-hidden relative select-none group-hover:border-ink-300 transition-colors bg-gradient-to-br from-ink-50 to-ink-100/50">
          {/* Absolute overlays for controls */}
          <div className="absolute top-2 left-2 z-10 flex items-center gap-1.5">
            {user?.role === 'ADMIN' && onToggleSelect && (
              <input
                type="checkbox"
                checked={isSelected}
                onChange={() => onToggleSelect(asset.id)}
                className="w-3.5 h-3.5 rounded border-ink-300 bg-ink-0 text-ink-900 focus:ring-ink-900/10 cursor-pointer shadow-sm"
              />
            )}
          </div>

          <div className="absolute top-2 right-2 z-10 flex items-center gap-1">
            {isRenderable(asset.type, asset.url) && (
              <button 
                onClick={() => onOpenViewer(asset)}
                className="p-1 rounded-md bg-ink-0/90 backdrop-blur text-ink-600 hover:text-ink-900 border border-ink-200 shadow-sm transition-all hover:scale-105"
                title="Preview Online"
              >
                <Eye className="w-3.5 h-3.5" />
              </button>
            )}

            <div className="relative">
              <button 
                onClick={() => setActiveMenuId(isMenuOpen ? null : asset.id)}
                className="p-1 rounded-md bg-ink-0/90 backdrop-blur text-ink-600 hover:text-ink-900 border border-ink-200 shadow-sm transition-all hover:scale-105"
              >
                <MoreVertical className="w-3.5 h-3.5" />
              </button>
              
              {isMenuOpen && (
                <>
                  <div className="fixed inset-0 z-10" onClick={() => setActiveMenuId(null)} />
                  <div className="absolute right-0 mt-1.5 w-44 bg-ink-0 border border-ink-200 rounded-lg shadow-lg z-20 overflow-hidden py-1">
                    <button 
                      onClick={() => {
                        onViewDetails(asset);
                        setActiveMenuId(null);
                      }}
                      className="w-full text-left px-4 py-2 text-xs font-semibold text-ink-700 hover:bg-ink-50 hover:text-ink-900 flex items-center gap-2"
                    >
                      <File className="w-3.5 h-3.5" />
                      View Details
                    </button>
                    {user?.role === 'ADMIN' && (
                      <>
                        <button 
                          onClick={() => {
                            onEdit(asset);
                            setActiveMenuId(null);
                          }}
                          className="w-full text-left px-4 py-2 text-xs font-semibold text-ink-700 hover:bg-ink-50 hover:text-ink-900 flex items-center gap-2"
                        >
                          <Edit3 className="w-3.5 h-3.5" />
                          Edit Asset
                        </button>
                        <button 
                          onClick={() => {
                            onShare(asset);
                            setActiveMenuId(null);
                          }}
                          className="w-full text-left px-4 py-2 text-xs font-semibold text-ink-700 hover:bg-ink-50 hover:text-ink-900 flex items-center gap-2"
                        >
                          <Share2 className="w-3.5 h-3.5" />
                          Share Settings
                        </button>
                        <button 
                          onClick={() => {
                            onDelete(asset.id);
                            setActiveMenuId(null);
                          }}
                          className="w-full text-left px-4 py-2 text-xs font-semibold text-red-650 hover:bg-red-500/10 flex items-center gap-2"
                        >
                          <Trash2 className="w-3.5 h-3.5" />
                          Delete Asset
                        </button>
                      </>
                    )}
                  </div>
                </>
              )}
            </div>
          </div>

          {/* Thumbnail Preview Area Content */}
          {hasBanner ? (
            <img 
              src={getFullAssetUrl(bannerSrc)} 
              alt={asset.title} 
              className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"
              onError={(e) => {
                e.currentTarget.style.display = 'none';
                const placeholder = document.getElementById(`fallback-${asset.id}`);
                if (placeholder) placeholder.style.display = 'flex';
              }}
            />
          ) : null}

          {/* Fallbacks / simulated thumbnails */}
          <div 
            id={`fallback-${asset.id}`} 
            className="w-full h-full flex items-center justify-center"
            style={{ display: hasBanner ? 'none' : 'flex' }}
          >
            {isPdf ? (
              <div className="flex flex-col items-center justify-center w-full h-full p-4 relative">
                <div className="w-14 h-18 bg-ink-0 border border-ink-200 shadow-sm rounded flex flex-col justify-between p-1.5 relative overflow-hidden">
                  <div className="absolute top-0 right-0 left-0 bg-red-600 text-ink-0 py-0.5 text-[8px] font-extrabold uppercase text-center tracking-wider">
                    PDF
                  </div>
                  <div className="space-y-1 mt-4">
                    <div className="h-1 bg-ink-200 rounded w-5/6" />
                    <div className="h-1 bg-ink-200 rounded w-full" />
                    <div className="h-1 bg-ink-200 rounded w-4/5" />
                  </div>
                  <div className="flex items-center justify-between text-[7px] text-ink-400 font-bold border-t border-ink-100 pt-0.5 mt-1">
                    <span>PDF</span>
                    <FileText className="w-2.5 h-2.5 text-red-500" />
                  </div>
                </div>
              </div>
            ) : isPresentation ? (
              <div className="flex flex-col items-center justify-center w-full h-full p-4">
                <div className="w-18 h-13 bg-amber-500 border border-amber-600 shadow-sm rounded-lg flex flex-col justify-between p-1.5 relative overflow-hidden">
                  <div className="h-1.5 bg-ink-0/90 rounded w-3/4 mb-1" />
                  <div className="space-y-1">
                    <div className="h-1 bg-ink-0/60 rounded w-full" />
                    <div className="h-1 bg-ink-0/60 rounded w-5/6" />
                  </div>
                  <div className="flex items-center justify-between text-[7px] text-ink-0/80 font-bold pt-0.5">
                    <span>SLIDE</span>
                    <span className="font-extrabold">PPTX</span>
                  </div>
                </div>
              </div>
            ) : isWord ? (
              <div className="flex flex-col items-center justify-center w-full h-full p-4">
                <div className="w-14 h-18 bg-ink-0 border border-ink-200 shadow-sm rounded flex flex-col justify-between p-1.5 relative overflow-hidden">
                  <div className="absolute top-0 right-0 left-0 bg-blue-600 text-ink-0 py-0.5 text-[8px] font-extrabold uppercase text-center tracking-wider">
                    DOC
                  </div>
                  <div className="space-y-1 mt-4">
                    <div className="h-1 bg-ink-200 rounded w-full" />
                    <div className="h-1 bg-ink-200 rounded w-5/6" />
                    <div className="h-1 bg-ink-200 rounded w-full" />
                  </div>
                  <div className="flex items-center justify-between text-[7px] text-ink-400 font-bold border-t border-ink-100 pt-0.5 mt-1">
                    <span>WORD</span>
                    <FileText className="w-2.5 h-2.5 text-blue-500" />
                  </div>
                </div>
              </div>
            ) : isSpreadsheet ? (
              <div className="flex flex-col items-center justify-center w-full h-full p-4">
                <div className="w-16 h-13 bg-emerald-600 border border-emerald-700 shadow-sm rounded-lg flex flex-col justify-between p-1.5 relative overflow-hidden">
                  <div className="grid grid-cols-3 gap-0.5 mt-0.5">
                    <div className="h-1.5 bg-ink-0/90 rounded-sm" />
                    <div className="h-1.5 bg-ink-0/70 rounded-sm" />
                    <div className="h-1.5 bg-ink-0/70 rounded-sm" />
                    <div className="h-1.5 bg-ink-0/60 rounded-sm" />
                    <div className="h-1.5 bg-ink-0/80 rounded-sm" />
                    <div className="h-1.5 bg-ink-0/60 rounded-sm" />
                  </div>
                  <div className="flex items-center justify-between text-[7px] text-emerald-100 font-bold pt-0.5">
                    <span>SHEET</span>
                    <span className="font-extrabold">XLSX</span>
                  </div>
                </div>
              </div>
            ) : (
              <div className="flex flex-col items-center justify-center w-full h-full p-4">
                <div className="w-12 h-12 rounded-xl bg-ink-100 border border-ink-200 flex items-center justify-center shadow-inner relative group-hover:scale-105 transition-transform">
                  <Icon className="w-6 h-6 text-ink-650" />
                  <div className="absolute -bottom-1 -right-1 bg-ink-800 border border-ink-700 rounded px-1 py-0.5 text-[7px] font-bold text-ink-0 uppercase">
                    {asset.type === 'case_study' ? 'CASE STUDY' : asset.type === 'url' ? 'LINK' : 'FILE'}
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>

        <div className="space-y-1 mb-4 flex-grow flex flex-col">
          <div className="flex items-center gap-1.5 mb-2">
            <div className="inline-block px-1.5 py-0.5 rounded text-[10px] font-bold text-ink-500 uppercase tracking-wider bg-ink-50 border border-ink-200">
              {asset.categoryId || 'General'}
            </div>
            {!asset.isDownloadable && (
              <div className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-bold text-ink-600 bg-ink-100 border border-ink-200">
                <Lock className="w-2.5 h-2.5" />
                <span>Strict View Only</span>
              </div>
            )}
          </div>

          <h3 className="font-bold text-ink-900 text-sm asset-card-title leading-snug line-clamp-2 group-hover:text-ink-950 transition-colors" title={asset.title}>
            {asset.title}
          </h3>
          {asset.description && (
            <p className="text-xs text-ink-500 line-clamp-2 mt-1.5 leading-relaxed" title={asset.description}>
              {asset.description}
            </p>
          )}
          <div className="flex items-center justify-between mt-auto pt-2.5">
            <p className="text-[11px] font-medium text-ink-400">
              {asset.type === 'case_study' ? 'Case Study' : asset.type === 'url' ? 'External Link' : formatBytes(asset.size)} • {new Date(asset.createdAt).toLocaleDateString()}
            </p>
            {asset.type === 'case_study' && (asset.problemStatement || asset.solution) && (
              <button
                type="button"
                onClick={(e) => {
                  e.stopPropagation();
                  onToggleExpand?.();
                }}
                className="toggle-expand-btn text-[10px] font-bold text-ink-650 hover:text-ink-900 bg-ink-50 hover:bg-ink-100 border border-ink-200 px-2 py-0.5 rounded transition-all cursor-pointer"
              >
                {isExpanded ? 'Hide Summary' : 'Show Summary'}
              </button>
            )}
          </div>

          <AnimatePresence initial={false}>
            {asset.type === 'case_study' && isExpanded && (asset.problemStatement || asset.solution) && (
              <motion.div
                initial={{ height: 0, opacity: 0 }}
                animate={{ height: 'auto', opacity: 1 }}
                exit={{ height: 0, opacity: 0 }}
                transition={{ duration: 0.25, ease: 'easeInOut' }}
                className="mt-3.5 space-y-2.5 border-t border-ink-100 pt-3 text-[11px] overflow-hidden"
              >
                {asset.problemStatement && (
                  <div>
                    <span className="font-bold text-red-650 uppercase tracking-wider text-[9px] block mb-0.5">Problem / Challenge</span>
                    <p className="text-ink-700 leading-relaxed bg-red-500/[0.01] border border-red-500/5 p-2 rounded" title={asset.problemStatement}>
                      {asset.problemStatement}
                    </p>
                  </div>
                )}
                {asset.solution && (
                  <div>
                    <span className="font-bold text-emerald-650 uppercase tracking-wider text-[9px] block mb-0.5">Our Approach</span>
                    <p className="text-ink-700 leading-relaxed bg-emerald-500/[0.01] border border-emerald-500/5 p-2 rounded" title={asset.solution}>
                      {asset.solution}
                    </p>
                  </div>
                )}
                <div className="pt-2 flex justify-end">
                  <a
                    href={asset.url}
                    target="_blank"
                    rel="noreferrer"
                    className="inline-flex items-center gap-1.5 text-[10px] font-bold text-ink-600 hover:text-ink-900 transition-colors bg-ink-50 hover:bg-ink-100 border border-ink-200 px-2.5 py-1 rounded-md"
                  >
                    <span>Read Full Case Study</span>
                    <ExternalLink className="w-3.5 h-3.5" />
                  </a>
                </div>
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      </div>

      <div className="pt-3 border-t border-ink-100 flex items-center justify-between mt-auto">
        <div className="flex flex-col">
          <span className="text-[10px] font-semibold uppercase tracking-wider text-ink-400">
            {asset.type === 'url' || asset.type === 'case_study' ? 'Type' : 'Downloads'}
          </span>
          <span className="text-xs font-extrabold text-ink-900 mt-0.5">
            {asset.type === 'case_study' ? 'Case Study' : asset.type === 'url' ? 'URL Link' : asset.downloadsCount}
          </span>
        </div>

        {asset.type === 'url' || asset.type === 'case_study' ? (
          <a 
            href={asset.url} 
            target="_blank" 
            rel="noreferrer"
            className="w-7 h-7 rounded-md bg-ink-900 border border-ink-900 flex items-center justify-center text-ink-0 hover:bg-ink-800 transition-all shadow-sm"
            title={asset.type === 'case_study' ? 'Open Case Study' : 'Open External URL'}
          >
            <ExternalLink className="w-3.5 h-3.5" />
          </a>
        ) : canDirectDownload ? (
          <button 
            onClick={() => onDownload(asset)}
            className="w-7 h-7 rounded-md bg-ink-50 border border-ink-200 flex items-center justify-center text-ink-600 hover:bg-ink-100 hover:border-ink-300 hover:text-ink-900 transition-all shadow-sm"
            title="Download Asset"
          >
            <Download className="w-3.5 h-3.5" />
          </button>
        ) : requestStatus === 'PENDING' ? (
          <div className="inline-flex items-center gap-1 text-[10px] font-bold text-ink-500 bg-ink-50 border border-ink-200 px-2 py-1 rounded-md">
            <Clock className="w-3 h-3 text-ink-500 animate-pulse" />
            <span>Pending Access</span>
          </div>
        ) : requestStatus === 'REJECTED' ? (
          <button 
            onClick={() => onRequestDownload(asset)}
            className="inline-flex items-center gap-1 text-[10px] font-bold text-red-650 bg-red-500/10 border border-red-500/20 px-2 py-1 rounded-md hover:bg-red-500/25 transition-all"
          >
            <AlertCircle className="w-3 h-3" />
            <span>Rejected (Retry)</span>
          </button>
        ) : (
          <button 
            onClick={() => onRequestDownload(asset)}
            className="inline-flex items-center gap-1 text-[10px] font-bold text-ink-900 bg-ink-100 border border-ink-300 hover:bg-ink-200 px-2 py-1 rounded-md transition-all cursor-pointer"
          >
            <Lock className="w-3 h-3" />
            <span>Request Download</span>
          </button>
        )}
      </div>
    </motion.div>
  );
};

