import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import AppLayout from '@/layouts/app-layout';
import { type BreadcrumbItem } from '@/types';
import { Head, Link, router } from '@inertiajs/react';
import { ArrowLeft, Edit, Trash2, Users, Mail, Building, CheckCircle, XCircle, Shield, Key, FolderOpen, Phone, MapPin } from 'lucide-react';
import { showConfirmation, showSuccess, showError } from '@/lib/toast';

interface Role {
    id: number;
    name: string;
}

interface Permission {
    id: number;
    name: string;
}

interface Project {
    id: number;
    name: string;
    description?: string;
}

interface Institution {
    id: number;
    name: string;
}

interface Departamento {
    id: number;
    name: string;
}

interface Municipio {
    id: number;
    name: string;
}

interface User {
    id: number;
    name: string;
    email: string;
    phone?: string;
    avatar?: string;
    profile_photo_url: string;
    institution?: Institution;
    departamento?: Departamento;
    municipio?: Municipio;
    profile_completed: boolean;
    is_researcher: boolean;
    email_verified_at?: string;
    roles?: Role[];
    permissions?: Permission[];
    created_projects?: Project[];
    collaborating_projects?: Project[];
    created_at: string;
    updated_at: string;
}

interface Props {
    user: User;
}

export default function UsersShow({ user }: Props) {
    const breadcrumbs: BreadcrumbItem[] = [
        { title: 'Dashboard', href: '/dashboard' },
        { title: 'Usuarios', href: '/users' },
        { title: user.name, href: `/users/${user.id}` },
    ];

    const handleDelete = () => {
        showConfirmation(
            `¿Estás seguro de que quieres eliminar el usuario "${user.name}"?`,
            () => {
                router.delete(`/users/${user.id}`, {
                    onSuccess: () => {
                        showSuccess('Usuario eliminado exitosamente');
                    },
                    onError: () => {
                        showError('Error al eliminar el usuario');
                    }
                });
            }
        );
    };

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={user.name} />

            <div className="flex h-full flex-1 flex-col gap-6 rounded-xl p-6">
                {/* Header */}
                <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
                    <div className="flex items-center gap-4">
                        <div className="flex items-center gap-3">
                            <Avatar className="h-10 w-10 sm:h-12 sm:w-12">
                                <AvatarImage src={user.profile_photo_url} alt={user.name} />
                                <AvatarFallback>
                                    {user.name?.split(' ').map(n => n[0]).join('').toUpperCase()}
                                </AvatarFallback>
                            </Avatar>
                            <div>
                                <h1 className="text-2xl sm:text-3xl font-bold text-emerald-700 dark:text-emerald-400">
                                    {user.name}
                                </h1>
                                <p className="text-slate-600 dark:text-slate-400 mt-2">
                                    Detalles del usuario
                                </p>
                            </div>
                        </div>
                    </div>
                    <div className="flex flex-wrap gap-2">
                        <Button variant="outline" asChild>
                            <Link href="/users">
                                <ArrowLeft className="w-4 h-4 mr-2" />
                                Volver
                            </Link>
                        </Button>
                        <Button variant="outline" asChild>
                            <Link href={`/usuarios/${user.id}/roles`}>
                                <Shield className="w-4 h-4 mr-2" />
                                Gestionar Roles
                            </Link>
                        </Button>
                        <Button variant="outline" asChild>
                            <Link href={`/users/${user.id}/edit`}>
                                <Edit className="w-4 h-4 mr-2" />
                                Editar
                            </Link>
                        </Button>
                        <Button
                            variant="destructive"
                            onClick={handleDelete}
                        >
                            <Trash2 className="w-4 h-4 mr-2" />
                            Eliminar
                        </Button>
                    </div>
                </div>

                {/* User Details */}
                <div className="w-auto space-y-6">
                    {/* Basic Information */}
                    <Card>
                        <CardHeader>
                            <CardTitle className="text-emerald-700 dark:text-emerald-400">
                                Información del Usuario
                            </CardTitle>
                            <CardDescription>
                                Detalles básicos del usuario
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-6">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div>
                                    <label className="text-sm font-medium text-slate-900 dark:text-white">
                                        Nombre Completo
                                    </label>
                                    <p className="mt-1 text-slate-700 dark:text-slate-300 bg-slate-50 dark:bg-slate-800/50 p-3 rounded-lg">
                                        {user.name}
                                    </p>
                                </div>

                                <div>
                                    <label className="text-sm font-medium text-slate-900 dark:text-white">
                                        Correo Electrónico
                                    </label>
                                    <div className="mt-1 flex items-center gap-2 bg-slate-50 dark:bg-slate-800/50 p-3 rounded-lg">
                                        <Mail className="w-4 h-4 text-slate-500" />
                                        <span className="text-slate-700 dark:text-slate-300">
                                            {user.email}
                                        </span>
                                    </div>
                                </div>

                                {user.phone && (
                                    <div>
                                        <label className="text-sm font-medium text-slate-900 dark:text-white">
                                            Teléfono
                                        </label>
                                        <div className="mt-1 flex items-center gap-2 bg-slate-50 dark:bg-slate-800/50 p-3 rounded-lg">
                                            <Phone className="w-4 h-4 text-slate-500" />
                                            <span className="text-slate-700 dark:text-slate-300">
                                                {user.phone}
                                            </span>
                                        </div>
                                    </div>
                                )}

                                {user.institution && (
                                    <div>
                                        <label className="text-sm font-medium text-slate-900 dark:text-white">
                                            Institución
                                        </label>
                                        <div className="mt-1 flex items-center gap-2 bg-slate-50 dark:bg-slate-800/50 p-3 rounded-lg">
                                            <Building className="w-4 h-4 text-slate-500" />
                                            <span className="text-slate-700 dark:text-slate-300">
                                                {user.institution.name}
                                            </span>
                                        </div>
                                    </div>
                                )}

                                {user.departamento && (
                                    <div>
                                        <label className="text-sm font-medium text-slate-900 dark:text-white">
                                            Departamento
                                        </label>
                                        <div className="mt-1 flex items-center gap-2 bg-slate-50 dark:bg-slate-800/50 p-3 rounded-lg">
                                            <MapPin className="w-4 h-4 text-slate-500" />
                                            <span className="text-slate-700 dark:text-slate-300">
                                                {user.departamento.name}
                                            </span>
                                        </div>
                                    </div>
                                )}

                                {user.municipio && (
                                    <div>
                                        <label className="text-sm font-medium text-slate-900 dark:text-white">
                                            Municipio
                                        </label>
                                        <div className="mt-1 flex items-center gap-2 bg-slate-50 dark:bg-slate-800/50 p-3 rounded-lg">
                                            <MapPin className="w-4 h-4 text-slate-500" />
                                            <span className="text-slate-700 dark:text-slate-300">
                                                {user.municipio.name}
                                            </span>
                                        </div>
                                    </div>
                                )}

                                <div>
                                    <label className="text-sm font-medium text-slate-900 dark:text-white">
                                        Estado de Verificación
                                    </label>
                                    <div className="mt-1 flex items-center gap-2 bg-slate-50 dark:bg-slate-800/50 p-3 rounded-lg">
                                        {user.email_verified_at ? (
                                            <Badge variant="default">
                                                <CheckCircle className="w-3 h-3 mr-1" />
                                                Correo Verificado
                                            </Badge>
                                        ) : (
                                            <Badge variant="secondary">
                                                <XCircle className="w-3 h-3 mr-1" />
                                                Correo Sin Verificar
                                            </Badge>
                                        )}
                                    </div>
                                </div>

                                <div>
                                    <label className="text-sm font-medium text-slate-900 dark:text-white">
                                        Estado del Perfil
                                    </label>
                                    <div className="mt-1 flex items-center gap-2 bg-slate-50 dark:bg-slate-800/50 p-3 rounded-lg">
                                        {user.profile_completed ? (
                                            <Badge variant="outline">
                                                <CheckCircle className="w-3 h-3 mr-1" />
                                                Perfil Completo
                                            </Badge>
                                        ) : (
                                            <Badge variant="destructive">
                                                <XCircle className="w-3 h-3 mr-1" />
                                                Perfil Incompleto
                                            </Badge>
                                        )}
                                    </div>
                                </div>

                                <div>
                                    <label className="text-sm font-medium text-slate-900 dark:text-white">
                                        ¿Es Investigador?
                                    </label>
                                    <div className="mt-1 flex items-center gap-2 bg-slate-50 dark:bg-slate-800/50 p-3 rounded-lg">
                                        {user.is_researcher ? (
                                            <Badge variant="outline" className="border-emerald-500 text-emerald-600">
                                                <CheckCircle className="w-3 h-3 mr-1" />
                                                Sí
                                            </Badge>
                                        ) : (
                                            <Badge variant="secondary">
                                                <XCircle className="w-3 h-3 mr-1" />
                                                No
                                            </Badge>
                                        )}
                                    </div>
                                </div>

                                <div>
                                    <label className="text-sm font-medium text-slate-900 dark:text-white">
                                        Roles Asignados
                                    </label>
                                    <div className="mt-1 flex items-center gap-2 bg-slate-50 dark:bg-slate-800/50 p-3 rounded-lg">
                                        <Shield className="w-4 h-4 text-slate-500" />
                                        <span className="text-slate-700 dark:text-slate-300">
                                            {user.roles?.length || 0} roles
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </CardContent>
                    </Card>

                    {/* Roles */}
                    {user.roles && user.roles.length > 0 && (
                        <Card>
                            <CardHeader>
                                <CardTitle className="text-emerald-700 dark:text-emerald-400">
                                    Roles Asignados
                                </CardTitle>
                                <CardDescription>
                                    Roles que tiene asignado este usuario
                                </CardDescription>
                            </CardHeader>
                            <CardContent>
                                <div className="flex flex-wrap gap-2">
                                    {user.roles.map((role) => (
                                        <Badge key={role.id} variant="secondary" className="px-3 py-1">
                                            <Shield className="w-3 h-3 mr-1" />
                                            {role.name}
                                        </Badge>
                                    ))}
                                </div>
                            </CardContent>
                        </Card>
                    )}

                    {/* Permissions */}
                    {user.permissions && user.permissions.length > 0 && (
                        <Card>
                            <CardHeader>
                                <CardTitle className="text-emerald-700 dark:text-emerald-400">
                                    Permisos Directos
                                </CardTitle>
                                <CardDescription>
                                    Permisos asignados directamente a este usuario
                                </CardDescription>
                            </CardHeader>
                            <CardContent>
                                <div className="flex flex-wrap gap-2">
                                    {user.permissions.map((permission) => (
                                        <Badge key={permission.id} variant="secondary" className="px-3 py-1">
                                            <Key className="w-3 h-3 mr-1" />
                                            {permission.name}
                                        </Badge>
                                    ))}
                                </div>
                            </CardContent>
                        </Card>
                    )}

                    {/* Projects */}
                    {(user.created_projects && user.created_projects.length > 0) || (user.collaborating_projects && user.collaborating_projects.length > 0) ? (
                        <Card>
                            <CardHeader>
                                <CardTitle className="text-emerald-700 dark:text-emerald-400">
                                    Proyectos
                                </CardTitle>
                                <CardDescription>
                                    Proyectos asociados a este usuario
                                </CardDescription>
                            </CardHeader>
                            <CardContent className="space-y-4">
                                {user.created_projects && user.created_projects.length > 0 && (
                                    <div>
                                        <h4 className="text-sm font-medium text-slate-900 dark:text-white mb-3 flex items-center gap-2">
                                            <FolderOpen className="w-4 h-4" />
                                            Proyectos Creados ({user.created_projects.length})
                                        </h4>
                                        <div className="space-y-2">
                                            {user.created_projects.map((project) => (
                                                <div key={project.id} className="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-800/50 rounded-lg">
                                                    <div>
                                                        <p className="font-medium text-slate-900 dark:text-white">
                                                            {project.name}
                                                        </p>
                                                        {project.description && (
                                                            <p className="text-sm text-slate-600 dark:text-slate-400">
                                                                {project.description}
                                                            </p>
                                                        )}
                                                    </div>
                                                    <Badge variant="outline">Creador</Badge>
                                                </div>
                                            ))}
                                        </div>
                                    </div>
                                )}

                                {user.collaborating_projects && user.collaborating_projects.length > 0 && (
                                    <div>
                                        <h4 className="text-sm font-medium text-slate-900 dark:text-white mb-3 flex items-center gap-2">
                                            <Users className="w-4 h-4" />
                                            Proyectos de Colaboración ({user.collaborating_projects.length})
                                        </h4>
                                        <div className="space-y-2">
                                            {user.collaborating_projects.map((project) => (
                                                <div key={project.id} className="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-800/50 rounded-lg">
                                                    <div>
                                                        <p className="font-medium text-slate-900 dark:text-white">
                                                            {project.name}
                                                        </p>
                                                        {project.description && (
                                                            <p className="text-sm text-slate-600 dark:text-slate-400">
                                                                {project.description}
                                                            </p>
                                                        )}
                                                    </div>
                                                    <Badge variant="secondary">Colaborador</Badge>
                                                </div>
                                            ))}
                                        </div>
                                    </div>
                                )}
                            </CardContent>
                        </Card>
                    ) : (
                        <Card>
                            <CardHeader>
                                <CardTitle className="text-emerald-700 dark:text-emerald-400">
                                    Proyectos
                                </CardTitle>
                                <CardDescription>
                                    Este usuario aún no tiene proyectos asociados
                                </CardDescription>
                            </CardHeader>
                            <CardContent>
                                <p className="text-slate-600 dark:text-slate-400">
                                    No hay proyectos creados ni colaboraciones activas.
                                </p>
                            </CardContent>
                        </Card>
                    )}

                    {/* Timestamps */}
                    <Card>
                        <CardHeader>
                            <CardTitle className="text-emerald-700 dark:text-emerald-400">
                                Información del Sistema
                            </CardTitle>
                        </CardHeader>
                        <CardContent>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label className="text-sm font-medium text-slate-900 dark:text-white">
                                        Fecha de Registro
                                    </label>
                                    <p className="mt-1 text-slate-700 dark:text-slate-300 bg-slate-50 dark:bg-slate-800/50 p-3 rounded-lg">
                                        {new Date(user.created_at).toLocaleDateString('es-ES', {
                                            year: 'numeric',
                                            month: 'long',
                                            day: 'numeric',
                                            hour: '2-digit',
                                            minute: '2-digit'
                                        })}
                                    </p>
                                </div>
                                <div>
                                    <label className="text-sm font-medium text-slate-900 dark:text-white">
                                        Última Actualización
                                    </label>
                                    <p className="mt-1 text-slate-700 dark:text-slate-300 bg-slate-50 dark:bg-slate-800/50 p-3 rounded-lg">
                                        {new Date(user.updated_at).toLocaleDateString('es-ES', {
                                            year: 'numeric',
                                            month: 'long',
                                            day: 'numeric',
                                            hour: '2-digit',
                                            minute: '2-digit'
                                        })}
                                    </p>
                                </div>
                            </div>
                        </CardContent>
                    </Card>
                </div>
            </div>
        </AppLayout>
    );
}