'use client';

import React, { useCallback, useRef, useState } from 'react';
import { MediaLibraryProvider, useMediaLibrary } from './MediaLibraryContext';
import type { ImageSelection, MediaContext } from '@/types/media';
import {
  isPdfMimeType,
  isImageMimeType,
  ALLOWED_IMAGE_TYPES,
  ALLOWED_PDF_TYPES,
  ACCEPTED_IMAGE_TYPES,
  ACCEPTED_PDF_TYPES,
  IMAGE_TYPES_LABEL,
  PDF_TYPES_LABEL,
  MAX_IMAGE_SIZE,
  MAX_PDF_SIZE,
} from '@/lib/media-utils';
import styles from './MediaLibraryModal.module.css';

interface MediaLibraryModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSelect: (image: ImageSelection) => void;
  context?: MediaContext;
}

export default function MediaLibraryModal({
  isOpen,
  onClose,
  onSelect,
  context = 'general',
}: MediaLibraryModalProps) {
  if (!isOpen) return null;

  return (
    <MediaLibraryProvider>
      <MediaLibraryModalContent onClose={onClose} onSelect={onSelect} context={context} />
    </MediaLibraryProvider>
  );
}

interface MediaLibraryModalContentProps {
  onClose: () => void;
  onSelect: (image: ImageSelection) => void;
  context: MediaContext;
}

