import React, { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { apiClient, type RouteRequest, type Feed, type PlatformChannel } from '../../../lib/api';

const RouteStep: React.FC = () => {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [formData, setFormData] = useState<RouteRequest>({
    feed_id: 0,
    platform_channel_id: 0,
    priority: 50
  });
  const [errors, setErrors] = useState<Record<string, string[]>>({});

  // Get onboarding options (feeds and channels)
  const { data: options, isLoading: optionsLoading } = useQuery({
    queryKey: ['onboarding-options'],
    queryFn: () => apiClient.getOnboardingOptions()
  });

  const createRouteMutation = useMutation({
    mutationFn: (data: RouteRequest) => apiClient.createRouteForOnboarding(data),
    onSuccess: () => {
      // Invalidate onboarding status cache to refresh the status
      queryClient.invalidateQueries({ queryKey: ['onboarding-status'] });
      queryClient.invalidateQueries({ queryKey: ['dashboard-stats'] });
      navigate('/onboarding/complete');
    },
    onError: (error: any) => {
      if (error.response?.data?.errors) {
        setErrors(error.response.data.errors);
      } else {
        setErrors({ general: [error.response?.data?.message || 'An error occurred'] });
      }
    }
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setErrors({});
    createRouteMutation.mutate(formData);
  };

  const handleChange = (field: keyof RouteRequest, value: string | number | Record<string, any>) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    // Clear field error when user starts typing
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: [] }));
    }
  };

  if (optionsLoading) {
    return <div className="text-center">Loading...</div>;
  }

  return (
    <div className="text-center mb-8">
      <h1 className="text-2xl font-bold text-gray-900 mb-2">Create Your First Route</h1>
      <p className="text-gray-600">
        Connect your feed to a channel by creating a route. This tells FFR which articles to post where.
      </p>
      
      {/* Progress indicator */}
      <div className="flex justify-center mt-6 space-x-2">
        <div className="w-6 h-6 bg-green-500 text-white rounded-full flex items-center justify-center text-xs font-semibold">✓</div>
        <div className="w-6 h-6 bg-green-500 text-white rounded-full flex items-center justify-center text-xs font-semibold">✓</div>
        <div className="w-6 h-6 bg-green-500 text-white rounded-full flex items-center justify-center text-xs font-semibold">✓</div>
        <div className="w-6 h-6 bg-blue-500 text-white rounded-full flex items-center justify-center text-xs font-semibold">4</div>
        <div className="w-6 h-6 bg-gray-300 text-gray-600 rounded-full flex items-center justify-center text-xs font-semibold">5</div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6 mt-8 text-left">
        {errors.general && (
          <div className="p-3 bg-red-50 border border-red-200 rounded-md">
            <p className="text-red-600 text-sm">{errors.general[0]}</p>
          </div>
        )}
        
        <div>
          <label htmlFor="feed_id" className="block text-sm font-medium text-gray-700 mb-2">
            Select Feed
          </label>
          <select 
            id="feed_id" 
            value={formData.feed_id || ''}
            onChange={(e) => handleChange('feed_id', e.target.value ? parseInt(e.target.value) : 0)}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            required
          >
            <option value="">Select a feed</option>
            {options?.feeds?.map((feed: Feed) => (
              <option key={feed.id} value={feed.id}>
                {feed.name}
              </option>
            ))}
          </select>
          {errors.feed_id && (
            <p className="text-red-600 text-sm mt-1">{errors.feed_id[0]}</p>
          )}
        </div>

        <div>
          <label htmlFor="platform_channel_id" className="block text-sm font-medium text-gray-700 mb-2">
            Select Channel
          </label>
          <select 
            id="platform_channel_id" 
            value={formData.platform_channel_id || ''}
            onChange={(e) => handleChange('platform_channel_id', e.target.value ? parseInt(e.target.value) : 0)}
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            required
          >
            <option value="">Select a channel</option>
            {options?.platform_channels?.map((channel: PlatformChannel) => (
              <option key={channel.id} value={channel.id}>
                {channel.display_name || channel.name}
              </option>
            ))}
          </select>
          {(!options?.platform_channels || options.platform_channels.length === 0) && (
            <p className="text-sm text-gray-500 mt-1">
              No channels available. Please create a channel first.
            </p>
          )}
          {errors.platform_channel_id && (
            <p className="text-red-600 text-sm mt-1">{errors.platform_channel_id[0]}</p>
          )}
        </div>
        
        <div>
          <label htmlFor="priority" className="block text-sm font-medium text-gray-700 mb-2">
            Priority (1-100)
          </label>
          <input 
            type="number" 
            id="priority" 
            min="1"
            max="100"
            value={formData.priority || 50}
            onChange={(e) => handleChange('priority', parseInt(e.target.value))}
            placeholder="50"
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          />
          <p className="text-sm text-gray-500 mt-1">
            Higher priority routes are processed first (default: 50)
          </p>
          {errors.priority && (
            <p className="text-red-600 text-sm mt-1">{errors.priority[0]}</p>
          )}
        </div>
        
        <div className="flex justify-between">
          <Link 
            to="/onboarding/channel"
            className="px-4 py-2 text-gray-600 hover:text-gray-800 transition duration-200"
          >
            ← Back
          </Link>
          <button 
            type="submit" 
            disabled={createRouteMutation.isPending || (!options?.platform_channels || options.platform_channels.length === 0)}
            className="bg-blue-600 text-white py-2 px-6 rounded-md hover:bg-blue-700 transition duration-200 disabled:opacity-50"
          >
            {createRouteMutation.isPending ? 'Creating...' : 'Continue'}
          </button>
        </div>
      </form>
    </div>
  );
};

export default RouteStep;