import React, { useEffect, useState } from 'react';

import { useMarketplaceProject } from '../../project/MarketplaceProjectProvider';

interface ProjectApplicationModalProps {
  projectId: string;
  isOpen: boolean;
  onClose: () => void;
  onApplicationSubmitted: () => void;
}

const ProjectApplicationModal: React.FC<ProjectApplicationModalProps> = ({
  isOpen,
  onClose,
  onApplicationSubmitted,
}) => {
  const { handleSubmitApplication, project } = useMarketplaceProject();
  const [message, setMessage] = useState('');
  const [portfolioUrl, setPortfolioUrl] = useState('');
  const [estimatedDays, setEstimatedDays] = useState<number | ''>(7);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [deadlineWarning, setDeadlineWarning] = useState('');

  // Calculate days until deadline from today
  const getDaysUntilDeadline = (
    deadline: string | null | undefined
  ): number | null => {
    if (!deadline) return null;
    const deadlineDate = new Date(deadline);
    const now = new Date();
    const deadlineStart = new Date(
      deadlineDate.getFullYear(),
      deadlineDate.getMonth(),
      deadlineDate.getDate()
    );
    const nowStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const diffTime = deadlineStart.getTime() - nowStart.getTime();
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    return diffDays > 0 ? diffDays : null;
  };

  // Initialize estimatedDays to project deadline when modal opens
  useEffect(() => {
    if (isOpen && project?.deadline) {
      const daysUntilDeadline = getDaysUntilDeadline(project.deadline);
      if (daysUntilDeadline !== null && daysUntilDeadline > 0) {
        setEstimatedDays(daysUntilDeadline);
      }
    } else if (!isOpen) {
      // Reset form when modal closes
      setMessage('');
      setPortfolioUrl('');
      setEstimatedDays(7);
      setError('');
      setSuccess('');
      setDeadlineWarning('');
      setIsSubmitted(false);
    }
  }, [isOpen, project?.deadline]);

  // Validate estimatedDays against deadline
  useEffect(() => {
    if (
      project?.deadline &&
      estimatedDays !== '' &&
      typeof estimatedDays === 'number'
    ) {
      const daysUntilDeadline = getDaysUntilDeadline(project.deadline);
      if (daysUntilDeadline !== null && estimatedDays > daysUntilDeadline) {
        setDeadlineWarning(
          `Your estimated completion time (${estimatedDays} days) exceeds the project deadline (${daysUntilDeadline} days). Please adjust your estimate to meet the deadline.`
        );
      } else {
        setDeadlineWarning('');
      }
    } else {
      setDeadlineWarning('');
    }
  }, [estimatedDays, project?.deadline]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!message.trim()) {
      setError(
        "Please provide a message explaining why you're a good fit for this project."
      );
      return;
    }

    // Check if estimatedDays exceeds deadline
    if (
      project?.deadline &&
      estimatedDays !== '' &&
      typeof estimatedDays === 'number'
    ) {
      const daysUntilDeadline = getDaysUntilDeadline(project.deadline);
      if (daysUntilDeadline !== null && estimatedDays > daysUntilDeadline) {
        setError(
          `Your estimated completion time (${estimatedDays} days) exceeds the project deadline (${daysUntilDeadline} days). Please adjust your estimate to meet the deadline.`
        );
        return;
      }
    }

    setIsSubmitting(true);
    setError('');
    setSuccess('');

    try {
      await handleSubmitApplication(
        message.trim(),
        portfolioUrl.trim() || undefined,
        estimatedDays ? Number(estimatedDays) : undefined
      );

      // Show success message and hide form
      setSuccess(
        'Application submitted successfully! The creator will review your application.'
      );
      setIsSubmitted(true);

      // Reset form
      setMessage('');
      setPortfolioUrl('');
      setEstimatedDays(7);

      // Close modal after a short delay
      setTimeout(() => {
        onApplicationSubmitted();
        onClose();
        // Reset submitted state for next time
        setIsSubmitted(false);
      }, 2000);
    } catch (err) {
      console.error('Error submitting application:', err);
      setError(
        err instanceof Error ? err.message : 'Failed to submit application'
      );
    } finally {
      setIsSubmitting(false);
    }
  };

  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/50 backdrop-blur-sm'
        onClick={onClose}
        onKeyDown={(e) => {
          if (e.key === 'Escape') {
            onClose();
          }
        }}
        role='button'
        tabIndex={0}
        aria-label='Close modal'
      />

      {/* Modal */}
      <div className='relative mx-4 w-full max-w-2xl rounded-2xl bg-background-primary p-8'>
        {/* Header */}
        <div className='mb-6 flex items-center justify-between'>
          <h2 className='text-2xl font-bold text-foreground-primary'>
            Apply to Project
          </h2>
          <button
            onClick={onClose}
            className='text-foreground-secondary transition-colors hover:text-foreground-primary'
          >
            <svg
              className='h-6 w-6'
              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>

        {/* Success Message */}
        {success && isSubmitted && (
          <div className='rounded-lg border border-accent-brand/20 bg-accent-brand/5 p-4'>
            <div className='flex'>
              <div className='mt-2 h-2 w-2 flex-shrink-0 rounded-full bg-accent-brand'></div>
              <div className='ml-3'>
                <p className='text-sm text-foreground-primary'>{success}</p>
              </div>
            </div>
          </div>
        )}

        {/* Form */}
        {!isSubmitted && (
          <form onSubmit={handleSubmit} className='space-y-6'>
            {/* Error Message */}
            {error && (
              <div className='rounded-lg border border-red-200 bg-red-50 p-4'>
                <div className='flex'>
                  <svg
                    className='h-5 w-5 text-red-400'
                    fill='currentColor'
                    viewBox='0 0 20 20'
                  >
                    <path
                      fillRule='evenodd'
                      d='M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z'
                      clipRule='evenodd'
                    />
                  </svg>
                  <div className='ml-3'>
                    <p className='text-sm text-red-800'>{error}</p>
                  </div>
                </div>
              </div>
            )}

            {/* Profile Sharing Notice */}
            <div className='rounded-lg border border-accent-brand/20 bg-accent-brand/5 p-4'>
              <div className='flex'>
                <div className='mt-2 h-2 w-2 flex-shrink-0 rounded-full bg-accent-brand'></div>
                <div className='ml-3'>
                  <h3 className='text-sm font-medium text-foreground-primary'>
                    Profile Sharing
                  </h3>
                  <p className='mt-1 text-sm text-foreground-secondary'>
                    By applying to this project, your Suno profile (including
                    your display name, handle, and avatar) will be shared with
                    the project creator for review purposes.
                  </p>
                </div>
              </div>
            </div>

            {/* Application Message */}
            <div>
              <label
                htmlFor='application-message'
                className='mb-2 block text-sm font-medium text-foreground-primary'
              >
                Why are you a good fit for this project? *
              </label>
              <textarea
                id='application-message'
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                rows={1}
                className='w-full rounded-lg border border-border-primary bg-background-secondary px-3 py-2 text-foreground-primary placeholder-foreground-secondary focus:border-accent-brand focus:outline-none'
                required
              />
              <p className='mt-1 text-xs text-foreground-secondary'>
                This message will be visible to the project creator when
                reviewing applications.
              </p>
            </div>

            {/* Portfolio URL */}
            <div>
              <label
                htmlFor='portfolio-url'
                className='mb-2 block text-sm font-medium text-foreground-primary'
              >
                Portfolio or Previous Work (Optional)
              </label>
              <input
                id='portfolio-url'
                type='url'
                value={portfolioUrl}
                onChange={(e) => setPortfolioUrl(e.target.value)}
                placeholder='https://...'
                className='w-full rounded-lg border border-border-primary bg-background-secondary px-3 py-2 text-foreground-primary placeholder-foreground-secondary focus:border-accent-brand focus:outline-none'
              />
              <p className='mt-1 text-xs text-foreground-secondary'>
                Share examples of your previous work to help the creator
                evaluate your skills.
              </p>
            </div>

            {/* Estimated Completion Time */}
            <div>
              <label
                htmlFor='estimated-days'
                className='mb-2 block text-sm font-medium text-foreground-primary'
              >
                Estimated Completion Time (Optional)
              </label>
              <div className='flex items-center gap-2'>
                <input
                  id='estimated-days'
                  type='number'
                  value={estimatedDays}
                  onChange={(e) =>
                    setEstimatedDays(
                      e.target.value ? Number(e.target.value) : ''
                    )
                  }
                  placeholder='7'
                  min='1'
                  max='365'
                  className={`w-24 rounded-lg border px-3 py-2 text-foreground-primary placeholder-foreground-secondary focus:outline-none ${
                    deadlineWarning
                      ? 'border-red-400 bg-background-secondary focus:border-red-500'
                      : 'border-border-primary bg-background-secondary focus:border-accent-brand'
                  }`}
                />
                <span className='text-sm text-foreground-secondary'>days</span>
              </div>
              {deadlineWarning ? (
                <p className='mt-1 text-xs font-medium text-red-400'>
                  {deadlineWarning}
                </p>
              ) : (
                <p className='mt-1 text-xs text-foreground-secondary'>
                  How many days do you estimate it will take to complete this
                  project?
                </p>
              )}
            </div>

            {/* Actions */}
            <div className='flex gap-3 pt-4'>
              <button
                type='button'
                onClick={onClose}
                className='flex-1 rounded-lg bg-background-secondary px-6 py-3 text-foreground-primary transition-colors hover:bg-background-secondary/80'
              >
                Cancel
              </button>
              <button
                type='submit'
                disabled={isSubmitting || !message.trim() || !!deadlineWarning}
                className='flex-1 rounded-lg bg-accent-brand px-6 py-3 text-white transition-colors hover:bg-accent-brand/90 disabled:cursor-not-allowed disabled:opacity-50'
              >
                {isSubmitting ? (
                  <div className='flex items-center justify-center gap-2'>
                    <svg
                      className='h-4 w-4 animate-spin'
                      fill='none'
                      viewBox='0 0 24 24'
                    >
                      <circle
                        className='opacity-25'
                        cx='12'
                        cy='12'
                        r='10'
                        stroke='currentColor'
                        strokeWidth='4'
                      />
                      <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'
                      />
                    </svg>
                    Submitting...
                  </div>
                ) : (
                  'Submit Application'
                )}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
};

export default ProjectApplicationModal;
