'use client';

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

interface MarketplaceDeadlineFormProps {
  deadline: string | null | undefined;
  onSave: (deadline: string) => Promise<void>;
  isSaving?: boolean;
  isCreator?: boolean;
  compact?: boolean;
}

const MarketplaceDeadlineForm: React.FC<MarketplaceDeadlineFormProps> = ({
  deadline,
  onSave,
  isSaving = false,
  isCreator = false,
  compact = false,
}) => {
  // Calculate days from deadline if provided
  const getDaysFromDeadline = (
    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.round(diffTime / (1000 * 60 * 60 * 24));
    return diffDays;
  };

  const [isEditing, setIsEditing] = useState(false);
  const [timelineDays, setTimelineDays] = useState<number>(7);
  const [isSavingDeadline, setIsSavingDeadline] = useState(false);
  const prevDeadlineRef = useRef<string | null | undefined>(undefined);
  const isInitialMount = useRef(true);

  // Initialize timelineDays from deadline on mount and when deadline changes
  useEffect(() => {
    if (deadline) {
      const days = getDaysFromDeadline(deadline);
      if (days !== null && days > 0) {
        setTimelineDays(days);
      }
      // Only reset to display mode on initial mount
      if (isInitialMount.current) {
        setIsEditing(false);
        isInitialMount.current = false;
      }
      prevDeadlineRef.current = deadline;
    } else {
      prevDeadlineRef.current = deadline;
      if (isInitialMount.current) {
        isInitialMount.current = false;
      }
    }
  }, [deadline]);

  // For creators without a deadline, show edit mode by default
  useEffect(() => {
    if (!deadline && isCreator && !isEditing) {
      setIsEditing(true);
    }
  }, [deadline, isCreator, isEditing]);

  const handleSave = async () => {
    if (timelineDays < 1 || timelineDays > 90) return;

    setIsSavingDeadline(true);
    try {
      // Calculate deadline from timeline days
      const deadlineDate = new Date();
      deadlineDate.setDate(deadlineDate.getDate() + timelineDays);
      deadlineDate.setHours(23, 59, 59, 999); // Set to end of day

      await onSave(deadlineDate.toISOString());
      // Exit edit mode after successful save
      setIsEditing(false);
    } catch (error) {
      console.error('Failed to save deadline:', error);
      // Don't exit edit mode on error - let user try again
      throw error; // Re-throw so caller knows it failed
    } finally {
      setIsSavingDeadline(false);
    }
  };

  const handleCancel = () => {
    // Reset to original deadline days
    if (deadline) {
      const days = getDaysFromDeadline(deadline);
      if (days !== null && days > 0) {
        setTimelineDays(days);
      }
    }
    setIsEditing(false);
  };

  if (!deadline && !isCreator) return null;

  // Display mode (compact for sidebar)
  if (!isEditing && deadline) {
    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.round(diffTime / (1000 * 60 * 60 * 24));
    const isOverdue = diffDays < 0;
    const isDueToday = diffDays === 0;
    const isDueSoon = diffDays > 0 && diffDays <= 3;

    const formatDate = (date: Date) => {
      return date.toLocaleDateString('en-US', {
        month: 'short',
        day: 'numeric',
        year: 'numeric',
      });
    };

    if (compact) {
      return (
        <div>
          <div className='mb-2 flex items-center justify-between'>
            <h3 className='text-sm font-medium text-foreground-secondary'>
              Deadline
            </h3>
            {isCreator && (
              <button
                onClick={() => setIsEditing(true)}
                className='text-xs text-foreground-tertiary transition-colors hover:text-foreground-primary'
                title='Edit deadline'
              >
                <svg
                  className='h-3 w-3'
                  fill='none'
                  stroke='currentColor'
                  viewBox='0 0 24 24'
                >
                  <path
                    strokeLinecap='round'
                    strokeLinejoin='round'
                    strokeWidth={2}
                    d='M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z'
                  />
                </svg>
              </button>
            )}
          </div>
          <div className='space-y-1'>
            <p className='text-sm font-medium text-foreground-primary'>
              {formatDate(deadlineDate)}
            </p>
            {isOverdue ? (
              <p className='text-xs font-medium text-red-400'>
                {Math.abs(diffDays)} day{Math.abs(diffDays) !== 1 ? 's' : ''}{' '}
                overdue
              </p>
            ) : isDueToday ? (
              <p className='text-xs font-medium text-yellow-400'>Due today</p>
            ) : isDueSoon ? (
              <p className='text-xs font-medium text-yellow-400'>
                {diffDays} day{diffDays !== 1 ? 's' : ''} left
              </p>
            ) : (
              <p className='text-xs text-foreground-tertiary'>
                {diffDays} day{diffDays !== 1 ? 's' : ''} remaining
              </p>
            )}
          </div>
        </div>
      );
    }
  }

  // Edit mode or no deadline yet
  return (
    <div className={compact ? '' : 'space-y-6'}>
      {!compact && (
        <div className='mb-8 text-center'>
          <h3 className='mb-2 text-xl font-semibold text-foreground-primary'>
            When do you need this by?
          </h3>
          <p className='text-sm text-foreground-secondary'>
            Set a timeline for when you need this project completed.
          </p>
        </div>
      )}

      {compact && (
        <div className='mb-2'>
          <h3 className='text-sm font-medium text-foreground-secondary'>
            Deadline
          </h3>
        </div>
      )}

      <div className={`space-y-4 ${compact ? 'space-y-3' : ''}`}>
        {/* Timeline Days Input */}
        <div className={`space-y-4 ${compact ? 'space-y-3' : ''}`}>
          <div
            className={`flex items-center ${compact ? 'justify-start gap-3' : 'justify-center gap-4'}`}
          >
            <input
              type='number'
              min='1'
              max='90'
              value={timelineDays}
              onChange={(e) => setTimelineDays(parseInt(e.target.value) || 1)}
              className={`rounded-lg border border-border-primary bg-transparent text-center font-semibold text-foreground-primary focus:border-accent-brand focus:outline-none ${
                compact
                  ? 'w-16 px-2 py-1.5 text-base'
                  : 'w-24 px-4 py-3 text-2xl'
              }`}
            />
            <span
              className={
                compact
                  ? 'text-sm text-foreground-secondary'
                  : 'text-lg text-foreground-secondary'
              }
            >
              {timelineDays === 1 ? 'day' : 'days'}
            </span>
          </div>

          {/* Quick select buttons */}
          <div
            className={`flex ${compact ? 'justify-start gap-1.5' : 'justify-center gap-2'} flex-wrap`}
          >
            {[3, 7, 14, 30].map((days) => (
              <button
                key={days}
                type='button'
                onClick={() => setTimelineDays(days)}
                className={`rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors ${
                  timelineDays === days
                    ? 'border-accent-brand bg-accent-brand/10 text-accent-brand'
                    : 'border-border-primary bg-background-primary text-foreground-secondary hover:bg-background-secondary'
                }`}
              >
                {days} {days === 1 ? 'day' : 'days'}
              </button>
            ))}
          </div>
        </div>

        {/* Save/Cancel buttons for compact mode */}
        {compact && (
          <div className='flex gap-2'>
            <button
              onClick={handleSave}
              disabled={
                isSavingDeadline ||
                isSaving ||
                timelineDays < 1 ||
                timelineDays > 90
              }
              className='flex-1 rounded-lg border border-accent-brand bg-accent-brand px-3 py-1.5 text-xs font-medium text-white transition-colors hover:bg-accent-brand/90 disabled:cursor-not-allowed disabled:opacity-50'
            >
              {isSavingDeadline || isSaving ? 'Saving...' : 'Save'}
            </button>
            {deadline && (
              <button
                onClick={handleCancel}
                disabled={isSavingDeadline || isSaving}
                className='rounded-lg border border-border-primary bg-background-primary px-3 py-1.5 text-xs font-medium text-foreground-primary transition-colors hover:bg-background-secondary disabled:cursor-not-allowed disabled:opacity-50'
              >
                Cancel
              </button>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

export default MarketplaceDeadlineForm;