function MediaLibraryModalContent({ onClose, onSelect, context }: MediaLibraryModalContentProps) {
  const {
    myImages,
    amsoilImages,
    imageUsage,
    documentUsage,
    isLoading,
    error,
    selectedImage,
    activeTab,
    uploadProgress,
    uploadImage,
    deleteImage,
    selectImage,
    setActiveTab,
    clearError,
  } = useMediaLibrary();

  const [categoryFilter, setCategoryFilter] = useState<string>('all');
  const [isDragging, setIsDragging] = useState(false);
  const [validationError, setValidationError] = useState<string | null>(null);
  const [copiedId, setCopiedId] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Handle file selection
  const handleFileSelect = useCallback(
    async (files: FileList | null) => {
      if (!files || files.length === 0) return;

      const file = files[0];

      // Validate file type based on active tab
      const allowedTypes = activeTab === 'my-documents'
        ? (ALLOWED_PDF_TYPES as readonly string[])
        : (ALLOWED_IMAGE_TYPES as readonly string[]);
      const typeLabel = activeTab === 'my-documents' ? PDF_TYPES_LABEL : IMAGE_TYPES_LABEL;
      if (!allowedTypes.includes(file.type)) {
        setValidationError(`Invalid file type. Only ${typeLabel} files are allowed.`);
        return;
      }

      const maxSize = activeTab === 'my-documents' ? MAX_PDF_SIZE : MAX_IMAGE_SIZE;
      const maxLabel = activeTab === 'my-documents' ? '25MB' : '10MB';
      if (file.size > maxSize) {
        setValidationError(`File too large. Maximum size is ${maxLabel}.`);
        return;
      }
      setValidationError(null);

      await uploadImage(file, context);
    },
    [uploadImage, context, activeTab]
  );

  // Handle drag and drop
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  };

  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    handleFileSelect(e.dataTransfer.files);
  };

  // Handle image selection
  const handleImageClick = (image: ImageSelection) => {
    if (selectedImage?.id === image.id) {
      selectImage(null);
    } else {
      selectImage(image);
    }
  };

  // Handle select button click
  const handleSelect = () => {
    if (selectedImage) {
      onSelect(selectedImage);
      onClose();
    }
  };

  // Handle copy URL
  const handleCopyUrl = async (url: string, id: string) => {
    const fullUrl = `${window.location.origin}${url}`;
    try {
      await navigator.clipboard.writeText(fullUrl);
      setCopiedId(id);
      setTimeout(() => setCopiedId(null), 2000);
    } catch {
      setValidationError('Could not copy to clipboard. Please copy the URL manually.');
    }
  };

  // Handle delete
  const handleDelete = async (e: React.MouseEvent, id: string) => {
    e.stopPropagation();
    if (confirm('Are you sure you want to delete this file?')) {
      await deleteImage(id);
    }
  };

  // Get unique categories from AMSOIL images
  const categories = ['all', ...new Set(amsoilImages.map((img) => img.category))];

  // Filter AMSOIL images by category
  const filteredAmsoilImages =
    categoryFilter === 'all'
      ? amsoilImages
      : amsoilImages.filter((img) => img.category === categoryFilter);

  // Filter assets by type
  const myImageAssets = myImages.filter((a) => isImageMimeType(a.mimeType));
  const myDocumentAssets = myImages.filter((a) => isPdfMimeType(a.mimeType));

  // Usage progress percentage — per active tab
  const activeUsage = activeTab === 'my-documents' ? documentUsage : imageUsage;
  const usagePercentage = activeUsage.limit > 0 ? (activeUsage.current / activeUsage.limit) * 100 : 0;
  const usageStatus = usagePercentage >= 100 ? 'full' : usagePercentage >= 80 ? 'warning' : '';

  return (
    <div className={styles.modalOverlay} onClick={onClose}>
      <div className={styles.modalContent} onClick={(e) => e.stopPropagation()}>
        {/* Header */}
        <div className={styles.modalHeader}>
          <h2 className={styles.modalTitle}>Media Library</h2>
          <button className={styles.closeButton} onClick={onClose} aria-label="Close">
            &times;
          </button>
        </div>

        {/* Tabs */}
        <div className={styles.tabNav}>
          <button
            className={`${styles.tabButton} ${activeTab === 'my-images' ? styles.active : ''}`}
            onClick={() => setActiveTab('my-images')}
          >
            My Images
          </button>
          <button
            className={`${styles.tabButton} ${activeTab === 'my-documents' ? styles.active : ''}`}
            onClick={() => setActiveTab('my-documents')}
          >
            My Documents
          </button>
          <button
            className={`${styles.tabButton} ${activeTab === 'amsoil' ? styles.active : ''}`}
            onClick={() => setActiveTab('amsoil')}
          >
            AMSOIL Images
          </button>
        </div>

        {/* Main Content */}
        <div className={styles.mainContent}>
          {/* Error message */}
          {(error || validationError) && (
            <div className={styles.errorMessage}>
              <span>{error || validationError}</span>
              <button className={styles.errorDismiss} onClick={() => { clearError(); setValidationError(null); }}>
                &times;
              </button>
            </div>
          )}

          {/* Loading state */}
          {isLoading ? (
            <div className={styles.loadingContainer}>Loading media library...</div>
          ) : activeTab === 'my-images' || activeTab === 'my-documents' ? (
            <>
              {/* Usage bar */}
              <div className={styles.usageBar}>
                <span className={styles.usageLabel}>Storage</span>
                <div className={styles.usageProgress}>
                  <div
                    className={`${styles.usageProgressFill} ${usageStatus ? styles[usageStatus] : ''}`}
                    style={{ width: `${Math.min(usagePercentage, 100)}%` }}
                  />
                </div>
                <span className={styles.usageCount}>
                  {activeUsage.current} / {activeUsage.limit} {activeTab === 'my-documents' ? 'documents' : 'images'}
                </span>
              </div>

              {/* Upload zone */}
              <div
                className={`${styles.uploadZone} ${isDragging ? styles.dragOver : ''}`}
                onDragOver={handleDragOver}
                onDragLeave={handleDragLeave}
                onDrop={handleDrop}
              >
                <svg
                  className={styles.uploadIcon}
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="1.5"
                >
                  <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
                  <polyline points="17 8 12 3 7 8" />
                  <line x1="12" y1="3" x2="12" y2="15" />
                </svg>
                <p className={styles.uploadText}>
                  {activeTab === 'my-documents'
                    ? 'Drag and drop a document here, or click to browse'
                    : 'Drag and drop an image here, or click to browse'}
                </p>
                <p className={styles.uploadSubtext}>
                  {activeTab === 'my-documents' ? `${PDF_TYPES_LABEL} (max 25MB)` : `${IMAGE_TYPES_LABEL} (max 10MB)`}
                </p>
                <input
                  ref={fileInputRef}
                  type="file"
                  accept={activeTab === 'my-documents' ? ACCEPTED_PDF_TYPES : ACCEPTED_IMAGE_TYPES}
                  onChange={(e) => handleFileSelect(e.target.files)}
                  style={{ display: 'none' }}
                />
                <button
                  className={styles.uploadButton}
                  onClick={() => fileInputRef.current?.click()}
                  disabled={uploadProgress !== null || activeUsage.current >= activeUsage.limit}
                >
                  {uploadProgress !== null ? 'Uploading...' : 'Choose File'}
                </button>
              </div>

              {/* Grid for active tab */}
              {activeTab === 'my-images' ? (
                myImageAssets.length === 0 ? (
                  <div className={styles.emptyState}>
                    <svg
                      className={styles.emptyStateIcon}
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="1.5"
                    >
                      <rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
                      <circle cx="8.5" cy="8.5" r="1.5" />
                      <polyline points="21 15 16 10 5 21" />
                    </svg>
                    <p className={styles.emptyStateText}>No images yet</p>
                    <p className={styles.emptyStateSubtext}>Upload your first image to get started</p>
                  </div>
                ) : (
                  <div className={styles.imageGrid}>
                    {myImageAssets.map((image) => {
                      const isSelected = selectedImage?.id === image.id;
                      return (
                        <div
                          key={image.id}
                          className={`${styles.imageCard} ${isSelected ? styles.selected : ''}`}
                          onClick={() =>
                            handleImageClick({
                              id: image.id,
                              url: image.url,
                              source: 'my-images',
                              filename: image.filename,
                              alt: image.alt || undefined,
                            })
                          }
                        >
                          {/* eslint-disable-next-line @next/next/no-img-element */}
                          <img
                            src={image.url}
                            alt={image.alt || image.filename}
                            className={styles.imageCardImg}
                          />
                          <div className={styles.imageCardOverlay} />
                          <span className={styles.imageCardName}>{image.filename}</span>
                          {isSelected && (
                            <span className={styles.selectedBadge}>
                              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3">
                                <polyline points="20 6 9 17 4 12" />
                              </svg>
                            </span>
                          )}
                          <div className={styles.imageCardActions}>
                            <button
                              className={styles.deleteButton}
                              onClick={(e) => handleDelete(e, image.id)}
                              title="Delete image"
                            >
                              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                <path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
                              </svg>
                            </button>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )
              ) : (
                myDocumentAssets.length === 0 ? (
                  <div className={styles.emptyState}>
                    <svg
                      className={styles.emptyStateIcon}
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="1.5"
                    >
                      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
                      <polyline points="14 2 14 8 20 8" />
                      <line x1="16" y1="13" x2="8" y2="13" />
                      <line x1="16" y1="17" x2="8" y2="17" />
                    </svg>
                    <p className={styles.emptyStateText}>No documents yet</p>
                    <p className={styles.emptyStateSubtext}>Upload your first PDF to get started</p>
                  </div>
                ) : (
                  <div className={styles.imageGrid}>
                    {myDocumentAssets.map((doc) => {
                      const isSelected = selectedImage?.id === doc.id;
                      return (
                        <div
                          key={doc.id}
                          className={`${styles.imageCard} ${isSelected ? styles.selected : ''}`}
                          onClick={() =>
                            handleImageClick({
                              id: doc.id,
                              url: `/api/documents/${doc.id}`,
                              source: 'my-images',
                              filename: doc.filename,
                              alt: doc.alt || undefined,
                            })
                          }
                        >
                          <div className={styles.pdfThumbnail}>
                            <svg className={styles.pdfIcon} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
                              <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
                              <polyline points="14 2 14 8 20 8" />
                              <line x1="16" y1="13" x2="8" y2="13" />
                              <line x1="16" y1="17" x2="8" y2="17" />
                            </svg>
                            <span className={styles.pdfFilename}>{doc.filename}</span>
                            <span className={styles.pdfBadge}>PDF</span>
                          </div>
                          {isSelected && (
                            <span className={styles.selectedBadge}>
                              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3">
                                <polyline points="20 6 9 17 4 12" />
                              </svg>
                            </span>
                          )}
                          <div className={styles.pdfActions}>
                            <a
                              className={styles.actionButton}
                              href={`/api/documents/${doc.id}`}
                              target="_blank"
                              rel="noopener noreferrer"
                              title="Open PDF"
                              onClick={(e) => e.stopPropagation()}
                            >
                              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
                                <polyline points="15 3 21 3 21 9" />
                                <line x1="10" y1="14" x2="21" y2="3" />
                              </svg>
                            </a>
                            <button
                              className={styles.actionButton}
                              onClick={(e) => { e.stopPropagation(); handleCopyUrl(`/api/documents/${doc.id}`, doc.id); }}
                              title={copiedId === doc.id ? 'Copied!' : 'Copy URL'}
                            >
                              {copiedId === doc.id ? (
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                  <polyline points="20 6 9 17 4 12" />
                                </svg>
                              ) : (
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                  <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" />
                                  <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" />
                                </svg>
                              )}
                            </button>
                          </div>
                          <div className={styles.imageCardActions}>
                            <button
                              className={styles.deleteButton}
                              onClick={(e) => handleDelete(e, doc.id)}
                              title="Delete document"
                            >
                              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                                <path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
                              </svg>
                            </button>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )
              )}
            </>
          ) : (
            <>
              {/* Category filter */}
              {categories.length > 1 && (
                <div className={styles.categoryFilter}>
                  {categories.map((category) => (
                    <button
                      key={category}
                      className={`${styles.categoryButton} ${categoryFilter === category ? styles.active : ''}`}
                      onClick={() => setCategoryFilter(category)}
                    >
                      {category === 'all'
                        ? 'All'
                        : category.charAt(0).toUpperCase() + category.slice(1)}
                    </button>
                  ))}
                </div>
              )}

              {/* AMSOIL Images grid */}
              {filteredAmsoilImages.length === 0 ? (
                <div className={styles.emptyState}>
                  <svg
                    className={styles.emptyStateIcon}
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="1.5"
                  >
                    <rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
                    <circle cx="8.5" cy="8.5" r="1.5" />
                    <polyline points="21 15 16 10 5 21" />
                  </svg>
                  <p className={styles.emptyStateText}>No AMSOIL images available</p>
                  <p className={styles.emptyStateSubtext}>
                    Check back later for branded images from AMSOIL
                  </p>
                </div>
              ) : (
                <div className={styles.imageGrid}>
                  {filteredAmsoilImages.map((image) => {
                    const isSelected = selectedImage?.id === image.id;
                    return (
                      <div
                        key={image.id}
                        className={`${styles.imageCard} ${isSelected ? styles.selected : ''}`}
                        onClick={() =>
                          handleImageClick({
                            id: image.id,
                            url: image.url,
                            source: 'amsoil',
                            filename: image.filename,
                            alt: image.name,
                          })
                        }
                      >
                        {/* eslint-disable-next-line @next/next/no-img-element */}
                        <img src={image.url} alt={image.name} className={styles.imageCardImg} />
                        <div className={styles.imageCardOverlay} />
                        <span className={styles.imageCardName}>{image.name}</span>
                        {isSelected && (
                          <span className={styles.selectedBadge}>
                            <svg
                              width="14"
                              height="14"
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              strokeWidth="3"
                            >
                              <polyline points="20 6 9 17 4 12" />
                            </svg>
                          </span>
                        )}
                      </div>
                    );
                  })}
                </div>
              )}
            </>
          )}
        </div>

        {/* Footer */}
        <div className={styles.modalFooter}>
          <div className={styles.footerLeft}>
            {selectedImage && <span>Selected: {selectedImage.filename}</span>}
          </div>
          <div className={styles.footerRight}>
            <button className={styles.cancelButton} onClick={onClose}>
              Cancel
            </button>
            <button
              className={styles.selectButton}
              onClick={handleSelect}
              disabled={!selectedImage}
            >
              Select Image
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
