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

const PlatformStep: React.FC = () => {
  const navigate = useNavigate();
  const [formData, setFormData] = useState<PlatformAccountRequest>({
    instance_url: '',
    username: '',
    password: '',
    platform: 'lemmy'
  });
  const [errors, setErrors] = useState<Record<string, string[]>>({});

  const createPlatformMutation = useMutation({
    mutationFn: (data: PlatformAccountRequest) => apiClient.createPlatformAccount(data),
    onSuccess: () => {
      navigate('/onboarding/feed');
    },
    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({});
    createPlatformMutation.mutate(formData);
  };

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

  return (
    <div className="text-center mb-8">
      <h1 className="text-2xl font-bold text-gray-900 mb-2">Connect Your Lemmy Account</h1>
      <p className="text-gray-600">
        Enter your Lemmy instance details and login credentials
      </p>
      
      {/* Progress indicator */}
      <div className="flex justify-center mt-6 space-x-2">
        <div className="w-6 h-6 bg-blue-500 text-white rounded-full flex items-center justify-center text-xs font-semibold">1</div>
        <div className="w-6 h-6 bg-gray-300 text-gray-600 rounded-full flex items-center justify-center text-xs font-semibold">2</div>
        <div className="w-6 h-6 bg-gray-300 text-gray-600 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="instance_url" className="block text-sm font-medium text-gray-700 mb-2">
            Lemmy Instance URL
          </label>
          <input 
            type="url" 
            id="instance_url" 
            value={formData.instance_url}
            onChange={(e) => handleChange('instance_url', e.target.value)}
            placeholder="https://lemmy.world"
            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
          />
          {errors.instance_url && (
            <p className="text-red-600 text-sm mt-1">{errors.instance_url[0]}</p>
          )}
        </div>
        
        <div>
          <label htmlFor="username" className="block text-sm font-medium text-gray-700 mb-2">
            Username
          </label>
          <input 
            type="text" 
            id="username" 
            value={formData.username}
            onChange={(e) => handleChange('username', 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
          />
          {errors.username && (
            <p className="text-red-600 text-sm mt-1">{errors.username[0]}</p>
          )}
        </div>
        
        <div>
          <label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-2">
            Password
          </label>
          <input 
            type="password" 
            id="password" 
            value={formData.password}
            onChange={(e) => handleChange('password', 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
          />
          {errors.password && (
            <p className="text-red-600 text-sm mt-1">{errors.password[0]}</p>
          )}
        </div>
        
        <div className="flex justify-between">
          <Link 
            to="/onboarding"
            className="px-4 py-2 text-gray-600 hover:text-gray-800 transition duration-200"
          >
            ← Back
          </Link>
          <button 
            type="submit" 
            disabled={createPlatformMutation.isPending}
            className="bg-blue-600 text-white py-2 px-6 rounded-md hover:bg-blue-700 transition duration-200 disabled:opacity-50"
          >
            {createPlatformMutation.isPending ? 'Connecting...' : 'Continue'}
          </button>
        </div>
      </form>
    </div>
  );
};

export default PlatformStep;