import React, { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { useAuth } from '../../hooks/useAuth';
import authService, { UpdateProfileRequest } from '../../services/auth';
import { SUPPORTED_LANGUAGES, COMMON_INDUSTRIES } from '../../utils/constants';
import { User, Globe, Briefcase, Save, CheckCircle, AlertCircle, Settings } from 'lucide-react';

interface ProfileFormData extends UpdateProfileRequest {}

const Profile: React.FC = () => {
  const { user, refreshUser } = useAuth();
  const [isLoading, setIsLoading] = useState(false);
  const [updateSuccess, setUpdateSuccess] = useState(false);
  const [updateError, setUpdateError] = useState<string | null>(null);
  const [profile, setProfile] = useState<any>(null);

  const {
    register,
    handleSubmit,
    setValue,
    formState: { errors, isDirty },
    reset,
  } = useForm<ProfileFormData>();

  // Load profile data on mount
  useEffect(() => {
    const loadProfile = async () => {
      try {
        const profileData = await authService.getProfile();
        setProfile(profileData);
        
        // Set form values
        setValue('name', profileData.user.name);
        setValue('preferred_language', profileData.profile?.preferred_language || '');
        setValue('default_industry', profileData.profile?.default_industry || '');
      } catch (error: any) {
        setUpdateError('Failed to load profile data');
      }
    };

    loadProfile();
  }, [setValue]);

  const onSubmit = async (data: ProfileFormData) => {
    setIsLoading(true);
    setUpdateError(null);
    setUpdateSuccess(false);

    try {
      const result = await authService.updateProfile(data);
      
      // Refresh user data in auth context
      refreshUser();
      
      // Show success message
      setUpdateSuccess(true);
      setTimeout(() => setUpdateSuccess(false), 3000);

      // Reset form dirty state
      reset(data);
      
    } catch (error: any) {
      setUpdateError(error.message || 'Failed to update profile');
    } finally {
      setIsLoading(false);
    }
  };

  if (!user) {
    return (
      <div className="min-h-96 flex items-center justify-center">
        <div className="text-white text-lg">Loading profile...</div>
      </div>
    );
  }

  return (
    <div className="space-y-8">
      {/* Header */}
      <div className="text-center text-white space-y-4">
        <div className="flex items-center justify-center space-x-3">
          <Settings className="h-12 w-12" />
          <h1 className="text-4xl md:text-5xl font-bold">Profile Settings</h1>
        </div>
        <p className="text-xl opacity-90 max-w-2xl mx-auto">
          Manage your account settings and preferences
        </p>
      </div>

      {/* Profile Form */}
      <div className="bg-white rounded-xl shadow-lg p-8">
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
          {/* Success/Error Messages */}
          {updateSuccess && (
            <div className="bg-green-50 border border-green-200 rounded-md p-4">
              <div className="flex items-center space-x-2 text-green-600">
                <CheckCircle className="h-5 w-5" />
                <span className="text-sm">Profile updated successfully!</span>
              </div>
            </div>
          )}

          {updateError && (
            <div className="bg-red-50 border border-red-200 rounded-md p-4">
              <div className="flex items-center space-x-2 text-red-600">
                <AlertCircle className="h-5 w-5" />
                <span className="text-sm">{updateError}</span>
              </div>
            </div>
          )}

          {/* Personal Information Section */}
          <div>
            <h3 className="text-lg font-semibold text-gray-800 mb-4 flex items-center space-x-2">
              <User className="h-5 w-5" />
              <span>Personal Information</span>
            </h3>
            
            <div className="grid md:grid-cols-2 gap-6">
              {/* Name Field */}
              <div>
                <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-2">
                  Full Name
                </label>
                <input
                  {...register('name', {
                    required: 'Name is required',
                    minLength: {
                      value: 2,
                      message: 'Name must be at least 2 characters long',
                    },
                    maxLength: {
                      value: 255,
                      message: 'Name must be less than 255 characters',
                    },
                  })}
                  type="text"
                  className="block w-full px-3 py-3 border border-gray-300 rounded-md focus:outline-none focus:ring-purple-500 focus:border-purple-500"
                  placeholder="Enter your full name"
                />
                {errors.name && (
                  <p className="mt-1 text-sm text-red-600">{errors.name.message}</p>
                )}
              </div>

              {/* Email Field (Read-only) */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Email Address
                </label>
                <input
                  type="email"
                  value={user.email}
                  disabled
                  className="block w-full px-3 py-3 border border-gray-300 rounded-md bg-gray-50 text-gray-500 cursor-not-allowed"
                />
                <p className="mt-1 text-xs text-gray-500">
                  Email cannot be changed. Contact support if you need to update your email.
                </p>
              </div>
            </div>
          </div>

          {/* Preferences Section */}
          <div className="border-t pt-6">
            <h3 className="text-lg font-semibold text-gray-800 mb-4 flex items-center space-x-2">
              <Globe className="h-5 w-5" />
              <span>Preferences</span>
            </h3>
            
            <div className="grid md:grid-cols-2 gap-6">
              {/* Preferred Language */}
              <div>
                <label htmlFor="preferred_language" className="block text-sm font-medium text-gray-700 mb-2">
                  Preferred Language
                </label>
                <select
                  {...register('preferred_language')}
                  className="block w-full px-3 py-3 border border-gray-300 rounded-md focus:outline-none focus:ring-purple-500 focus:border-purple-500"
                >
                  <option value="">Select language (optional)</option>
                  {SUPPORTED_LANGUAGES.map((lang) => (
                    <option key={lang.value} value={lang.value}>
                      {lang.label}
                    </option>
                  ))}
                </select>
              </div>

              {/* Default Industry */}
              <div>
                <label htmlFor="default_industry" className="block text-sm font-medium text-gray-700 mb-2">
                  Default Industry
                </label>
                <select
                  {...register('default_industry')}
                  className="block w-full px-3 py-3 border border-gray-300 rounded-md focus:outline-none focus:ring-purple-500 focus:border-purple-500"
                >
                  <option value="">Select industry (optional)</option>
                  {COMMON_INDUSTRIES.map((industry) => (
                    <option key={industry} value={industry}>
                      {industry}
                    </option>
                  ))}
                </select>
                <p className="mt-1 text-xs text-gray-500">
                  This will be pre-selected in the numerology calculator
                </p>
              </div>
            </div>
          </div>

          {/* Account Information Section */}
          <div className="border-t pt-6">
            <h3 className="text-lg font-semibold text-gray-800 mb-4">Account Information</h3>
            
            <div className="bg-gray-50 rounded-lg p-4 space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-gray-600">Member since:</span>
                <span className="text-gray-800">
                  {new Date(user.created_at).toLocaleDateString('en-US', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                  })}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-600">Last updated:</span>
                <span className="text-gray-800">
                  {new Date(user.updated_at).toLocaleDateString('en-US', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                  })}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-600">Account status:</span>
                <span className="text-green-600 font-medium">Active</span>
              </div>
            </div>
          </div>

          {/* Submit Button */}
          <div className="flex flex-col sm:flex-row gap-4 pt-6">
            <button
              type="submit"
              disabled={isLoading || !isDirty}
              className="flex-1 flex items-center justify-center space-x-2 py-3 px-6 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-purple-600 hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-purple-500 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-300"
            >
              {isLoading ? (
                <>
                  <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                  <span>Updating...</span>
                </>
              ) : (
                <>
                  <Save className="h-5 w-5" />
                  <span>{isDirty ? 'Save Changes' : 'No Changes'}</span>
                </>
              )}
            </button>
          </div>
        </form>
      </div>

      {/* Additional Settings */}
      <div className="bg-white rounded-xl shadow-lg p-8">
        <h3 className="text-lg font-semibold text-gray-800 mb-4">Additional Settings</h3>
        
        <div className="space-y-4">
          <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
            <div>
              <h4 className="font-medium text-gray-800">Password</h4>
              <p className="text-sm text-gray-600">Update your account password</p>
            </div>
            <button
              type="button"
              className="px-4 py-2 text-sm text-purple-600 border border-purple-600 rounded-md hover:bg-purple-50 transition-colors duration-300"
              onClick={() => alert('Password change functionality coming soon!')}
            >
              Change Password
            </button>
          </div>

          <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
            <div>
              <h4 className="font-medium text-gray-800">Data Export</h4>
              <p className="text-sm text-gray-600">Download all your numerology calculations</p>
            </div>
            <button
              type="button"
              className="px-4 py-2 text-sm text-blue-600 border border-blue-600 rounded-md hover:bg-blue-50 transition-colors duration-300"
              onClick={() => alert('Data export functionality coming soon!')}
            >
              Export Data
            </button>
          </div>

          <div className="flex items-center justify-between p-4 bg-red-50 rounded-lg border border-red-200">
            <div>
              <h4 className="font-medium text-red-800">Delete Account</h4>
              <p className="text-sm text-red-600">Permanently delete your account and all data</p>
            </div>
            <button
              type="button"
              className="px-4 py-2 text-sm text-red-600 border border-red-600 rounded-md hover:bg-red-100 transition-colors duration-300"
              onClick={() => alert('Account deletion requires contacting support.')}
            >
              Delete Account
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Profile;