'use client'

import { useState } from 'react'
import { updateProfile, updatePassword } from '@/actions/auth'
import { updatePreferences, type UserPreferences, type Language } from '@/actions/preferences'

type SettingsFormProps = {
  user: { id: string; name: string | null; email: string }
  preferences: UserPreferences
  languages: Language[]
}

export default function SettingsForm({ user, preferences, languages }: SettingsFormProps) {
  // Profile state
  const [name, setName] = useState(user.name || '')
  const [email, setEmail] = useState(user.email)
  const [profileMessage, setProfileMessage] = useState('')
  const [profileLoading, setProfileLoading] = useState(false)

  // Password state
  const [currentPassword, setCurrentPassword] = useState('')
  const [newPassword, setNewPassword] = useState('')
  const [passwordMessage, setPasswordMessage] = useState('')
  const [passwordLoading, setPasswordLoading] = useState(false)

  // Preferences state
  const [prefs, setPrefs] = useState(preferences)
  const [prefsMessage, setPrefsMessage] = useState('')
  const [prefsLoading, setPrefsLoading] = useState(false)

  const handleProfileSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setProfileMessage('')
    setProfileLoading(true)

    try {
      const result = await updateProfile(name, email)
      setProfileMessage(result.message || (result.success ? 'Profile updated' : 'Update failed'))
    } catch (err) {
      setProfileMessage('An error occurred')
    } finally {
      setProfileLoading(false)
    }
  }

  const handlePasswordSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setPasswordMessage('')
    setPasswordLoading(true)

    try {
      const result = await updatePassword(currentPassword, newPassword)
      if (result.success) {
        setCurrentPassword('')
        setNewPassword('')
      }
      setPasswordMessage(result.message || (result.success ? 'Password updated' : 'Update failed'))
    } catch (err) {
      setPasswordMessage('An error occurred')
    } finally {
      setPasswordLoading(false)
    }
  }

  const handlePreferencesSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setPrefsMessage('')
    setPrefsLoading(true)

    try {
      const result = await updatePreferences(prefs)
      setPrefsMessage(result.message || (result.success ? 'Preferences updated' : 'Update failed'))
    } catch (err) {
      setPrefsMessage('An error occurred')
    } finally {
      setPrefsLoading(false)
    }
  }

  return (
    <div className="space-y-8">
      {/* Profile Section */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
        <h3 className="text-xl font-semibold text-gray-900 dark:text-white mb-4">
          Profile
        </h3>
        <form onSubmit={handleProfileSubmit} className="space-y-4">
          {profileMessage && (
            <div className={`px-4 py-3 rounded ${
              profileMessage.includes('success') || profileMessage.includes('updated')
                ? 'bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 text-green-700 dark:text-green-400'
                : 'bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 text-red-700 dark:text-red-400'
            }`}>
              {profileMessage}
            </div>
          )}

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Name
            </label>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 dark:text-white"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Email
            </label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 dark:text-white"
            />
          </div>

          <button
            type="submit"
            disabled={profileLoading}
            className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
          >
            {profileLoading ? 'Saving...' : 'Save Profile'}
          </button>
        </form>
      </div>

      {/* Password Section */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
        <h3 className="text-xl font-semibold text-gray-900 dark:text-white mb-4">
          Change Password
        </h3>
        <form onSubmit={handlePasswordSubmit} className="space-y-4">
          {passwordMessage && (
            <div className={`px-4 py-3 rounded ${
              passwordMessage.includes('success') || passwordMessage.includes('updated')
                ? 'bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 text-green-700 dark:text-green-400'
                : 'bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 text-red-700 dark:text-red-400'
            }`}>
              {passwordMessage}
            </div>
          )}

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Current Password
            </label>
            <input
              type="password"
              value={currentPassword}
              onChange={(e) => setCurrentPassword(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 dark:text-white"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              New Password
            </label>
            <input
              type="password"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              minLength={6}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 dark:text-white"
            />
          </div>

          <button
            type="submit"
            disabled={passwordLoading}
            className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
          >
            {passwordLoading ? 'Updating...' : 'Update Password'}
          </button>
        </form>
      </div>

      {/* Learning Preferences Section */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
        <h3 className="text-xl font-semibold text-gray-900 dark:text-white mb-4">
          Learning Preferences
        </h3>
        <form onSubmit={handlePreferencesSubmit} className="space-y-4">
          {prefsMessage && (
            <div className={`px-4 py-3 rounded ${
              prefsMessage.includes('success') || prefsMessage.includes('updated')
                ? 'bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 text-green-700 dark:text-green-400'
                : 'bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 text-red-700 dark:text-red-400'
            }`}>
              {prefsMessage}
            </div>
          )}

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Preferred Language
            </label>
            <select
              value={prefs.preferredLanguageId}
              onChange={(e) => setPrefs({ ...prefs, preferredLanguageId: e.target.value })}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 dark:text-white"
            >
              {languages.map((lang) => (
                <option key={lang.id} value={lang.id}>
                  {lang.name} ({lang.nativeName})
                </option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Character Display
            </label>
            <select
              value={prefs.characterDisplay}
              onChange={(e) => setPrefs({ ...prefs, characterDisplay: e.target.value as any })}
              className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 dark:text-white"
            >
              <option value="SIMPLIFIED">Simplified</option>
              <option value="TRADITIONAL">Traditional</option>
              <option value="BOTH">Both</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Cards Per Session: {prefs.cardsPerSession}
            </label>
            <input
              type="range"
              min="5"
              max="100"
              value={prefs.cardsPerSession}
              onChange={(e) => setPrefs({ ...prefs, cardsPerSession: parseInt(e.target.value) })}
              className="w-full"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Daily Goal: {prefs.dailyGoal} cards
            </label>
            <input
              type="range"
              min="10"
              max="500"
              step="10"
              value={prefs.dailyGoal}
              onChange={(e) => setPrefs({ ...prefs, dailyGoal: parseInt(e.target.value) })}
              className="w-full"
            />
          </div>

          <div className="flex items-center">
            <input
              type="checkbox"
              id="allowManualDifficulty"
              checked={prefs.allowManualDifficulty}
              onChange={(e) => setPrefs({ ...prefs, allowManualDifficulty: e.target.checked })}
              className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
            />
            <label htmlFor="allowManualDifficulty" className="ml-2 block text-sm text-gray-700 dark:text-gray-300">
              Allow manual difficulty adjustment
            </label>
          </div>

          <button
            type="submit"
            disabled={prefsLoading}
            className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
          >
            {prefsLoading ? 'Saving...' : 'Save Preferences'}
          </button>
        </form>
      </div>
    </div>
  )
}
