'use client';

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

interface ExperienceDocument {
  id: string;
  filename: string;
  fileUrl: string;
  fileSize: string;
  fileType: string;
}

interface Experience {
  id: string;
  title: string;
  company: string;
  location: string;
  startDate: string;
  endDate?: string;
  isCurrent: boolean;
  description: string;
  documents: ExperienceDocument[];
  createdAt: string;
  updatedAt: string;
}

interface AddExperienceModalProps {
  isOpen: boolean;
  onClose: () => void;
  experience?: Experience | null;
  onExperienceUpdated: () => void;
}

export default function AddExperienceModal({ 
  isOpen, 
  onClose, 
  experience, 
  onExperienceUpdated 
}: AddExperienceModalProps) {
  const [formData, setFormData] = useState({
    title: '',
    company: '',
    location: '',
    startDate: '',
    endDate: '',
    isCurrent: false,
    description: ''
  });
  const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const fileInputRef = useRef<HTMLInputElement>(null);
  const { showError, showSuccess } = useToast();

  // Initialize form data when experience prop changes
  useEffect(() => {
    if (experience) {
      setFormData({
        title: experience.title || '',
        company: experience.company || '',
        location: experience.location || '',
        startDate: experience.startDate ? new Date(experience.startDate).toISOString().split('T')[0] : '',
        endDate: experience.endDate ? new Date(experience.endDate).toISOString().split('T')[0] : '',
        isCurrent: experience.isCurrent || false,
        description: experience.description || ''
      });
    } else {
      setFormData({
        title: '',
        company: '',
        location: '',
        startDate: '',
        endDate: '',
        isCurrent: false,
        description: ''
      });
    }
    setSelectedFiles([]);
    setErrors({});
  }, [experience, isOpen]);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value, type } = e.target;

    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? (e.target as HTMLInputElement).checked : value
    }));

    // Clear error when user starts typing
    if (errors[name]) {
      setErrors(prev => ({
        ...prev,
        [name]: ''
      }));
    }
  };

  const handleFileSelect = (files: FileList) => {
    const newFiles = Array.from(files);
    const validFiles: File[] = [];
    
    newFiles.forEach(file => {
      // Validate file type
      if (!file.type.match(/^(image|application\/pdf|text|application\/msword|application\/vnd\.openxmlformats-officedocument\.wordprocessingml\.document).*$/)) {
        showError(`File "${file.name}" is not a supported format`);
        return;
      }
      
      // Validate file size (max 10MB)
      if (file.size > 10 * 1024 * 1024) {
        showError(`File "${file.name}" exceeds 10MB limit`);
        return;
      }
      
      validFiles.push(file);
    });
    
    setSelectedFiles(prev => [...prev, ...validFiles]);
  };

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

  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);
    }
  };

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

  const handleRemoveFile = (index: number) => {
    setSelectedFiles(prev => prev.filter((_, i) => i !== index));
  };

  const validateForm = () => {
    const newErrors: Record<string, string> = {};

    if (!formData.title.trim()) {
      newErrors.title = 'Title is required';
    }

    if (!formData.company.trim()) {
      newErrors.company = 'Company is required';
    }

    if (!formData.startDate.trim()) {
      newErrors.startDate = 'Start date is required';
    }

    if (!formData.isCurrent && !formData.endDate.trim()) {
      newErrors.endDate = 'End date is required when not current position';
    }

    if (formData.startDate && formData.endDate && new Date(formData.startDate) > new Date(formData.endDate)) {
      newErrors.endDate = 'End date must be after start date';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }
    
    setIsSubmitting(true);
    
    try {
      const submitData = new FormData();
      submitData.append('title', formData.title.trim());
      submitData.append('company', formData.company.trim());
      submitData.append('location', formData.location.trim());
      submitData.append('startDate', formData.startDate);
      if (formData.endDate) {
        submitData.append('endDate', formData.endDate);
      }
      submitData.append('isCurrent', formData.isCurrent.toString());
      submitData.append('description', formData.description.trim());
      
      // Add files to form data
      selectedFiles.forEach((file, index) => {
        submitData.append(`documents`, file);
      });
      
      const url = experience 
        ? `/api/freelancer/experiences/${experience.id}`
        : '/api/freelancer/experiences';
      
      const method = experience ? 'PUT' : 'POST';
      
      const response = await fetch(url, {
        method,
        body: submitData,
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to save experience');
      }
      
      const data = await response.json();
      
      if (data.success) {
        showSuccess(experience ? 'Experience updated successfully!' : 'Experience added successfully!');
        onExperienceUpdated();
      } else {
        throw new Error(data.error || 'Failed to save experience');
      }
      
    } catch (error: any) {
      console.error('Error submitting experience:', error);
      showError(error.message || 'Failed to save experience');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleClose = () => {
    if (!isSubmitting) {
      setFormData({
        title: '',
        company: '',
        location: '',
        startDate: '',
        endDate: '',
        isCurrent: false,
        description: ''
      });
      setSelectedFiles([]);
      setErrors({});
      onClose();
    }
  };

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

  if (!isOpen) return null;

  return (
    <div className="modal fade show custom-modal modal-overlay" onClick={handleClose}>
      <div className='modal-dialog w-100 modal-dialog-centered'>
        <div className="modal-content" onClick={(e) => e.stopPropagation()}>
          <div className="modal-header-borderless tab-title mb-4">
            <h5>{experience ? 'Edit Experience' : 'Add Experience'}</h5>
            <button 
              className="btn-close" 
              onClick={handleClose}
              disabled={isSubmitting}
            >
            </button>
          </div>

          <div className="modal-body-no-pb">
            <form onSubmit={handleSubmit}>
              <div className="form-group">
                <div className="mb-20">
                  <label htmlFor="title" className="form-label">Title</label>
                  <div className="input-icon">
                    <input
                      type="text"
                      className={`form-control ${errors.title ? 'error' : ''}`}
                      name="title"
                      id="title"
                      placeholder="Enter Job Title"
                      value={formData.title}
                      onChange={handleInputChange}
                      disabled={isSubmitting}
                    />
                  </div>
                  {errors.title && <div className="error-message">{errors.title}</div>}
                </div>

                <div className="mb-20">
                  <label htmlFor="company" className="form-label">Company</label>
                  <div className="input-icon">
                    <input
                      type="text"
                      className={`form-control ${errors.company ? 'error' : ''}`}
                      name="company"
                      id="company"
                      placeholder="Enter Company Name"
                      value={formData.company}
                      onChange={handleInputChange}
                      disabled={isSubmitting}
                    />
                  </div>
                  {errors.company && <div className="error-message">{errors.company}</div>}
                </div>
              </div>

              <div className="form-group">
                <div className="mb-20">
                  <label htmlFor="startDate" className="form-label">Start Date</label>
                  <div className="input-icon">
                    <input
                      type="date"
                      className={`form-control ${errors.startDate ? 'error' : ''}`}
                      name="startDate"
                      id="startDate"
                      value={formData.startDate}
                      onChange={handleInputChange}
                      disabled={isSubmitting}
                    />
                  </div>
                  {errors.startDate && <div className="error-message">{errors.startDate}</div>}
                </div>

                <div className="mb-20">
                  <label htmlFor="endDate" className="form-label">End Date</label>
                  <div className="input-icon">
                    <input
                      type="date"
                      className={`form-control ${errors.endDate ? 'error' : ''}`}
                      name="endDate"
                      id="endDate"
                      value={formData.endDate}
                      onChange={handleInputChange}
                      disabled={isSubmitting || formData.isCurrent}
                    />
                  </div>
                  {errors.endDate && <div className="error-message">{errors.endDate}</div>}
                </div>
              </div>

              <div className="form-group single-column">
                <div className="mb-20">
                  <div className="form-check">
                    <input
                      type="checkbox"
                      className="form-check-input"
                      name="isCurrent"
                      id="isCurrent"
                      checked={formData.isCurrent}
                      onChange={handleInputChange}
                      disabled={isSubmitting}
                    />
                    <label htmlFor="isCurrent" className="form-check-label">
                      I currently work here
                    </label>
                  </div>
                </div>
              </div>

              <div className="form-group single-column">
                <div className="mb-20">
                  <label htmlFor="location" className="form-label">Location</label>
                  <div className="input-icon">
                    <input
                      type="text"
                      className={`form-control ${errors.location ? 'error' : ''}`}
                      name="location"
                      id="location"
                      placeholder="Enter Location"
                      value={formData.location}
                      onChange={handleInputChange}
                      disabled={isSubmitting}
                    />
                  </div>
                  {errors.location && <div className="error-message">{errors.location}</div>}
                </div>
              </div>

              <div className="upload-outer mb-20">
                <label className="form-label fw-semibold">Upload Documents</label>
                <div 
                  className="upload-area"
                  onDrop={handleDrop}
                  onDragOver={handleDragOver}
                >
                  {selectedFiles.length > 0 ? (
                    <div className="files-preview">
                      {selectedFiles.map((file, index) => (
                        <div key={index} className="file-preview-item">
                          <div className="file-info">
                            <div className="file-name">{file.name}</div>
                            <div className="file-size">{formatFileSize(file.size)}</div>
                          </div>
                          <button 
                            type="button" 
                            className="remove-file-btn"
                            onClick={() => handleRemoveFile(index)}
                            disabled={isSubmitting}
                          >
                            &times;
                          </button>
                        </div>
                      ))}
                      <div className="add-more-files">
                        <button 
                          type="button" 
                          className="browse-btn" 
                          onClick={handleBrowseClick}
                          disabled={isSubmitting}
                        >
                          Add more files
                        </button>
                      </div>
                    </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={isSubmitting}
                        >
                          Browse
                        </button>
                      </p>
                      <small className="text-muted">Supported formats: Images, PDF, Word documents</small>
                    </div>
                  )}
                  
                  <input 
                    type="file" 
                    ref={fileInputRef}
                    onChange={handleFileInputChange}
                    accept="image/*,application/pdf,.doc,.docx,.txt"
                    className="file-input"
                    multiple
                    disabled={isSubmitting}
                  />
                </div>
              </div>

              <div className="form-group-box">
                <div className="mb-20">
                  <label htmlFor="description" className="form-label">Description</label>
                  <div className="input-icon">
                    <textarea 
                      className="form-control" 
                      name="description"
                      id="description"
                      rows={5} 
                      placeholder="Describe your experience..."
                      value={formData.description}
                      onChange={handleInputChange}
                      disabled={isSubmitting}
                    />
                  </div>
                </div>
              </div>

              <div className="modal-actions">
                <button 
                  type="button" 
                  className="custom-btn secondary-outline" 
                  onClick={handleClose}
                  disabled={isSubmitting}
                >
                  Cancel
                </button>
                
                <button 
                  type="submit" 
                  className="custom-btn primary-fill"
                  disabled={isSubmitting}
                >
                  {isSubmitting ? 'Saving...' : (experience ? 'Update' : 'Save')}
                </button>
              </div>
            </form>
          </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-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;
        }

        .form-group {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 20px;
          margin-bottom: 20px;
        }

        .form-group.single-column {
          grid-template-columns: 1fr;
        }

        .mb-20 {
          margin-bottom: 20px;
        }

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

        .form-label:after {
          content: " *";
          color: #e74c3c;
        }

        .input-icon {
          position: relative;
          width: 100%;
        }

        .form-control {
          width: 100%;
          padding: 12px 15px;
          border: 1px solid var(--border-color);
          border-radius: 8px;
          font-size: var(--font-small);
          color: var(--typo-secondary);
          background: var(--color-white);
          transition: all 0.3s ease;
        }

        .form-control:focus {
          outline: none;
          border-color: var(--color-primary);
          box-shadow: 0 0 0 2px rgba(239, 115, 16, 0.1);
        }

        .form-control.error {
          border-color: #e74c3c;
        }

        .form-control::placeholder {
          color: var(--text-color);
        }

        .error-message {
          color: #e74c3c;
          font-size: var(--font-xs);
          margin-top: 5px;
        }

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

        .form-label.fw-semibold {
          font-weight: 600;
        }

        .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);
        }

        .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;
        }

        .files-preview {
          width: 100%;
        }

        .file-preview-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 10px 15px;
          background: var(--bg-light);
          border-radius: 8px;
          margin-bottom: 10px;
        }

        .file-info {
          flex: 1;
        }

        .file-name {
          font-size: var(--font-small);
          font-weight: 600;
          color: var(--typo-secondary);
          margin-bottom: 2px;
        }

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

        .remove-file-btn {
          background: #e74c3c;
          color: white;
          border: none;
          border-radius: 50%;
          width: 24px;
          height: 24px;
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 16px;
          font-weight: bold;
          transition: all 0.3s ease;
        }

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

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

        .add-more-files {
          text-align: center;
          padding: 15px;
          border: 1px dashed var(--border-color);
          border-radius: 8px;
          margin-top: 10px;
        }

        .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: 767px) {
          .modal-content {
            margin: 10px;
            max-height: calc(100vh - 20px);
          }

          .modal-header {
            padding: 20px;
          }

          .modal-body {
            padding: 20px;
          }

          .form-group {
            grid-template-columns: 1fr;
            gap: 0;
          }

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

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

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