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

const ChannelStep: React.FC = () => {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [formData, setFormData] = useState<ChannelRequest>({
    name: '',
    platform_instance_id: 0,
    language_id: 0,
    description: ''
  });
  const [errors, setErrors] = useState<Record<string, string[]>>({});

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

  const createChannelMutation = useMutation({
    mutationFn: (data: ChannelRequest) => apiClient.createChannelForOnboarding(data),
    onSuccess: () => {
      // Invalidate onboarding status cache
      queryClient.invalidateQueries({ queryKey: ['onboarding-status'] });
      navigate('/onboarding/route');
    },
    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({});
    createChannelMutation.mutate(formData);
  };

  const handleChange = (field: keyof ChannelRequest, value: string | number) => {
    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">Configure Your Channel</h1>
      <p className="text-gray-600">
        Set up a Lemmy community where articles will be posted
      </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-blue-500 text-white rounded-full flex items-center justify-center text-xs font-semibold">3</div>
        <div className="w-6 h-6 bg-gray-300 text-gray-600 rounded-full flex items-center justify-center text-xs font-semibold">4</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="name" className="block text-sm font-medium text-gray-700 mb-2">
            Community Name
          </label>
          <input 
            type="text" 
            id="name" 
            value={formData.name}
            onChange={(e) => handleChange('name', e.target.value)}
            placeholder="technology"
            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
          />
          <p className="text-sm text-gray-500 mt-1">Enter the community name (without the @ or instance)</p>
          {errors.name && (
            <p className="text-red-600 text-sm mt-1">{errors.name[0]}</p>
          )}
        </div>
        
        <div>
          <label htmlFor="platform_instance_id" className="block text-sm font-medium text-gray-700 mb-2">
            Platform Instance
          </label>
          <select 
            id="platform_instance_id" 
            value={formData.platform_instance_id}
            onChange={(e) => handleChange('platform_instance_id', parseInt(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 focus:border-transparent"
            required
          >
            <option value="">Select platform instance</option>
            {options?.platform_instances.filter(instance => instance.is_active).map((instance: PlatformInstance) => (
              <option key={instance.id} value={instance.id}>
                {instance.name} ({instance.url})
              </option>
            ))}
          </select>
          {errors.platform_instance_id && (
            <p className="text-red-600 text-sm mt-1">{errors.platform_instance_id[0]}</p>
          )}
        </div>
        
        <div>
          <label htmlFor="language_id" className="block text-sm font-medium text-gray-700 mb-2">
            Language
          </label>
          <select 
            id="language_id" 
            value={formData.language_id}
            onChange={(e) => handleChange('language_id', parseInt(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 focus:border-transparent"
            required
          >
            <option value="">Select language</option>
            {options?.languages.map((language: Language) => (
              <option key={language.id} value={language.id}>
                {language.name}
              </option>
            ))}
          </select>
          {errors.language_id && (
            <p className="text-red-600 text-sm mt-1">{errors.language_id[0]}</p>
          )}
        </div>
        
        <div>
          <label htmlFor="description" className="block text-sm font-medium text-gray-700 mb-2">
            Description (Optional)
          </label>
          <textarea 
            id="description" 
            rows={3}
            value={formData.description || ''}
            onChange={(e) => handleChange('description', e.target.value)}
            placeholder="Brief description of this channel"
            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"
          />
          {errors.description && (
            <p className="text-red-600 text-sm mt-1">{errors.description[0]}</p>
          )}
        </div>
        
        <div className="flex justify-between">
          <Link 
            to="/onboarding/feed"
            className="px-4 py-2 text-gray-600 hover:text-gray-800 transition duration-200"
          >
            ← Back
          </Link>
          <button 
            type="submit" 
            disabled={createChannelMutation.isPending}
            className="bg-blue-600 text-white py-2 px-6 rounded-md hover:bg-blue-700 transition duration-200 disabled:opacity-50"
          >
            {createChannelMutation.isPending ? 'Creating...' : 'Continue'}
          </button>
        </div>
      </form>
    </div>
  );
};

export default ChannelStep;