import React, { useState, useEffect, useContext } from 'react'
import { useNavigate } from 'react-router-dom'
import api from '../api'
import { AuthContext } from '../context/AuthContext'
import Toast from '../components/Toast'
import '../styles/global.css'

export default function Profile() {
  const navigate = useNavigate()
  const { token, user, setUser } = useContext(AuthContext)
  const [formData, setFormData] = useState({
    full_name: '',
    email: '',
    phone: '',
    address: '',
    city: '',
    postal_code: '',
    country: '',
  })
  const [passwordData, setPasswordData] = useState({
    old_password: '',
    new_password: '',
    confirm_password: '',
  })
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [changingPassword, setChangingPassword] = useState(false)
  const [toast, setToast] = useState(null)

  useEffect(() => {
    if (!token) {
      navigate('/login')
    } else {
      fetchProfile()
    }
  }, [token, navigate])

  const fetchProfile = async () => {
    try {
      const response = await api.get('/users/me')
      setFormData(response.data)
      setUser(response.data)
    } catch (error) {
      console.error('Error fetching profile:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value,
    })
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    setSaving(true)

    try {
      const response = await api.put('/users/me', formData)
      setUser(response.data)
      setToast({ type: 'success', message: 'Profile updated successfully!' })
    } catch (error) {
      console.error('Error updating profile:', error)
      setToast({ type: 'error', message: error.response?.data?.detail || 'Error updating profile. Please try again.' })
    } finally {
      setSaving(false)
    }
  }

  const handlePasswordChange = async (e) => {
    e.preventDefault()
    
    if (passwordData.new_password !== passwordData.confirm_password) {
      setToast({ type: 'error', message: 'New passwords do not match!' })
      return
    }

    if (passwordData.new_password.length < 6) {
      setToast({ type: 'error', message: 'Password must be at least 6 characters!' })
      return
    }

    setChangingPassword(true)
    try {
      await api.post('/auth/change-password', {
        old_password: passwordData.old_password,
        new_password: passwordData.new_password,
      })
      setToast({ type: 'success', message: 'Password changed successfully!' })
      setPasswordData({ old_password: '', new_password: '', confirm_password: '' })
    } catch (error) {
      console.error('Error changing password:', error)
      setToast({ type: 'error', message: error.response?.data?.detail || 'Error changing password. Please try again.' })
    } finally {
      setChangingPassword(false)
    }
  }

  if (loading) return <div className="loading">Loading...</div>

  return (
    <div className="profile-page">
      <div style={{ display: 'flex', alignItems: 'center', gap: '1rem', marginBottom: '1rem' }}>
        <h1>My Profile</h1>
        {user?.is_admin && (
          <span style={{ 
            backgroundColor: '#ff6b6b', 
            color: 'white', 
            padding: '0.25rem 0.75rem', 
            borderRadius: '4px', 
            fontSize: '0.875rem',
            fontWeight: 'bold' 
          }}>
            ADMIN
          </span>
        )}
      </div>

      <div className="profile-container">
        <form onSubmit={handleSubmit} className="profile-form">
          <h2>Personal Information</h2>

          <div className="form-group">
            <label>Full Name</label>
            <input
              type="text"
              name="full_name"
              value={formData.full_name}
              onChange={handleChange}
            />
          </div>

          <div className="form-group">
            <label>Email</label>
            <input
              type="email"
              name="email"
              value={formData.email}
              onChange={handleChange}
              required
            />
          </div>

          <div className="form-group">
            <label>Phone</label>
            <input
              type="tel"
              name="phone"
              value={formData.phone || ''}
              onChange={handleChange}
            />
          </div>

          <h2>Shipping Address</h2>

          <div className="form-group">
            <label>Address</label>
            <input
              type="text"
              name="address"
              value={formData.address || ''}
              onChange={handleChange}
            />
          </div>

          <div className="form-row">
            <div className="form-group">
              <label>City</label>
              <input
                type="text"
                name="city"
                value={formData.city || ''}
                onChange={handleChange}
              />
            </div>

            <div className="form-group">
              <label>Postal Code</label>
              <input
                type="text"
                name="postal_code"
                value={formData.postal_code || ''}
                onChange={handleChange}
              />
            </div>

            <div className="form-group">
              <label>Country</label>
              <input
                type="text"
                name="country"
                value={formData.country || ''}
                onChange={handleChange}
              />
            </div>
          </div>

          <button type="submit" className="btn btn-full" disabled={saving}>
            {saving ? 'Saving...' : 'Save Changes'}
          </button>
        </form>

        <form onSubmit={handlePasswordChange} className="profile-form" style={{ marginTop: '2rem' }}>
          <h2>Change Password</h2>

          <div className="form-group">
            <label>Current Password</label>
            <input
              type="password"
              value={passwordData.old_password}
              onChange={(e) => setPasswordData({ ...passwordData, old_password: e.target.value })}
              required
            />
          </div>

          <div className="form-group">
            <label>New Password</label>
            <input
              type="password"
              value={passwordData.new_password}
              onChange={(e) => setPasswordData({ ...passwordData, new_password: e.target.value })}
              minLength="6"
              required
            />
          </div>

          <div className="form-group">
            <label>Confirm New Password</label>
            <input
              type="password"
              value={passwordData.confirm_password}
              onChange={(e) => setPasswordData({ ...passwordData, confirm_password: e.target.value })}
              minLength="6"
              required
            />
          </div>

          <button type="submit" className="btn btn-full" disabled={changingPassword}>
            {changingPassword ? 'Changing...' : 'Change Password'}
          </button>
        </form>
      </div>
      
      {toast && (
        <Toast
          message={toast.message}
          type={toast.type}
          onClose={() => setToast(null)}
        />
      )}
    </div>
  )
}
