'use client';

import { useState, useRef, useCallback } from 'react';
import Image from 'next/image';

interface PhotoUploadModalProps {
  isOpen: boolean;
  onClose: () => void;
  onUpload: (file: File) => Promise<void>;
  currentPhoto?: string | null;
  currentPhotoUrl?: string | null; // Presigned URL for display
}

export function PhotoUploadModal({ isOpen, onClose, onUpload, currentPhoto, currentPhotoUrl }: PhotoUploadModalProps) {
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  const [isDragging, setIsDragging] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const validateFile = (file: File): string | null => {
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
    const maxSize = 5 * 1024 * 1024; // 5MB

    if (!allowedTypes.includes(file.type)) {
      return 'Only JPG, PNG, GIF, and WebP images are allowed';
    }

    if (file.size > maxSize) {
      return 'File size must be less than 5MB';
    }

    return null;
  };

  const handleFileSelect = (file: File) => {
    const validationError = validateFile(file);
    if (validationError) {
      setError(validationError);
      return;
    }

    setError(null);
    setSelectedFile(file);

    // Create preview URL
    const reader = new FileReader();
    reader.onload = (e) => {
      setPreviewUrl(e.target?.result as string);
    };
    reader.readAsDataURL(file);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      handleFileSelect(file);
    }
  };

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  }, []);

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

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);

    const file = e.dataTransfer.files?.[0];
    if (file) {
      handleFileSelect(file);
    }
  }, []);

  const handleUpload = async () => {
    if (!selectedFile) return;

    try {
      setIsUploading(true);
      setError(null);
      await onUpload(selectedFile);
      handleClose();
    } catch (err) {
      console.error('Upload failed:', err);
      setError('Failed to upload photo. Please try again.');
    } finally {
      setIsUploading(false);
    }
  };

  const handleClose = () => {
    setSelectedFile(null);
    setPreviewUrl(null);
    setError(null);
    setIsDragging(false);
    onClose();
  };

  const handleBrowseClick = () => {
    fileInputRef.current?.click();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* Backdrop */}
      <div className="absolute inset-0 bg-black/30" onClick={handleClose} />

      {/* Modal */}
      <div className="relative bg-white rounded-[20px] w-[500px] max-w-[90vw] overflow-hidden shadow-xl">
        {/* Header */}
        <div className="px-8 py-5 border-b border-[#d9d9d9] flex items-center justify-between">
          <h2 className="font-fractul font-bold text-[20px] text-[#00293d]">Upload Profile Photo</h2>
          <button onClick={handleClose} className="text-[#00293d] hover:opacity-70">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
              <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        </div>

        {/* Content */}
        <div className="px-8 py-6">
          {/* Error Message */}
          {error && (
            <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-[10px] flex items-center gap-2">
              <svg className="w-5 h-5 text-red-500 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              <p className="text-[14px] font-serif text-red-700">{error}</p>
            </div>
          )}

          {/* Preview or Upload Area */}
          {previewUrl ? (
            <div className="flex flex-col items-center">
              <div className="relative w-[200px] h-[200px] rounded-[15px] overflow-hidden mb-4">
                <Image
                  src={previewUrl}
                  alt="Preview"
                  fill
                  className="object-cover"
                />
              </div>
              <button
                onClick={() => {
                  setSelectedFile(null);
                  setPreviewUrl(null);
                }}
                className="text-[14px] font-serif text-[#e58625] hover:underline"
              >
                Choose a different photo
              </button>
            </div>
          ) : (
            <div
              onDragOver={handleDragOver}
              onDragLeave={handleDragLeave}
              onDrop={handleDrop}
              className={`border-2 border-dashed rounded-[15px] p-8 text-center transition-colors ${
                isDragging
                  ? 'border-[#e58625] bg-[#e58625]/5'
                  : 'border-[#00293d]/20 hover:border-[#e58625]/50'
              }`}
            >
              {/* Current Photo Preview */}
              {(currentPhotoUrl || currentPhoto) && (
                <div className="flex justify-center mb-4">
                  <div className="relative w-[100px] h-[100px] rounded-[10px] overflow-hidden opacity-50">
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img
                      src={currentPhotoUrl || currentPhoto || ''}
                      alt="Current photo"
                      className="w-full h-full object-cover"
                    />
                  </div>
                </div>
              )}

              <div className="flex flex-col items-center gap-3">
                <div className="w-16 h-16 bg-[#e58625]/10 rounded-full flex items-center justify-center">
                  <svg className="w-8 h-8 text-[#e58625]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                  </svg>
                </div>
                <div>
                  <p className="font-serif font-semibold text-[16px] text-[#00293d] mb-1">
                    Drag and drop your photo here
                  </p>
                  <p className="font-serif text-[14px] text-[#00293d]/60">
                    or{' '}
                    <button
                      onClick={handleBrowseClick}
                      className="text-[#e58625] hover:underline font-semibold"
                    >
                      browse files
                    </button>
                  </p>
                </div>
                <p className="font-serif text-[12px] text-[#00293d]/40">
                  JPG, PNG, GIF, WebP • Max 5MB
                </p>
              </div>

              <input
                ref={fileInputRef}
                type="file"
                accept="image/jpeg,image/jpg,image/png,image/gif,image/webp"
                onChange={handleInputChange}
                className="hidden"
              />
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="px-8 py-5 border-t border-[#d9d9d9] flex items-center justify-end gap-3">
          <button
            onClick={handleClose}
            disabled={isUploading}
            className="px-6 py-3 rounded-[15px] border border-[#00293d]/20 font-serif font-semibold text-[14px] text-[#00293d] hover:bg-gray-50 transition-colors disabled:opacity-50"
          >
            Cancel
          </button>
          <button
            onClick={handleUpload}
            disabled={!selectedFile || isUploading}
            className="px-6 py-3 rounded-[15px] bg-[#e58625] font-serif font-semibold text-[14px] text-white hover:bg-[#d47720] transition-colors disabled:opacity-50 flex items-center gap-2"
          >
            {isUploading && (
              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
            )}
            {isUploading ? 'Uploading...' : 'Upload Photo'}
          </button>
        </div>
      </div>
    </div>
  );
}
