import React, { useState } from 'react'
import { ArrowLeft } from 'lucide-react'
import { supabase } from '../lib/supabaseClient'
import { useTranslation } from '../i18n/LanguageContext'

export default function AuthPanel({ onAuth, themeToggle, onBack }) {
  const t = useTranslation()
  const [mode, setMode] = useState('login')
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [message, setMessage] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  const handleSubmit = async (event) => {
    event.preventDefault()
    if (!supabase) return

    setLoading(true)
    setError('')
    setMessage('')

    try {
      if (mode === 'login') {
        const { data, error: signInError } = await supabase.auth.signInWithPassword({
          email,
          password
        })
        if (signInError) {
          setError(signInError.message)
        } else {
          setMessage(t('auth.login_success'))
          onAuth?.(data.session)
        }
      } else {
        const { data, error: signUpError } = await supabase.auth.signUp({
          email,
          password
        })
        if (signUpError) {
          setError(signUpError.message)
        } else if (!data.session) {
          setMessage(t('auth.register_success'))
        } else {
          onAuth?.(data.session)
        }
      }
    } catch (err) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-sky-100 via-blue-50 to-emerald-100 dark:from-gray-950 dark:via-gray-900 dark:to-gray-950 flex items-center justify-center p-6 text-gray-900 dark:text-gray-100">
      <div className="absolute top-4 left-4 flex items-center gap-3">
        {onBack && (
          <button
            type="button"
            onClick={onBack}
            className="inline-flex items-center gap-2 rounded-full border border-gray-200/70 bg-white/70 px-3 py-2 text-sm font-medium text-gray-800 shadow-sm backdrop-blur transition hover:-translate-y-[1px] hover:shadow-md dark:border-gray-800 dark:bg-gray-900/70 dark:text-gray-100"
          >
            <ArrowLeft className="h-4 w-4" />
            {t('auth.back')}
          </button>
        )}
      </div>
      <div className="absolute top-4 right-4">{themeToggle}</div>
      <div className="w-full max-w-lg bg-white/90 dark:bg-gray-900/80 backdrop-blur rounded-2xl shadow-xl border border-white/70 dark:border-gray-800">
        <div className="px-8 py-6 border-b border-gray-100 dark:border-gray-800">
          <p className="text-sm uppercase tracking-wide text-indigo-600 dark:text-indigo-300 font-semibold">{t('auth.title')}</p>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-gray-100 mt-1">{t('auth.subtitle')}</h1>
          <p className="text-gray-600 dark:text-gray-300 mt-2">
            {t('auth.description')}
          </p>
        </div>

        <form onSubmit={handleSubmit} className="px-8 py-6 space-y-4">
          <div className="flex items-center gap-2 text-sm font-medium">
            <button
              type="button"
              onClick={() => setMode('login')}
              className={`px-4 py-2 rounded-full transition ${mode === 'login' ? 'bg-indigo-600 text-white' : 'text-gray-600 dark:text-gray-300 hover:bg-indigo-50 dark:hover:bg-indigo-900/40'}`}
            >
              {t('auth.login_tab')}
            </button>
            <button
              type="button"
              onClick={() => setMode('register')}
              className={`px-4 py-2 rounded-full transition ${mode === 'register' ? 'bg-emerald-600 text-white' : 'text-gray-600 dark:text-gray-300 hover:bg-emerald-50 dark:hover:bg-emerald-900/40'}`}
            >
              {t('auth.register_tab')}
            </button>
          </div>

          <label className="block">
            <span className="text-sm font-semibold text-gray-700 dark:text-gray-200">{t('auth.email')}</span>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
              className="mt-1 w-full px-4 py-3 rounded-lg border border-gray-200 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 bg-white dark:bg-gray-800 dark:text-gray-100"
              placeholder="you@example.com"
            />
          </label>

          <label className="block">
            <span className="text-sm font-semibold text-gray-700 dark:text-gray-200">{t('auth.password')}</span>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
              className="mt-1 w-full px-4 py-3 rounded-lg border border-gray-200 dark:border-gray-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 bg-white dark:bg-gray-800 dark:text-gray-100"
              placeholder="••••••••"
            />
          </label>

          {error && (
            <div className="p-3 rounded-lg bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 text-red-700 dark:text-red-200 text-sm">
              {error}
            </div>
          )}

          {message && (
            <div className="p-3 rounded-lg bg-emerald-50 dark:bg-emerald-900/30 border border-emerald-200 dark:border-emerald-800 text-emerald-700 dark:text-emerald-200 text-sm">
              {message}
            </div>
          )}

          <button
            type="submit"
            disabled={loading}
            className="w-full py-3 rounded-lg font-semibold text-white bg-gradient-to-r from-indigo-600 to-emerald-600 shadow-md hover:shadow-lg transition disabled:opacity-60 disabled:cursor-not-allowed"
          >
            {loading ? t('auth.sending') : mode === 'login' ? t('auth.login_btn') : t('auth.register_btn')}
          </button>
        </form>
      </div>
    </div>
  )
}
