// app/components/admin/websites/BulkUploadModal.tsx
'use client';

import { useRef, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';

interface BulkUploadModalProps {
  isOpen: boolean;
  onClose: () => void;
  onUpload: (file: File) => Promise<void>;
  uploading: boolean;
  onDownloadSample: () => void;
}

export default function BulkUploadModal({
  isOpen,
  onClose,
  onUpload,
  uploading,
  onDownloadSample
}: BulkUploadModalProps) {
  const [dragActive, setDragActive] = useState(false);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [error, setError] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleDrag = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === "dragenter" || e.type === "dragover") {
      setDragActive(true);
    } else if (e.type === "dragleave") {
      setDragActive(false);
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);
    setError(null);
    
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      validateAndSetFile(e.dataTransfer.files[0]);
    }
  };

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    setError(null);
    if (e.target.files && e.target.files[0]) {
      validateAndSetFile(e.target.files[0]);
    }
  };

  const validateAndSetFile = (file: File) => {
    if (!file.name.endsWith('.csv')) {
      setError('Please upload a CSV file');
      return;
    }

    if (file.size > 10 * 1024 * 1024) {
      setError('File size must be less than 10MB');
      return;
    }

    setSelectedFile(file);
  };

  const handleUpload = async () => {
    if (selectedFile) {
      await onUpload(selectedFile);
    }
  };

  const clearSelectedFile = () => {
    setSelectedFile(null);
    setError(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          {/* Backdrop */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={onClose}
            className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50"
          />

          {/* Modal */}
          <motion.div
            initial={{ opacity: 0, scale: 0.95, y: 20 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.95, y: 20 }}
            className="fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-full max-w-lg z-50"
          >
            <div className="bg-var-surface rounded-2xl shadow-var-card overflow-hidden">
              {/* Header */}
              <div className="px-6 py-4 border-b border-var-border bg-var-surface-hover">
                <div className="flex items-center justify-between">
                  <div>
                    <h2 className="text-xl font-semibold text-var-text">
                      Bulk Import Websites
                    </h2>
                    <p className="text-sm text-var-text-muted mt-1">
                      Upload a CSV file with your website data
                    </p>
                  </div>
                  <button
                    onClick={onClose}
                    className="text-var-text-muted hover:text-var-text transition-colors"
                  >
                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                    </svg>
                  </button>
                </div>
              </div>

              {/* Content */}
              <div className="p-6">
                {/* Instructions */}
                <div className="mb-6 p-4 bg-var-info-bg rounded-xl border border-var-info-border">
                  <h3 className="text-sm font-medium text-var-info-text mb-2 flex items-center">
                    <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    CSV Format Instructions:
                  </h3>
                  <ul className="text-xs text-var-info-text space-y-1 list-disc pl-4">
                    <li>Download the sample file to see the required format</li>
                    <li>Category names must match exactly as they appear in the database</li>
                    <li>For SPECIAL categories with pricing, use format: CategoryName:Price</li>
                    <li>Multiple niches should be separated by semicolons (;)</li>
                    <li>User email must match an existing active user in the system</li>
                    <li>Required fields: name, slug, domain, base_price</li>
                  </ul>
                  <button
                    onClick={onDownloadSample}
                    className="mt-3 text-xs text-var-info hover:text-var-info-text font-medium inline-flex items-center"
                  >
                    <svg className="w-3 h-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                    </svg>
                    Download sample CSV
                  </button>
                </div>

                {/* Error Message */}
                {error && (
                  <div className="mb-4 p-3 bg-var-danger-bg border border-var-danger-border rounded-lg">
                    <p className="text-sm text-var-danger flex items-center">
                      <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                      </svg>
                      {error}
                    </p>
                  </div>
                )}

                {/* File Upload Area */}
                <div
                  className={`relative border-2 border-dashed rounded-xl p-8 transition-colors duration-200 cursor-pointer ${
                    dragActive 
                      ? 'border-var-primary bg-var-primary-muted' 
                      : selectedFile 
                        ? 'border-var-success bg-var-success-bg'
                        : 'border-var-border hover:border-var-border-strong hover:bg-var-surface-hover'
                  }`}
                  onDragEnter={handleDrag}
                  onDragLeave={handleDrag}
                  onDragOver={handleDrag}
                  onDrop={handleDrop}
                  onClick={() => !selectedFile && fileInputRef.current?.click()}
                >
                  <input
                    ref={fileInputRef}
                    type="file"
                    accept=".csv"
                    onChange={handleFileSelect}
                    className="hidden"
                  />

                  {selectedFile ? (
                    <div className="text-center">
                      <div className="w-12 h-12 mx-auto mb-3 rounded-full bg-var-success-bg flex items-center justify-center">
                        <svg className="w-6 h-6 text-var-success" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                        </svg>
                      </div>
                      <p className="text-sm font-medium text-var-text mb-1">
                        {selectedFile.name}
                      </p>
                      <p className="text-xs text-var-text-muted mb-3">
                        {(selectedFile.size / 1024).toFixed(2)} KB
                      </p>
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          clearSelectedFile();
                        }}
                        className="text-xs text-var-danger hover:text-var-danger/80 font-medium"
                      >
                        Remove file
                      </button>
                    </div>
                  ) : (
                    <div className="text-center">
                      <svg className="w-12 h-12 mx-auto text-var-text-muted mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                      </svg>
                      <p className="text-sm text-var-text-muted mb-1">
                        <span className="font-medium text-var-primary hover:text-var-primary-hover">
                          Click to upload
                        </span> or drag and drop
                      </p>
                      <p className="text-xs text-var-text-muted">
                        CSV files only (max 10MB)
                      </p>
                    </div>
                  )}
                </div>

                {/* Preview of columns */}
                <div className="mt-4">
                  <h4 className="text-xs font-medium text-var-text mb-2">
                    Expected CSV Headers:
                  </h4>
                  <div className="bg-var-surface-hover rounded-lg p-3 border border-var-border">
                    <code className="text-xs text-var-text-muted break-all">
                      name,slug,domain,da,dr,traffic,spam_score,backlinks,link_type,base_price,sale_price,
                      content_service_price,category,niches,special_niches,user_email,description,meta_title,
                      meta_description,is_indexable,status,featured
                    </code>
                  </div>
                </div>
              </div>

              {/* Footer */}
              <div className="px-6 py-4 border-t border-var-border bg-var-surface-hover flex justify-end space-x-3">
                <button
                  onClick={onClose}
                  disabled={uploading}
                  className="px-4 py-2 text-sm font-medium text-var-text-secondary bg-var-surface border border-var-border rounded-xl hover:bg-var-surface-hover transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  Cancel
                </button>
                <button
                  onClick={handleUpload}
                  disabled={!selectedFile || uploading}
                  className="px-4 py-2 text-sm font-medium text-white bg-var-gradient-success rounded-xl hover:opacity-90 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed inline-flex items-center"
                >
                  {uploading ? (
                    <>
                      <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                      </svg>
                      Uploading...
                    </>
                  ) : (
                    'Import Websites'
                  )}
                </button>
              </div>
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}