"use client"

import { useState, useEffect } from 'react'
import { createPortal } from 'react-dom'
import { useTranslations } from 'next-intl'
import { Home, Hash, MapPin, CheckCircle, Circle, AlertCircle, Building2, User, DoorOpen } from 'lucide-react'
import { authFetch } from '@/lib/fetchAuth'

interface CharacterBrief {
	id: number
	name: string
}

interface Interior {
	id: number
	owner: string // character name like Ivan_Sanchez
	posX: number | null
	posY: number | null
	posZ: number | null
	type: string | number | null
	wardrobe: number // 0/1
}

interface PlayerInteriorsProps {
	characters?: CharacterBrief[]
}

export default function PlayerInteriors({ characters = [] }: PlayerInteriorsProps) {
	const t = useTranslations('interiors')
	const [interiors, setInteriors] = useState<Interior[]>([])
	const [loading, setLoading] = useState(true)
	const [error, setError] = useState<string | null>(null)
	const [selected, setSelected] = useState<Interior | null>(null)

	useEffect(() => {
		fetchInteriorsByCharacters()
	// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [characters.map(c => c.name).join('|')])

	const fetchInteriorsByCharacters = async () => {
		try {
			setLoading(true)
			const all: Interior[] = []
			for (const c of characters) {
				const owner = c.name
				const res = await authFetch(`/api/user/character-interiors?owner=${encodeURIComponent(owner)}`)
				if (!res.ok) continue
				const data = await res.json()
				const mapped: Interior[] = (data.interiors || []).map((r: any) => ({
					id: Number(r.id),
					owner: String(r.owner),
					posX: r.posX != null ? Number(r.posX) : null,
					posY: r.posY != null ? Number(r.posY) : null,
					posZ: r.posZ != null ? Number(r.posZ) : null,
					type: r.type ?? null,
					wardrobe: Number(r.wardrobe ?? 0),
				}))
				all.push(...mapped)
			}
			setInteriors(all)
		} catch (e) {
			console.error('Error fetching character interiors', e)
			setError(t('error'))
		} finally {
			setLoading(false)
		}
	}

	const getWardrobeColor = (w: number) => (w === 1 ? 'text-emerald-400' : 'text-red-400')
	const getWardrobeIcon = (w: number) => (w === 1 ? <CheckCircle className="w-4 h-4 text-emerald-400" /> : <AlertCircle className="w-4 h-4 text-red-400" />)

	if (loading) {
		return (
			<div className="bg-gradient-to-br from-[#0b1422]/90 to-[#0a1120]/90 border border-[#0090ff]/15 rounded-2xl p-4 backdrop-blur-md shadow-[0_0_30px_-12px_rgba(0,135,255,0.35)]">
				<div className="text-center">
					<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-[#53b1ff] mx-auto mb-3"></div>
					<p className="text-[#b8d8ff] text-sm">{t('loading')}</p>
				</div>
			</div>
		)
	}

	if (error) {
		return (
			<div className="bg-gradient-to-br from-[#1a0f14]/90 to-[#160d12]/90 border border-rose-500/30 rounded-2xl p-4 backdrop-blur-md">
				<div className="text-center">
					<p className="text-rose-300 mb-2 text-sm">{error}</p>
					<button onClick={fetchInteriorsByCharacters} className="text-xs text-[#a9c7ff] hover:text-white transition-colors">{t('tryAgain')}</button>
				</div>
			</div>
		)
	}

	if (interiors.length === 0) {
		return (
			<div className="bg-gradient-to-br from-[#0b1422]/90 to-[#0a1120]/90 border border-[#0090ff]/15 rounded-2xl p-4 backdrop-blur-md">
				<div className="text-center">
					<div className="w-12 h-12 bg-[#0e223f]/60 rounded-2xl flex items-center justify-center mx-auto mb-3 border border-[#1c3e6e]/50">
						<Building2 className="w-6 h-6 text-[#94c2ff]" />
					</div>
					<h3 className="text-lg font-semibold text-white mb-2">{t('noInteriors')}</h3>
					<p className="text-[#9cbdf5] text-sm">{t('noInteriorsDesc')}</p>
				</div>
			</div>
		)
	}

	const InteriorCard = ({ interior, onClick }: { interior: Interior, onClick: () => void }) => (
		<button
			type="button"
			onClick={onClick}
			className="group relative bg-gradient-to-br from-[#0f1620] to-[#0c1320] rounded-2xl p-5 border border-[#0087FF]/20 hover:border-[#0087FF]/40 transition-all duration-300 hover:shadow-xl hover:shadow-[#0087FF]/20 hover:-translate-y-0.5 focus:outline-none focus:ring-2 focus:ring-[#0087FF]/40 w-full text-left"
			aria-label={`Open interior ${interior.id}`}
		>
			<div className="flex items-center gap-4">
				<div className="w-12 h-12 rounded-2xl bg-[#0e223f]/40 border-2 border-[#0087FF]/30 flex items-center justify-center group-hover:border-[#8ab4ff] transition-all">
					<Home className="w-6 h-6 text-[#bcd7ff]" />
				</div>
				<div className="min-w-0">
					<h4 className="text-lg font-bold text-white truncate group-hover:text-[#8ab4ff] transition-colors">Interior #{interior.id}</h4>
					<p className="text-xs text-gray-400 flex items-center gap-1"><Hash className="w-3 h-3" /> ID {interior.id}</p>
					{interior.owner ? (
						<p className="text-[11px] text-gray-400 mt-0.5 inline-flex items-center gap-1"><User className="w-3 h-3" /> {interior.owner.replace(/_/g, ' ')}</p>
					) : null}
				</div>
			</div>
			<div className="absolute inset-0 rounded-2xl bg-gradient-to-br from-[#0087FF]/5 to-transparent opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none" />
		</button>
	)

	const InteriorDetailModal = ({ interior, onClose }: { interior: Interior, onClose: () => void }) => (
		<div className="relative bg-gradient-to-br from-slate-800 to-slate-900 rounded-3xl border border-slate-700 p-6 md:p-8 max-w-3xl w-full max-h-[90vh] overflow-y-auto animate-slide-in">
			<button
				onClick={onClose}
				className="absolute top-4 right-4 p-2 text-gray-400 hover:text-white hover:bg-slate-700 rounded-xl transition-colors"
				aria-label="Close"
			>
				×
			</button>
			<div className="flex items-start gap-4 md:gap-6 mb-6">
				<div className="w-16 h-16 rounded-2xl bg-[#0e223f]/40 border-2 border-[#0087FF]/30 flex items-center justify-center">
					<Home className="w-8 h-8 text-[#bcd7ff]" />
				</div>
				<div className="min-w-0 flex-1">
					<h2 className="text-2xl md:text-3xl font-bold text-white mb-1 truncate">Interior #{interior.id}</h2>
					<div className="flex items-center gap-3 text-xs text-gray-300 flex-wrap">
						<span className="inline-flex items-center gap-1"><Hash className="w-3 h-3" /> ID #{interior.id}</span>
						{interior.owner ? <span className="inline-flex items-center gap-1"><User className="w-3 h-3" /> {interior.owner.replace(/_/g,' ')}</span> : null}
					</div>
				</div>
			</div>

			<div className="grid grid-cols-1 sm:grid-cols-3 gap-3 mb-6">
				<div className="rounded-xl border border-slate-600 bg-slate-700/40 p-4">
					<p className="text-sm text-gray-300 mb-1">{t('details.type')}</p>
					<p className="text-2xl font-bold text-white">{interior.type ?? '—'}</p>
				</div>
				<div className="rounded-xl border border-slate-600 bg-slate-700/40 p-4">
					<p className="text-sm text-gray-300 mb-1">{t('details.wardrobe')}</p>
					<p className={`text-2xl font-bold ${getWardrobeColor(interior.wardrobe)}`}>{interior.wardrobe === 1 ? t('details.yes') : t('details.no')}</p>
				</div>
				<div className="rounded-xl border border-slate-600 bg-slate-700/40 p-4">
					<p className="text-sm text-gray-300 mb-1">{t('details.owner')}</p>
					<p className="text-2xl font-bold text-emerald-400">{interior.owner ? interior.owner.replace(/_/g,' ') : '—'}</p>
				</div>
			</div>

			<div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
				<div>
					<div className="flex items-center justify-between text-sm text-gray-300 mb-2">
						<span className="inline-flex items-center gap-2"><MapPin className="w-4 h-4 text-blue-300" /> {t('details.position')}</span>
						<span className="text-white font-semibold">{typeof interior.posX === 'number' && typeof interior.posY === 'number' && typeof interior.posZ === 'number' ? `${interior.posX.toFixed(2)}, ${interior.posY.toFixed(2)}, ${interior.posZ.toFixed(2)}` : '—'}</span>
					</div>
					<div className="h-2 rounded-full bg-slate-700 overflow-hidden">
						<div className="h-full bg-gradient-to-r from-blue-500 to-cyan-400" style={{ width: '100%' }}></div>
					</div>
				</div>
				<div>
					<div className="flex items-center justify-between text-sm text-gray-300 mb-2">
						<span className="inline-flex items-center gap-2"><DoorOpen className="w-4 h-4 text-emerald-300" /> {t('details.wardrobe')}</span>
						<span className="text-white font-semibold">{interior.wardrobe === 1 ? t('details.available') : t('details.notAvailable')}</span>
					</div>
					<div className="h-2 rounded-full bg-slate-700 overflow-hidden">
						<div className={`h-full ${interior.wardrobe === 1 ? 'bg-gradient-to-r from-emerald-500 to-emerald-300' : 'bg-gradient-to-r from-rose-500 to-rose-300'}`} style={{ width: interior.wardrobe === 1 ? '100%' : '25%' }}></div>
					</div>
				</div>
			</div>
		</div>
	)

	return (
		<>
			<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-2">
				{interiors.map((i) => (
					<InteriorCard key={i.id} interior={i} onClick={() => setSelected(i)} />
				))}
			</div>
			<div className="mt-4 pt-3 border-t border-[#0f2545]/60">
				<div className="grid grid-cols-3 gap-3 text-center">
					<div className="rounded-xl p-3 border border-[#0f2545]/60 bg-[#0c1627]/60">
						<p className="text-xl font-bold text-white">{interiors.length}</p>
						<p className="text-[#9cbdf5] text-xs">{t('details.total')}</p>
					</div>
					<div className="rounded-xl p-3 border border-[#0f2545]/60 bg-[#0c1627]/60">
						<p className="text-xl font-bold text-emerald-400">{interiors.filter(i => i.wardrobe === 1).length}</p>
						<p className="text-[#9cbdf5] text-xs">{t('details.wardrobe')}</p>
					</div>
					<div className="rounded-xl p-3 border border-[#0f2545]/60 bg-[#0c1627]/60">
						<p className="text-xl font-bold text-cyan-300">{interiors.filter(i => typeof i.posX === 'number').length}</p>
						<p className="text-[#9cbdf5] text-xs">{t('details.mapped')}</p>
					</div>
				</div>
			</div>

			{selected && createPortal(
				<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
					<div className="absolute inset-0 bg-black/80 backdrop-blur-sm" onClick={() => setSelected(null)}></div>
					<InteriorDetailModal interior={selected} onClose={() => setSelected(null)} />
				</div>,
				document.body
			)}
		</>
	)
}
