'use client';

import { useState, ComponentType } from 'react';
import { X } from 'lucide-react';

export interface ActivityTypeOption {
  value: string;
  label: string;
  icon: ComponentType<any>;
}

export interface OutcomeOption {
  value: string;
  label: string;
}

export interface LogActivityFormData {
  type: string;
  title: string;
  description: string;
  outcome: string | undefined;
  durationMinutes: number | undefined;
  occurredAt: string;
}

export interface LogActivityDialogProps {
  activityTypes: ActivityTypeOption[];
  outcomeOptions: OutcomeOption[];
  defaultType?: string;
  onSubmit: (data: LogActivityFormData) => Promise<void>;
  onClose: () => void;
  isSubmitting?: boolean;
  /** Activity types for which outcome is required */
  outcomeRequiredTypes?: string[];
  /** Activity types for which duration field is shown */
  durationTypes?: string[];
  /** Activity types with follow-up checkbox, mapped to outcome values that trigger it */
  followUpOutcomes?: string[];
  title?: string;
  submitLabel?: string;
  submittingLabel?: string;
}

export function LogActivityDialog({
  activityTypes,
  outcomeOptions,
  defaultType,
  onSubmit,
  onClose,
  isSubmitting = false,
  outcomeRequiredTypes = ['call', 'meeting'],
  durationTypes = ['call', 'meeting'],
  followUpOutcomes = ['callback_later', 'scheduled_meeting'],
  title = 'Log Activity',
  submitLabel = 'Log Activity',
  submittingLabel = 'Logging...',
}: LogActivityDialogProps) {
  const initialType = defaultType || activityTypes[0]?.value || '';
  const [activityType, setActivityType] = useState(initialType);
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    outcome: undefined as string | undefined,
    durationMinutes: undefined as number | undefined,
    occurredAt: new Date().toISOString().slice(0, 16),
  });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [createFollowUp, setCreateFollowUp] = useState(false);

  const showOutcome = outcomeRequiredTypes.includes(activityType);
  const showDuration = durationTypes.includes(activityType);
  const showFollowUp =
    followUpOutcomes.length > 0 &&
    formData.outcome !== undefined &&
    followUpOutcomes.includes(formData.outcome);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    const newErrors: Record<string, string> = {};
    if (!formData.title.trim()) {
      newErrors.title = 'Title is required';
    }
    if (showOutcome && !formData.outcome) {
      newErrors.outcome = 'Outcome is required for this activity type';
    }

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      return;
    }

    try {
      await onSubmit({
        type: activityType,
        title: formData.title,
        description: formData.description,
        outcome: formData.outcome,
        durationMinutes: formData.durationMinutes,
        occurredAt: formData.occurredAt
          ? new Date(formData.occurredAt).toISOString()
          : new Date().toISOString(),
      });
    } catch (error) {
      console.error('Failed to log activity:', error);
    }
  };

  const handleChange = (
    field: keyof typeof formData,
    value: string | number | undefined
  ) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: undefined as any }));
    }
  };

  const currentTypeLabel =
    activityTypes.find((t) => t.value === activityType)?.label || '';

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <h2 className="text-xl font-semibold text-gray-900">{title}</h2>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="p-6 space-y-4">
          {/* Activity Type Selection */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Activity Type *
            </label>
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
              {activityTypes.map(({ value, label, icon: Icon }) => (
                <button
                  key={value}
                  type="button"
                  onClick={() => setActivityType(value)}
                  className={`flex items-center justify-center gap-2 px-4 py-3 text-sm font-medium rounded-lg border-2 transition-colors ${
                    activityType === value
                      ? 'border-primary bg-primary/10 text-primary'
                      : 'border-gray-200 bg-white text-gray-700 hover:bg-gray-50'
                  }`}
                >
                  <Icon className="w-4 h-4" />
                  {label}
                </button>
              ))}
            </div>
          </div>

          {/* Title */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Title *
            </label>
            <input
              type="text"
              value={formData.title}
              onChange={(e) => handleChange('title', e.target.value)}
              className={`w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 ${
                errors.title ? 'border-red-500' : 'border-gray-300'
              }`}
              placeholder={`${currentTypeLabel} with...`}
            />
            {errors.title && (
              <p className="mt-1 text-sm text-red-600">{errors.title}</p>
            )}
          </div>

          {/* Date/Time and Duration */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Date & Time
              </label>
              <input
                type="datetime-local"
                value={formData.occurredAt?.slice(0, 16) || ''}
                onChange={(e) => handleChange('occurredAt', e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>

            {showDuration && (
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Duration (minutes)
                </label>
                <input
                  type="number"
                  value={formData.durationMinutes || ''}
                  onChange={(e) =>
                    handleChange(
                      'durationMinutes',
                      e.target.value ? parseInt(e.target.value) : undefined
                    )
                  }
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="30"
                  min="1"
                />
              </div>
            )}
          </div>

          {/* Outcome */}
          {showOutcome && (
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Outcome *
              </label>
              <select
                value={formData.outcome || ''}
                onChange={(e) =>
                  handleChange('outcome', e.target.value || undefined)
                }
                className={`w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 ${
                  errors.outcome ? 'border-red-500' : 'border-gray-300'
                }`}
              >
                <option value="">Select outcome...</option>
                {outcomeOptions.map((outcome) => (
                  <option key={outcome.value} value={outcome.value}>
                    {outcome.label}
                  </option>
                ))}
              </select>
              {errors.outcome && (
                <p className="mt-1 text-sm text-red-600">{errors.outcome}</p>
              )}
            </div>
          )}

          {/* Description */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Notes
            </label>
            <textarea
              value={formData.description || ''}
              onChange={(e) => handleChange('description', e.target.value)}
              rows={4}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="Add details about this activity..."
            />
          </div>

          {/* Follow-up Task */}
          {showFollowUp && (
            <div className="bg-primary/10 border border-primary/30 rounded-lg p-4">
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={createFollowUp}
                  onChange={(e) => setCreateFollowUp(e.target.checked)}
                  className="w-4 h-4 text-primary border-gray-300 rounded focus:ring-ring"
                />
                <span className="text-sm font-medium text-blue-900">
                  Create follow-up task
                </span>
              </label>
              {createFollowUp && (
                <p className="text-xs text-blue-700 mt-2">
                  A task reminder will be created for this follow-up
                </p>
              )}
            </div>
          )}

          {/* Actions */}
          <div className="flex justify-end gap-3 pt-4">
            <button
              type="button"
              onClick={onClose}
              disabled={isSubmitting}
              className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={isSubmitting}
              className="px-4 py-2 text-sm font-medium text-primary-foreground bg-primary rounded-md hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              {isSubmitting ? submittingLabel : submitLabel}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
