'use client';

import { useState, useRef } from 'react';
import Image from 'next/image';
import { useToast } from '@/components/ui/ToastContext';

interface ProfileImageUploadModalProps {
  isOpen: boolean;
  onClose: () => void;
  currentImage?: string;
  onImageUpdated: (newImageUrl: string) => void;
}

export default function ProfileImageUploadModal({ 
  isOpen, 
  onClose, 
  currentImage, 
  onImageUpdated 
}: ProfileImageUploadModalProps) {
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const { showError, showSuccess } = useToast();

  const handleFileSelect = (file: File) => {
    // Validate file type
    if (!file.type.match(/^image\/(jpeg|jpg|png)$/)) {
      showError('Please select a valid image file (JPG or PNG)');
      return;
    }

    // Validate file size (max 5MB)
    if (file.size > 5 * 1024 * 1024) {
      showError('File size must be less than 5MB');
      return;
    }

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

  const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    const files = e.dataTransfer.files;
    if (files.length > 0) {
      handleFileSelect(files[0]);
    }
  };

  const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
  };

  const handleFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (files && files.length > 0) {
      handleFileSelect(files[0]);
    }
  };

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

  const handleRemoveImage = () => {
    setSelectedFile(null);
    setPreviewUrl(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  const handleUpload = async () => {
    if (!selectedFile) {
      showError('Please select an image to upload');
      return;
    }

    setIsUploading(true);

    try {
      const formData = new FormData();
      formData.append('profileImage', selectedFile);

      const response = await fetch('/api/freelancer/upload-profile-image', {
        method: 'POST',
        body: formData,
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to upload image');
      }

      const data = await response.json();
      
      showSuccess('Profile image updated successfully!');
      onImageUpdated(data.data.imageUrl);
      handleClose();
      
    } catch (error: any) {
      console.error('Error uploading image:', error);
      showError(error.message || 'Failed to upload image');
    } finally {
      setIsUploading(false);
    }
  };

  const handleClose = () => {
    if (!isUploading) {
      setSelectedFile(null);
      setPreviewUrl(null);
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
      onClose();
    }
  };

  if (!isOpen) return null;

  return (
    <div className="modal-overlay" onClick={handleClose}>
      <div className="modal-content" onClick={(e) => e.stopPropagation()}>
        <div className="modal-header">
          <h5>Upload Profile Picture</h5>
          <button 
            className="modal-close" 
            onClick={handleClose}
            disabled={isUploading}
          >
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M6 18L18 6M6 6L18 18" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        </div>

        <div className="modal-body">
          <div className="upload-outer">
            <label className="form-label fw-semibold">Upload Profile Picture</label>
            
            <div 
              className="upload-area"
              onDrop={handleDrop}
              onDragOver={handleDragOver}
            >
              {previewUrl ? (
                <div className="preview-box">
                  <Image 
                    src={previewUrl} 
                    alt="Preview" 
                    width={200} 
                    height={200}
                    className="preview-image"
                  />
                  <button 
                    type="button" 
                    className="remove-btn"
                    onClick={handleRemoveImage}
                    disabled={isUploading}
                  >
                    <span>&times;</span>
                  </button>
                </div>
              ) : (
                <div className="upload-placeholder">
                  <svg width="69" height="60" viewBox="0 0 69 60" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M46.208 5.70117C46.6948 5.70117 47.0897 6.09627 47.0898 6.58301C47.0898 7.06987 46.6949 7.46484 46.208 7.46484C42.0957 7.46495 38.405 10.2157 37.2334 14.1523C37.1047 14.5864 36.6701 14.848 36.2324 14.7686L36.2285 14.7734L36.1367 14.7461C35.6703 14.607 35.4039 14.1162 35.543 13.6494C36.9067 9.06679 41.154 5.70127 46.208 5.70117Z" fill="#0E9493" stroke="#787676" strokeWidth="0.3"/>
                    <path d="M56.4522 42.4384H52.0618C51.6578 42.4384 51.3301 42.1107 51.3301 41.7067C51.3301 41.3027 51.6578 40.9749 52.0618 40.9749H56.4522C62.504 40.9749 67.4281 36.0509 67.4281 29.999C67.4281 23.9471 62.504 19.023 56.4522 19.023H56.3466C56.1344 19.023 55.9326 18.9311 55.7936 18.7706C55.6546 18.6101 55.5918 18.3974 55.6222 18.1873C55.6875 17.7315 55.7204 17.2737 55.7204 16.8279C55.7204 11.5829 51.4528 7.31531 46.2079 7.31531C44.1674 7.31531 42.2215 7.95296 40.5803 9.15978C40.2196 9.42478 39.7074 9.30718 39.4989 8.91047C34.8509 0.0596993 22.7107 -1.12887 16.4166 6.57053C13.7652 9.81417 12.7234 14.0336 13.5582 18.146C13.6502 18.6002 13.3026 19.0236 12.8411 19.0236H12.5479C6.496 19.0236 1.57193 23.9477 1.57193 29.9996C1.57193 36.0514 6.496 40.9755 12.5479 40.9755H16.9382C17.3422 40.9755 17.6699 41.3032 17.6699 41.7072C17.6699 42.1113 17.3422 42.439 16.9382 42.439H12.5479C5.6889 42.439 0.108398 36.8585 0.108398 29.9995C0.108398 23.3329 5.37995 17.8742 11.9735 17.5731C11.3541 13.3066 12.5385 9.00295 15.2835 5.64437C22.0222 -2.5996 34.9364 -1.67556 40.3955 7.51707C42.1371 6.42522 44.1299 5.85244 46.2076 5.85244C52.5622 5.85244 57.5976 11.261 57.157 17.58C63.6897 17.9463 68.8913 23.3763 68.8913 29.999C68.8913 36.8585 63.3108 42.4384 56.4518 42.4384L56.4522 42.4384Z" fill="#0E9493"/>
                    <path d="M34.4023 22.8496C44.5721 22.8499 52.8457 31.1242 52.8457 41.2939C52.8454 51.4634 44.5719 59.7371 34.4023 59.7373C24.2327 59.7373 15.9583 51.4637 15.958 41.2939C15.958 31.1241 24.2324 22.8496 34.4023 22.8496ZM34.4023 24.6143C25.2053 24.6143 17.7227 32.097 17.7227 41.2939C17.7229 50.4908 25.2056 57.9736 34.4023 57.9736C43.5989 57.9734 51.0818 50.4905 51.082 41.2939C51.082 32.0971 43.599 24.6145 34.4023 24.6143Z" fill="#0E9493" stroke="#787676" strokeWidth="0.3"/>
                    <path d="M34.7368 34.043C35.1153 34.0432 35.4224 34.351 35.4224 34.7295V48.6572C35.4224 49.0362 35.1152 49.3435 34.7368 49.3438C34.3582 49.3438 34.0503 49.0359 34.0503 48.6572V34.7295C34.0503 34.3509 34.3582 34.043 34.7368 34.043Z" fill="#0E9493" stroke="#0E9493" strokeWidth="0.3"/>
                    <path d="M34.252 34.2461C34.5196 33.9784 34.954 33.9784 35.2217 34.2461L39.5068 38.5322C39.7746 38.8001 39.7747 39.2341 39.5068 39.502L39.5059 39.501C39.372 39.6351 39.197 39.7021 39.0225 39.7021C38.8474 39.7021 38.6708 39.6356 38.5371 39.502L34.7363 35.7002L30.9355 39.502C30.668 39.7696 30.2335 39.7696 29.9658 39.502C29.698 39.2342 29.6982 38.8001 29.9658 38.5322L34.252 34.2461Z" fill="#0E9493" stroke="#0E9493" strokeWidth="0.3"/>
                  </svg>
                  <p>
                    Drag & drop files or{' '}
                    <button 
                      type="button" 
                      className="browse-btn" 
                      onClick={handleBrowseClick}
                      disabled={isUploading}
                    >
                      Browse
                    </button>
                  </p>
                  <small className="text-muted">Supported formats: .jpg & .png</small>
                </div>
              )}
              
              <input 
                type="file" 
                ref={fileInputRef}
                onChange={handleFileInputChange}
                accept="image/png, image/jpeg"
                className="file-input"
                disabled={isUploading}
              />
            </div>
          </div>

          <div className="modal-actions">
            <button 
              className="custom-btn secondary-outline" 
              onClick={handleClose}
              disabled={isUploading}
            >
              Cancel
            </button>
            
            {selectedFile && (
              <button 
                className="custom-btn primary-fill"
                onClick={handleUpload}
                disabled={isUploading}
              >
                {isUploading ? 'Uploading...' : 'Update'}
              </button>
            )}
          </div>
        </div>
      </div>
      
      <style jsx>{`
        .modal-overlay {
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.7);
          display: flex;
          align-items: center;
          justify-content: center;
          z-index: 9999;
          padding: 20px;
        }

        .modal-content {
          background: var(--color-white);
          border-radius: 15px;
          width: 100%;
          max-width: 500px;
          max-height: 90vh;
          overflow-y: auto;
          box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
          animation: modalFadeIn 0.3s ease-out;
        }

        @keyframes modalFadeIn {
          from {
            opacity: 0;
            transform: scale(0.9) translateY(-20px);
          }
          to {
            opacity: 1;
            transform: scale(1) translateY(0);
          }
        }

        .modal-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 25px 30px 20px;
          border-bottom: 1px solid var(--border-color);
        }

        .modal-header h5 {
          font-size: var(--font-18);
          font-weight: 700;
          color: var(--typo-secondary);
          margin: 0;
        }

        .modal-close {
          background: none;
          border: none;
          padding: 8px;
          cursor: pointer;
          color: var(--text-color);
          border-radius: 6px;
          transition: all 0.3s ease;
        }

        .modal-close:hover:not(:disabled) {
          background: var(--light-orange);
          color: var(--color-primary);
        }

        .modal-close:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        .modal-body {
          padding: 25px 30px;
        }

        .upload-outer {
          margin-bottom: 20px;
        }

        .form-label {
          display: block;
          margin-bottom: 15px;
          font-weight: 600;
          font-size: var(--font-small);
          color: var(--typo-secondary);
        }

        .upload-area {
          position: relative;
          border: 2px dashed var(--border-color);
          border-radius: 12px;
          padding: 40px 20px;
          text-align: center;
          transition: all 0.3s ease;
          cursor: pointer;
          min-height: 200px;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .upload-area:hover {
          border-color: var(--color-primary);
          background: rgba(239, 115, 16, 0.02);
        }

        .preview-box {
          position: relative;
          display: inline-block;
        }

        .preview-image {
          border-radius: 12px;
          object-fit: cover;
          max-width: 200px;
          max-height: 200px;
        }

        .remove-btn {
          position: absolute;
          top: -10px;
          right: -10px;
          width: 32px;
          height: 32px;
          background: #e74c3c;
          color: white;
          border: none;
          border-radius: 50%;
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 18px;
          font-weight: bold;
          transition: all 0.3s ease;
        }

        .remove-btn:hover:not(:disabled) {
          background: #c0392b;
          transform: scale(1.1);
        }

        .remove-btn:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        .upload-placeholder {
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 15px;
        }

        .upload-placeholder p {
          font-size: var(--font-small);
          color: var(--typo-secondary);
          margin: 0;
        }

        .browse-btn {
          background: none;
          border: none;
          color: var(--color-primary);
          text-decoration: underline;
          cursor: pointer;
          font-size: inherit;
          padding: 0;
        }

        .browse-btn:hover:not(:disabled) {
          opacity: 0.8;
        }

        .browse-btn:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        .text-muted {
          color: var(--text-color);
          font-size: var(--font-xs);
        }

        .file-input {
          display: none;
        }

        .modal-actions {
          display: flex;
          justify-content: flex-end;
          gap: 15px;
          margin-top: 25px;
          padding-top: 20px;
          border-top: 1px solid var(--border-color);
        }

        .custom-btn {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          padding: 10px 20px;
          border-radius: 8px;
          font-size: var(--font-small);
          font-weight: 600;
          text-decoration: none;
          cursor: pointer;
          transition: all 0.3s ease;
          border: 2px solid transparent;
          min-width: 100px;
        }

        .custom-btn.primary-fill {
          background: var(--color-primary);
          color: var(--color-white);
          border-color: var(--color-primary);
        }

        .custom-btn.primary-fill:hover:not(:disabled) {
          background: transparent;
          color: var(--color-primary);
        }

        .custom-btn.secondary-outline {
          background: transparent;
          color: var(--text-color);
          border-color: var(--border-color);
        }

        .custom-btn.secondary-outline:hover:not(:disabled) {
          background: var(--border-color);
          color: var(--typo-secondary);
        }

        .custom-btn:disabled {
          opacity: 0.6;
          cursor: not-allowed;
        }

        @media (max-width: 576px) {
          .modal-content {
            margin: 10px;
            max-height: calc(100vh - 20px);
          }

          .modal-header {
            padding: 20px;
          }

          .modal-body {
            padding: 20px;
          }

          .upload-area {
            padding: 30px 15px;
          }

          .modal-actions {
            flex-direction: column;
            gap: 10px;
          }

          .custom-btn {
            width: 100%;
          }
        }
      `}</style>
    </div>
  );
}