"use client"

import { useEffect, useMemo, useState } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { useLocale, useTranslations } from 'next-intl'
import ProtectedRoute from '@/components/ProtectedRoute'
import Header from '@/components/Header'
import { Button } from '@/components/ui/button'
import { useAuth } from '@/contexts/AuthContext'
import { authFetch } from '@/lib/fetchAuth'
import {
  ArrowLeft,
  ArrowRight,
  ChevronLeft,
  ChevronRight,
  MapPin,
  User,
  Footprints,
  FileText,
} from 'lucide-react'
import {
  getSkinsForGender,
  getSkinPreviewUrl,
  getGenderFallbackAvatar,
  getCityName,
  getWalkName,
  WALK_STYLES,
  CITIES,
  CHARACTER_AGE_MIN,
  CHARACTER_AGE_MAX,
  BIOGRAPHY_MAX,
  MAX_CHARACTERS_PER_ACCOUNT,
} from '@/lib/characterCreation'

const fieldClassName =
  'w-full px-4 py-3 bg-[#0c1320]/80 border border-[#0087FF]/20 rounded-2xl text-white placeholder-gray-500 focus:outline-none focus:border-[#0087FF] focus:ring-0'

type Gender = 'male' | 'female'

export default function CreateCharacterPage() {
  const t = useTranslations('dashboard.createCharacter')
  const locale = useLocale() as 'es' | 'en'
  const router = useRouter()
  const { user } = useAuth()

  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [name, setName] = useState('')
  const [gender, setGender] = useState<Gender>('male')
  const [age, setAge] = useState(24)
  const [cityId, setCityId] = useState(1)
  const [walkStyle, setWalkStyle] = useState(263)
  const [skinIndex, setSkinIndex] = useState(0)
  const [biography, setBiography] = useState('')

  const skins = useMemo(() => getSkinsForGender(gender), [gender])
  const selectedSkin = skins[skinIndex] ?? skins[0]

  useEffect(() => {
    setSkinIndex(0)
  }, [gender])

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault()
    if (!user) return

    setLoading(true)
    setError(null)

    try {
      const response = await authFetch('/api/user/characters/create', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name,
          gender,
          age,
          cityId,
          walkStyle,
          skin: selectedSkin,
          biography,
        }),
      })
      const data = await response.json()
      if (!response.ok) {
        setError(data.error || t('errors.generic'))
        return
      }

      router.push(`/${locale}/dashboard?characterCreated=1`)
    } catch {
      setError(t('errors.network'))
    } finally {
      setLoading(false)
    }
  }

  const shiftSkin = (direction: -1 | 1) => {
    setSkinIndex((current) => {
      const next = current + direction
      if (next < 0) return skins.length - 1
      if (next >= skins.length) return 0
      return next
    })
  }

  return (
    <ProtectedRoute>
      <div className="min-h-screen bg-gradient-to-b from-[#0b1220] via-[#0a1020] to-[#070b15]">
        <Header />
        <main className="container mx-auto px-4 py-10 max-w-5xl">
          <div className="mb-8">
            <Link
              href={`/${locale}/dashboard`}
              className="inline-flex items-center gap-2 text-sm text-[#8ab4ff] hover:text-white transition-colors"
            >
              <ArrowLeft className="w-4 h-4" />
              {t('back')}
            </Link>
            <h1 className="text-3xl font-bold text-white mt-4">{t('title')}</h1>
            <p className="text-gray-400 mt-2">{t('subtitle')}</p>
          </div>

          <form
            onSubmit={handleSubmit}
            className="grid grid-cols-1 lg:grid-cols-[320px_1fr] gap-6"
          >
            <section className="bg-[#0f1620]/70 backdrop-blur-sm rounded-2xl border border-[#0087FF]/20 p-6">
              <p className="text-sm font-medium text-gray-300 mb-4">{t('skinPreview')}</p>
              <div className="relative aspect-[3/4] rounded-2xl overflow-hidden bg-[#0c1320] border border-[#0087FF]/20 flex items-end justify-center">
                <img
                  src={getSkinPreviewUrl(selectedSkin)}
                  alt={t('skinAlt', { id: selectedSkin })}
                  className="max-h-full object-contain"
                  onError={(event) => {
                    event.currentTarget.src = getGenderFallbackAvatar(gender)
                  }}
                />
              </div>
              <div className="flex items-center justify-between mt-4">
                <button
                  type="button"
                  onClick={() => shiftSkin(-1)}
                  className="w-10 h-10 rounded-xl border border-[#0087FF]/20 text-[#8ab4ff] hover:bg-[#0087FF]/10"
                  aria-label={t('previousSkin')}
                >
                  <ChevronLeft className="w-5 h-5 mx-auto" />
                </button>
                <div className="text-center">
                  <p className="text-white font-semibold">{t('skinLabel', { id: selectedSkin })}</p>
                  <p className="text-xs text-gray-400">{skinIndex + 1}/{skins.length}</p>
                </div>
                <button
                  type="button"
                  onClick={() => shiftSkin(1)}
                  className="w-10 h-10 rounded-xl border border-[#0087FF]/20 text-[#8ab4ff] hover:bg-[#0087FF]/10"
                  aria-label={t('nextSkin')}
                >
                  <ChevronRight className="w-5 h-5 mx-auto" />
                </button>
              </div>
            </section>

            <section className="bg-[#0f1620]/70 backdrop-blur-sm rounded-2xl border border-[#0087FF]/20 p-6 space-y-5">
              {error && (
                <div className="p-3 rounded-xl bg-red-500/10 border border-red-500/30 text-red-300 text-sm">
                  {error}
                </div>
              )}

              <Field label={t('name.label')} hint={t('name.hint')}>
                <input
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder={t('name.placeholder')}
                  className={fieldClassName}
                  required
                  maxLength={24}
                />
              </Field>

              <Field label={t('gender.label')}>
                <div className="grid grid-cols-2 gap-3">
                  {(['male', 'female'] as Gender[]).map((option) => (
                    <button
                      key={option}
                      type="button"
                      onClick={() => setGender(option)}
                      className={`rounded-xl border px-4 py-3 text-sm font-medium transition-colors ${
                        gender === option
                          ? 'border-[#0087FF] bg-[#0087FF]/15 text-white'
                          : 'border-[#0087FF]/20 text-gray-400 hover:text-white hover:border-[#0087FF]/40'
                      }`}
                    >
                      {option === 'male' ? t('gender.male') : t('gender.female')}
                    </button>
                  ))}
                </div>
              </Field>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                <Field label={t('age.label')} icon={User}>
                  <input
                    type="number"
                    min={CHARACTER_AGE_MIN}
                    max={CHARACTER_AGE_MAX}
                    value={age}
                    onChange={(e) => setAge(Number(e.target.value))}
                    className={fieldClassName}
                    required
                  />
                </Field>

                <Field label={t('city.label')} icon={MapPin}>
                  <select
                    value={cityId}
                    onChange={(e) => setCityId(Number(e.target.value))}
                    className={fieldClassName}
                  >
                    {CITIES.map((city) => (
                      <option key={city.id} value={city.id}>
                        {city.name[locale]}
                      </option>
                    ))}
                  </select>
                </Field>
              </div>

              <Field label={t('walk.label')} icon={Footprints}>
                <select
                  value={walkStyle}
                  onChange={(e) => setWalkStyle(Number(e.target.value))}
                  className={fieldClassName}
                >
                  {WALK_STYLES.map((walk) => (
                    <option key={walk.id} value={walk.id}>
                      {walk.name[locale]}
                    </option>
                  ))}
                </select>
              </Field>

              <Field label={t('bio.label')} icon={FileText}>
                <textarea
                  value={biography}
                  onChange={(e) => setBiography(e.target.value)}
                  placeholder={t('bio.placeholder')}
                  maxLength={BIOGRAPHY_MAX}
                  rows={4}
                  className={`${fieldClassName} resize-none`}
                />
                <p className="text-xs text-gray-500 mt-2 text-right">
                  {biography.length}/{BIOGRAPHY_MAX}
                </p>
              </Field>

              <div className="rounded-xl border border-[#0087FF]/15 bg-[#0c1320]/60 p-4 grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
                <SummaryItem label={t('summary.skin')} value={t('skinLabel', { id: selectedSkin })} />
                <SummaryItem label={t('summary.age')} value={String(age)} />
                <SummaryItem label={t('summary.city')} value={getCityName(cityId, locale)} />
                <SummaryItem label={t('summary.walk')} value={getWalkName(walkStyle, locale)} />
              </div>

              <Button
                type="submit"
                disabled={loading}
                className="w-full bg-gradient-to-r from-[#0087FF] to-[#8ab4ff] text-white hover:from-[#0066CC] hover:to-[#6a9eff] rounded-full px-4 py-3 text-sm font-semibold shadow-lg shadow-[#0087FF]/20"
              >
                <span className="inline-flex items-center justify-center gap-2">
                  {loading ? t('creating') : t('submit')}
                  {!loading && <ArrowRight className="w-4 h-4" />}
                </span>
              </Button>

              <p className="text-xs text-gray-500 text-center">
                {t('limitHint', { max: MAX_CHARACTERS_PER_ACCOUNT })}
              </p>
            </section>
          </form>
        </main>
      </div>
    </ProtectedRoute>
  )
}

function Field({
  label,
  hint,
  icon: Icon,
  children,
}: {
  label: string
  hint?: string
  icon?: React.ComponentType<{ className?: string }>
  children: React.ReactNode
}) {
  return (
    <div className="space-y-2">
      <div className="flex items-center gap-2">
        {Icon && <Icon className="w-4 h-4 text-[#8ab4ff]" />}
        <label className="text-sm font-medium text-gray-300">{label}</label>
      </div>
      {hint && <p className="text-xs text-gray-500">{hint}</p>}
      {children}
    </div>
  )
}

function SummaryItem({ label, value }: { label: string; value: string }) {
  return (
    <div>
      <p className="text-gray-500">{label}</p>
      <p className="text-white font-medium">{value}</p>
    </div>
  )
}
