import { Avatar, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Link as InertiaLink } from '@inertiajs/react';
import {
  ArrowRight,
  Award,
  Building,
  Calendar,
  Clock,
  Dog,
  Heart,
  IdCard,
  MapPin,
  Medal,
  Phone,
  Shield,
  Star,
  Trophy,
  Users,
  X,
} from 'lucide-react';
import { useState } from 'react';

interface ProfileHeaderOwnerProps {
    profile: any;
}

// Define interfaces para los datos estructurados
interface PerroGanador {
    id: number;
    nombre: string;
    foto: string;
    raza: string;
    premio: string;
    evento: string;
    fecha: string;
}

interface EventoOwner {
    nombre: string;
    fecha: string;
    lugar?: string;
    resultado?: string;
}

export default function ProfileHeaderOwner({ profile }: ProfileHeaderOwnerProps) {
    const [previewImage, setPreviewImage] = useState<string | null>(null);

    if (!profile) return null;

    // Datos de perfil con valores por defecto
    const data = {
        name: profile.name || '—',
        lastname: profile.lastname || '',
        document: profile.documento_identidad || profile.document || '—',
        phone: profile.phone || '—',
        address: profile.address || '—',
        register_date: profile.register_date ? new Date(profile.register_date).toLocaleDateString() : '—',
        seguidores: profile.seguidores || profile.followers || 1000,
        seguidos: profile.seguidos || profile.following || 40,
        me_gusta: profile.me_gusta || profile.likes || 10000,
        pets: profile.pets || profile.mascotas || 2,
        kennels: profile.kennels || profile.criaderos || 1,
        isPremium: profile.isPremium || profile.premium || true,
        homologado: profile.homologado || profile.verified || true,
        city: profile.city || '—',
        country: profile.country || '—',
        last_activity: profile.last_activity || '12/05/2024',
        nationality: profile.nationality || '—',
    };

    // Imagen principal del perfil
    const profileImage = profile.photo || profile.image || '/landing/avatar.jpg';
    
    // Banner de fondo (usa la imagen por defecto si no hay una personalizada)
    const bannerImage = profile.banner_image || '/landing/image1.png';
    
    const fullName = data.lastname ? `${data.name} ${data.lastname}` : data.name;
    const location = [data.city, data.country].filter(Boolean).join(', ');

    // Datos del último animal ganador, si existe
    const ultimoGanador = profile.animales_destacados?.find((animal: any) => 
        animal.premios?.length > 0 || animal.logros?.length > 0
    ) || profile.ultimos_logros?.animal || null;

    // Últimos eventos del propietario
    const ultimosEventos: EventoOwner[] = profile.eventos || profile.events || [
        {
            nombre: "Campeonato Nacional Canino",
            fecha: "24/04/2024",
            lugar: "Madrid, España",
            resultado: "Primer lugar - Mejor Criador"
        }
    ];

    // Últimos perros destacados que han ganado concursos
    const perrosGanadores: PerroGanador[] = profile.perros_ganadores || profile.winning_dogs || [
        {
            id: 1,
            nombre: "King of Hearts",
            foto: "/landing/avatar2.webp",
            raza: "American Bully XL",
            premio: "Best in Show",
            evento: "Expo Canina Internacional",
            fecha: "15/03/2024"
        },
        {
            id: 2,
            nombre: "Queen's Gambit",
            foto: "/landing/avatar2.webp",
            raza: "American Bully Pocket",
            premio: "Mejor de Raza",
            evento: "Bully Championship",
            fecha: "22/02/2024"
        }
    ];

    // Último evento participado
    const ultimoEvento: EventoOwner = ultimosEventos[0] || {
        nombre: "Sin eventos registrados",
        fecha: "—"
    };

    return (
        <div className="relative">
            {/* Fondo degradado o imagen */}
            <div
                className="mb-[-64px] h-72 w-full rounded-2xl bg-zinc-900 bg-cover bg-center bg-no-repeat"
                style={{
                    backgroundImage: `url(${bannerImage})`,
                    boxShadow: 'inset 0 0 0 2000px rgba(0, 0, 0, 0.4)',
                }}
            />

            <Card className="relative z-10 mt-[-64px] rounded-2xl border-none bg-zinc-900 shadow-xl">
                <CardContent className="p-6 md:p-8">
                    <div className="flex flex-col items-center gap-8 md:flex-row md:items-start">
                        {/* Columna izquierda - Avatar y datos esenciales */}
                        <div className="flex w-full flex-col items-center md:w-auto md:items-center">
                            <div
                                className="relative mb-4 cursor-pointer transition-transform hover:scale-105"
                                onClick={() => setPreviewImage(profileImage)}
                            >
                                <Avatar className="h-48 w-48 border-4 border-yellow-400 shadow-lg">
                                    <AvatarImage
                                        src={profileImage}
                                        alt={fullName}
                                    />
                                </Avatar>
                                {/* Lupa indicadora */}
                                <div className="absolute right-2 bottom-2 flex h-8 w-8 items-center justify-center rounded-full bg-black/60 text-white opacity-0 transition-opacity hover:opacity-100">
                                    <svg
                                        xmlns="http://www.w3.org/2000/svg"
                                        className="h-4 w-4"
                                        fill="none"
                                        viewBox="0 0 24 24"
                                        stroke="currentColor"
                                    >
                                        <path
                                            strokeLinecap="round"
                                            strokeLinejoin="round"
                                            strokeWidth={2}
                                            d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                                        />
                                    </svg>
                                </div>
                            </div>

                            {/* Estadísticas */}
                            <div className="mt-4 flex w-full justify-center gap-6 rounded-xl border border-zinc-700 bg-transparent p-4 shadow-sm">
                                <div className="flex flex-col items-center">
                                    <span className="text-2xl font-bold text-white">
                                        {data.seguidores}
                                    </span>
                                    <span className="text-sm text-white">
                                        Seguidores
                                    </span>
                                </div>
                                <div className="flex flex-col items-center">
                                    <span className="text-2xl font-bold text-white">
                                        {data.seguidos}
                                    </span>
                                    <span className="text-sm text-white">
                                        Siguiendo
                                    </span>
                                </div>
                                <div className="flex flex-col items-center">
                                    <span className="text-2xl font-bold text-white">
                                        {data.me_gusta}
                                    </span>
                                    <span className="text-sm text-white">
                                        Me gusta
                                    </span>
                                </div>
                            </div>

                            <Button className="mt-4 w-full bg-yellow-400 text-black hover:bg-yellow-500">
                                <Heart className="mr-2 h-4 w-4" /> Seguir
                            </Button>

                            {/* Información adicional */}
                            <div className="mt-4 w-full space-y-2">
                                <div className="flex items-center rounded-lg border border-zinc-700 bg-transparent px-3 py-2 text-sm">
                                    <IdCard className="mr-2 h-4 w-4 text-yellow-400" />
                                    <span className="text-white">
                                        Documento:{' '}
                                        <span className="font-medium">
                                            {data.document}
                                        </span>
                                    </span>
                                </div>
                                <div className="flex items-center rounded-lg border border-zinc-700 bg-transparent px-3 py-2 text-sm">
                                    <Phone className="mr-2 h-4 w-4 text-yellow-400" />
                                    <span className="text-white">
                                        Teléfono:{' '}
                                        <span className="font-medium">
                                            {data.phone}
                                        </span>
                                    </span>
                                </div>
                                <div className="flex items-center rounded-lg border border-zinc-700 bg-transparent px-3 py-2 text-sm">
                                    <Calendar className="mr-2 h-4 w-4 text-yellow-400" />
                                    <span className="text-white">
                                        Registro:{' '}
                                        <span className="font-medium">
                                            {data.register_date}
                                        </span>
                                    </span>
                                </div>
                                <div className="flex items-center rounded-lg border border-zinc-700 bg-transparent px-3 py-2 text-sm">
                                    <Clock className="mr-2 h-4 w-4 text-yellow-400" />
                                    <span className="text-white">
                                        Última actividad:{' '}
                                        <span className="font-medium">
                                            {data.last_activity}
                                        </span>
                                    </span>
                                </div>
                                
                                {/* Nuevo - Último evento */}
                                <div className="flex items-center rounded-lg border border-zinc-700 bg-transparent px-3 py-2 text-sm">
                                    <Trophy className="mr-2 h-4 w-4 text-yellow-400" />
                                    <span className="text-white">
                                        Último evento:{' '}
                                        <span className="font-medium">
                                            {ultimoEvento.fecha}
                                        </span>
                                    </span>
                                </div>
                            </div>
                        </div>

                        {/* Columna central - Info principal y datos rápidos */}
                        <div className="flex-1 space-y-4">
                            <div>
                                <h1 className="flex flex-wrap items-center gap-2 text-3xl font-bold text-white">
                                    {fullName}

                                    {/* Badge Premium */}
                                    {data.isPremium && (
                                        <Badge className="flex items-center gap-1 bg-yellow-400 text-black">
                                            <Star className="h-4 w-4 text-black" />{' '}
                                            Premium
                                        </Badge>
                                    )}

                                    {/* Badge homologado */}
                                    {data.homologado && (
                                        <Badge
                                            className="flex items-center gap-1 bg-blue-600 text-white"
                                        >
                                            <Shield className="h-4 w-4 text-white" />{' '}
                                            Homologado
                                        </Badge>
                                    )}
                                </h1>

                                <p className="text-lg text-white/80">
                                    {data.nationality} • {location}
                                </p>
                            </div>

                            {/* Datos rápidos */}
                            <div className="grid grid-cols-1 gap-3 text-sm md:grid-cols-2">
                                <div className="flex items-center gap-2 rounded-lg border border-zinc-700 bg-transparent px-3 py-2 shadow-sm">
                                    <Dog className="h-5 w-5 text-yellow-400" />
                                    <div>
                                        <span className="font-medium text-white">
                                            Mascotas:
                                        </span>{' '}
                                        <span className="text-white/80">
                                            {data.pets} animal{data.pets !== 1 ? 'es' : ''}
                                        </span>
                                    </div>
                                </div>
                                <div className="flex items-center gap-2 rounded-lg border border-zinc-700 bg-transparent px-3 py-2 shadow-sm">
                                    <Building className="h-5 w-5 text-yellow-400" />
                                    <div>
                                        <span className="font-medium text-white">
                                            Criaderos:
                                        </span>{' '}
                                        <span className="text-white/80">
                                            {data.kennels} criadero{data.kennels !== 1 ? 's' : ''}
                                        </span>
                                    </div>
                                </div>
                                <div className="flex items-center gap-2 rounded-lg border border-zinc-700 bg-transparent px-3 py-2 shadow-sm">
                                    <MapPin className="h-5 w-5 text-yellow-400" />
                                    <div>
                                        <span className="font-medium text-white">
                                            Ciudad:
                                        </span>{' '}
                                        <span className="text-white/80">
                                            {data.city}
                                        </span>
                                    </div>
                                </div>
                                <div className="flex items-center gap-2 rounded-lg border border-zinc-700 bg-transparent px-3 py-2 shadow-sm">
                                    <Star className="h-5 w-5 text-yellow-400" />
                                    <div>
                                        <span className="font-medium text-white">
                                            Nacionalidad:
                                        </span>{' '}
                                        <span className="text-white/80">
                                            {data.nationality}
                                        </span>
                                    </div>
                                </div>
                            </div>

                            {/* Último evento del propietario */}
                            <div className="rounded-lg border border-zinc-700 bg-zinc-800/30 p-4">
                                <h3 className="flex items-center gap-2 text-sm font-semibold text-white mb-3">
                                    <Trophy className="h-4 w-4 text-yellow-400" />
                                    Último evento destacado
                                </h3>
                                <div className="text-sm text-white/80">
                                    <p className="font-medium text-white">{ultimoEvento.nombre}</p>
                                    <div className="flex flex-col md:flex-row md:items-center md:gap-6 mt-2 space-y-1 md:space-y-0">
                                        <p className="flex items-center gap-1">
                                            <Calendar className="h-3.5 w-3.5 text-yellow-400" />
                                            {ultimoEvento.fecha}
                                        </p>
                                        {ultimoEvento.lugar && (
                                            <p className="flex items-center gap-1">
                                                <MapPin className="h-3.5 w-3.5 text-yellow-400" />
                                                {ultimoEvento.lugar}
                                            </p>
                                        )}
                                        {ultimoEvento.resultado && (
                                            <p className="flex items-center gap-1">
                                                <Medal className="h-3.5 w-3.5 text-yellow-400" />
                                                {ultimoEvento.resultado}
                                            </p>
                                        )}
                                    </div>
                                </div>
                            </div>

                            {/* Perros ganadores */}
                            {perrosGanadores.length > 0 && (
                                <div className="rounded-lg border border-zinc-700 bg-zinc-800/30 p-4">
                                    <h3 className="flex items-center gap-2 text-sm font-semibold text-white mb-3">
                                        <Award className="h-4 w-4 text-yellow-400" />
                                        Perros premiados recientes
                                    </h3>
                                    <div className="space-y-3">
                                        {perrosGanadores.slice(0, 2).map((perro: PerroGanador, index: number) => (
                                            <div key={index} className="flex items-center gap-3">
                                                <div className="h-14 w-14 overflow-hidden rounded-lg border border-zinc-600">
                                                    <img 
                                                        src={perro.foto || '/placeholder.svg'} 
                                                        alt={perro.nombre} 
                                                        className="h-full w-full object-cover"
                                                    />
                                                </div>
                                                <div className="flex-1">
                                                    <p className="font-medium text-white flex items-center justify-between">
                                                        {perro.nombre}
                                                        <span className="text-xs font-normal text-yellow-400">
                                                            {perro.raza}
                                                        </span>
                                                    </p>
                                                    <p className="text-xs text-white/70 mt-1">
                                                        <span className="font-medium">{perro.premio}</span> - {perro.evento} ({perro.fecha})
                                                    </p>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            )}

                            {/* Último animal ganador - Si existe */}
                            {ultimoGanador && (
                                <div className="rounded-lg border border-zinc-700 bg-zinc-800/30 p-4">
                                    <h3 className="flex items-center gap-2 text-sm font-semibold text-white mb-3">
                                        <Trophy className="h-4 w-4 text-yellow-400" />
                                        Último animal premiado
                                    </h3>
                                    <div className="flex items-center gap-3">
                                        <div className="h-16 w-16 overflow-hidden rounded-lg border border-zinc-600">
                                            <img 
                                                src={ultimoGanador.foto || ultimoGanador.image || '/placeholder.svg'} 
                                                alt={ultimoGanador.nombre || ultimoGanador.name} 
                                                className="h-full w-full object-cover"
                                            />
                                        </div>
                                        <div className="flex-1">
                                            <p className="font-medium text-white">
                                                {ultimoGanador.nombre || ultimoGanador.name}
                                                <span className="ml-2 text-xs font-normal text-yellow-400">
                                                    {ultimoGanador.raza || ultimoGanador.breed}
                                                </span>
                                            </p>
                                            <p className="text-sm text-white/70 mt-1">
                                                {ultimoGanador.premios?.[0]?.titulo || 
                                                 ultimoGanador.logros?.[0]?.nombre || 
                                                 ultimoGanador.ultimo_premio?.nombre ||
                                                 "Premio destacado"}
                                                {ultimoGanador.premios?.[0]?.fecha || 
                                                 ultimoGanador.logros?.[0]?.fecha || 
                                                 ultimoGanador.ultimo_premio?.fecha ? 
                                                    ` (${ultimoGanador.premios?.[0]?.fecha || 
                                                        ultimoGanador.logros?.[0]?.fecha || 
                                                        ultimoGanador.ultimo_premio?.fecha})` : ""}
                                            </p>
                                        </div>
                                        <InertiaLink 
                                            href={`/bulls/${ultimoGanador.id}`} 
                                            className="flex h-8 w-8 items-center justify-center rounded-full bg-zinc-700 text-white hover:bg-yellow-400 hover:text-black transition-colors"
                                        >
                                            <ArrowRight className="h-4 w-4" />
                                        </InertiaLink>
                                    </div>
                                </div>
                            )}

                            {/* Mascotas destacadas - Si hay mascotas */}
                            {profile.destacados && profile.destacados.mascotas && profile.destacados.mascotas.length > 0 && (
                                <div className="mt-6">
                                    <h3 className="mb-3 flex items-center text-sm font-semibold text-white">
                                        <Dog className="mr-1 h-4 w-4 text-yellow-400" />
                                        Mascotas destacadas
                                    </h3>
                                    <div className="flex snap-x gap-3 overflow-x-auto pb-2">
                                        {profile.destacados.mascotas.map((mascota: any, i: number) => (
                                            <div
                                                key={i}
                                                className="relative h-24 w-24 cursor-pointer overflow-hidden rounded-md border border-zinc-700 shadow-sm transition-all hover:scale-105 hover:shadow-md"
                                            >
                                                <img
                                                    src={mascota.foto || '/placeholder.svg'}
                                                    alt={`Foto de ${mascota.nombre}`}
                                                    className="h-full w-full flex-shrink-0 snap-start object-cover"
                                                />
                                            </div>
                                        ))}
                                        {profile.destacados.mascotas.length > 5 && (
                                            <div className="flex h-24 w-24 flex-shrink-0 snap-start items-center justify-center rounded-md border border-zinc-700 bg-zinc-800/50 text-white shadow-sm">
                                                +{profile.destacados.mascotas.length - 5}
                                            </div>
                                        )}
                                    </div>
                                </div>
                            )}

                            {/* Criaderos destacados - Si hay criaderos */}
                            {profile.destacados && profile.destacados.criaderos && profile.destacados.criaderos.length > 0 && (
                                <div className="rounded-lg border border-zinc-700 bg-transparent p-4">
                                    <h3 className="flex items-center gap-2 text-sm font-semibold text-white">
                                        <Building className="h-4 w-4 text-yellow-400" />
                                        Criadero principal
                                    </h3>
                                    <div className="mt-2 text-sm text-white/80">
                                        <p className="font-medium text-white">
                                            {profile.destacados.criaderos[0].nombre}
                                        </p>
                                        <p className="mt-1 flex items-center gap-1">
                                            <MapPin className="h-3 w-3 text-yellow-400" />
                                            {profile.destacados.criaderos[0].ubicacion}
                                        </p>
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>

                    {/* Sección de Logros - Si hay logros */}
                    {profile.premios && profile.premios.length > 0 && (
                        <div className="mt-10">
                            <h2 className="mb-4 flex items-center gap-2 text-xl font-semibold text-white">
                                <Award className="h-6 w-6 text-yellow-400" />
                                Logros y Reconocimientos ({profile.premios.length})
                            </h2>

                            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 md:grid-cols-3">
                                {profile.premios.map((premio: any, idx: number) => (
                                    <div
                                        key={idx}
                                        className="flex flex-col gap-2 rounded-xl border border-zinc-700 bg-zinc-800/30 p-4 shadow-md transition-transform hover:-translate-y-1 hover:shadow-lg"
                                    >
                                        <div className="flex items-center gap-3">
                                            <div className="flex h-10 w-10 items-center justify-center rounded-full bg-yellow-400/20">
                                                <Award className="h-6 w-6 text-yellow-400" />
                                            </div>
                                            <h3 className="font-semibold text-white">
                                                {premio.titulo || 'Reconocimiento'}
                                            </h3>
                                        </div>
                                        <p className="text-sm text-white/80">
                                            {premio.descripcion || premio.entidad || 'Sin descripción disponible.'}
                                        </p>
                                        <div className="mt-1 flex flex-wrap gap-x-4 gap-y-1 text-xs text-white/70">
                                            {premio.fecha && (
                                                <p className="flex items-center">
                                                    <Calendar className="mr-1 h-3 w-3 text-yellow-400" />
                                                    {premio.fecha}
                                                </p>
                                            )}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}
                </CardContent>
            </Card>

            {/* Preview de imagen ampliada */}
            {previewImage && (
                <div
                    className="fixed inset-0 z-50 flex items-center justify-center bg-black/90 p-4 backdrop-blur-sm"
                    onClick={() => setPreviewImage(null)}
                >
                    <div className="relative max-h-[90vh] max-w-[90vw]">
                        <Button
                            variant="ghost"
                            size="icon"
                            className="absolute -top-2 -right-2 rounded-full bg-black text-white hover:bg-zinc-800"
                            onClick={(e) => {
                                e.stopPropagation();
                                setPreviewImage(null);
                            }}
                        >
                            <X className="h-5 w-5" />
                        </Button>
                        <img
                            src={previewImage}
                            alt="Foto ampliada"
                            className="max-h-[85vh] max-w-[85vw] rounded-lg object-contain shadow-2xl"
                        />
                    </div>
                </div>
            )}
        </div>
    );
}