import { useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import {
  ArrowLeft,
  Edit,
  Trash2,
  Mail,
  Phone,
  Calendar,
  Shield,
  UserCheck,
  UserX,
  Key,
} from 'lucide-react';
import { Button } from '@components/atoms/Button';
import { Avatar } from '@components/atoms/Avatar';
import { Spinner } from '@components/atoms/Spinner';
import { Card, CardHeader, CardTitle, CardContent } from '@components/molecules/Card';
import { Breadcrumbs } from '@components/organisms/Breadcrumbs';
import { ConfirmModal } from '@components/organisms/Modal';
import { useToast } from '@components/organisms/Toast';
import { ErrorEmptyState } from '@components/templates/EmptyState';
import { useUser } from '@features/users/hooks';
import { usersApi } from '@features/users/api';
import { UserStatusBadge } from '@features/users/components/UserStatusBadge';
import { formatDate } from '@utils/formatters';

export function UserDetailPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { showToast } = useToast();
  const { user, isLoading, error, refresh } = useUser(id);

  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [showToggleModal, setShowToggleModal] = useState(false);
  const [showResetPasswordModal, setShowResetPasswordModal] = useState(false);
  const [isProcessing, setIsProcessing] = useState(false);

  const handleDelete = async () => {
    if (!id) return;
    setIsProcessing(true);
    try {
      await usersApi.delete(id);
      showToast({
        type: 'success',
        title: 'Usuario eliminado',
        message: 'El usuario ha sido eliminado exitosamente.',
      });
      navigate('/users');
    } catch {
      showToast({
        type: 'error',
        title: 'Error',
        message: 'No se pudo eliminar el usuario.',
      });
    } finally {
      setIsProcessing(false);
      setShowDeleteModal(false);
    }
  };

  const handleToggleStatus = async () => {
    if (!id || !user) return;
    setIsProcessing(true);
    try {
      if (user.status === 'active') {
        await usersApi.deactivate(id);
        showToast({
          type: 'success',
          title: 'Usuario desactivado',
          message: 'El usuario ha sido desactivado.',
        });
      } else {
        await usersApi.activate(id);
        showToast({
          type: 'success',
          title: 'Usuario activado',
          message: 'El usuario ha sido activado.',
        });
      }
      refresh();
    } catch {
      showToast({
        type: 'error',
        title: 'Error',
        message: 'No se pudo cambiar el estado del usuario.',
      });
    } finally {
      setIsProcessing(false);
      setShowToggleModal(false);
    }
  };

  const handleResetPassword = async () => {
    if (!id) return;
    setIsProcessing(true);
    try {
      await usersApi.resetPassword(id);
      showToast({
        type: 'success',
        title: 'Contraseña restablecida',
        message: 'Se ha enviado un email con instrucciones para crear una nueva contraseña.',
      });
    } catch {
      showToast({
        type: 'error',
        title: 'Error',
        message: 'No se pudo restablecer la contraseña.',
      });
    } finally {
      setIsProcessing(false);
      setShowResetPasswordModal(false);
    }
  };

  if (isLoading) {
    return (
      <div className="flex h-96 items-center justify-center">
        <Spinner size="lg" />
      </div>
    );
  }

  if (error || !user) {
    return (
      <div className="p-6">
        <ErrorEmptyState
          title="Usuario no encontrado"
          description="No se pudo cargar la información del usuario."
          onRetry={refresh}
        />
      </div>
    );
  }

  return (
    <div className="space-y-6 p-6">
      <Breadcrumbs
        items={[
          { label: 'Usuarios', href: '/users' },
          { label: `${user.firstName} ${user.lastName}` },
        ]}
      />

      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="sm" onClick={() => navigate('/users')}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            Volver
          </Button>
          <div>
            <h1 className="text-2xl font-bold text-gray-900">Detalle de usuario</h1>
          </div>
        </div>

        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={() => navigate(`/users/${id}/edit`)}>
            <Edit className="mr-2 h-4 w-4" />
            Editar
          </Button>
          <Button variant="danger" onClick={() => setShowDeleteModal(true)}>
            <Trash2 className="mr-2 h-4 w-4" />
            Eliminar
          </Button>
        </div>
      </div>

      <div className="grid gap-6 lg:grid-cols-3">
        {/* User info card */}
        <div className="lg:col-span-1">
          <Card>
            <CardContent className="pt-6">
              <div className="flex flex-col items-center text-center">
                <Avatar
                  src={user.avatar}
                  fallback={`${user.firstName} ${user.lastName}`}
                  size="2xl"
                  status={user.status === 'active' ? 'online' : 'offline'}
                />
                <h2 className="mt-4 text-xl font-semibold text-gray-900">
                  {user.firstName} {user.lastName}
                </h2>
                <p className="text-sm text-gray-500">{user.email}</p>
                <div className="mt-2">
                  <UserStatusBadge status={user.status} />
                </div>

                <div className="mt-6 w-full space-y-2">
                  <Button
                    variant="outline"
                    className="w-full"
                    onClick={() => setShowToggleModal(true)}
                  >
                    {user.status === 'active' ? (
                      <>
                        <UserX className="mr-2 h-4 w-4" />
                        Desactivar usuario
                      </>
                    ) : (
                      <>
                        <UserCheck className="mr-2 h-4 w-4" />
                        Activar usuario
                      </>
                    )}
                  </Button>
                  <Button
                    variant="outline"
                    className="w-full"
                    onClick={() => setShowResetPasswordModal(true)}
                  >
                    <Key className="mr-2 h-4 w-4" />
                    Restablecer contraseña
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Details */}
        <div className="space-y-6 lg:col-span-2">
          <Card>
            <CardHeader>
              <CardTitle>Información de contacto</CardTitle>
            </CardHeader>
            <CardContent>
              <dl className="grid gap-4 sm:grid-cols-2">
                <div className="flex items-center gap-3">
                  <Mail className="h-5 w-5 text-gray-400" />
                  <div>
                    <dt className="text-sm text-gray-500">Email</dt>
                    <dd className="font-medium text-gray-900">{user.email}</dd>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <Phone className="h-5 w-5 text-gray-400" />
                  <div>
                    <dt className="text-sm text-gray-500">Teléfono</dt>
                    <dd className="font-medium text-gray-900">
                      {user.phone || 'No especificado'}
                    </dd>
                  </div>
                </div>
              </dl>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Permisos y acceso</CardTitle>
            </CardHeader>
            <CardContent>
              <dl className="grid gap-4 sm:grid-cols-2">
                <div className="flex items-center gap-3">
                  <Shield className="h-5 w-5 text-gray-400" />
                  <div>
                    <dt className="text-sm text-gray-500">Rol</dt>
                    <dd className="font-medium text-gray-900">
                      {user.role?.name || 'Sin rol asignado'}
                    </dd>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <Calendar className="h-5 w-5 text-gray-400" />
                  <div>
                    <dt className="text-sm text-gray-500">Último acceso</dt>
                    <dd className="font-medium text-gray-900">
                      {user.lastLoginAt
                        ? formatDate(user.lastLoginAt, 'full')
                        : 'Nunca'}
                    </dd>
                  </div>
                </div>
              </dl>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Información del sistema</CardTitle>
            </CardHeader>
            <CardContent>
              <dl className="grid gap-4 sm:grid-cols-2">
                <div>
                  <dt className="text-sm text-gray-500">ID</dt>
                  <dd className="font-mono text-sm text-gray-900">{user.id}</dd>
                </div>
                <div>
                  <dt className="text-sm text-gray-500">Tenant ID</dt>
                  <dd className="font-mono text-sm text-gray-900">{user.tenantId}</dd>
                </div>
                <div>
                  <dt className="text-sm text-gray-500">Creado</dt>
                  <dd className="text-gray-900">{formatDate(user.createdAt, 'full')}</dd>
                </div>
                <div>
                  <dt className="text-sm text-gray-500">Actualizado</dt>
                  <dd className="text-gray-900">{formatDate(user.updatedAt, 'full')}</dd>
                </div>
              </dl>
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Modals */}
      <ConfirmModal
        isOpen={showDeleteModal}
        onClose={() => setShowDeleteModal(false)}
        onConfirm={handleDelete}
        title="Eliminar usuario"
        message={`¿Estás seguro de que deseas eliminar a ${user.firstName} ${user.lastName}? Esta acción no se puede deshacer.`}
        variant="danger"
        confirmText="Eliminar"
        isLoading={isProcessing}
      />

      <ConfirmModal
        isOpen={showToggleModal}
        onClose={() => setShowToggleModal(false)}
        onConfirm={handleToggleStatus}
        title={user.status === 'active' ? 'Desactivar usuario' : 'Activar usuario'}
        message={
          user.status === 'active'
            ? `¿Deseas desactivar a ${user.firstName} ${user.lastName}? El usuario no podrá acceder al sistema.`
            : `¿Deseas activar a ${user.firstName} ${user.lastName}?`
        }
        variant={user.status === 'active' ? 'warning' : 'success'}
        confirmText={user.status === 'active' ? 'Desactivar' : 'Activar'}
        isLoading={isProcessing}
      />

      <ConfirmModal
        isOpen={showResetPasswordModal}
        onClose={() => setShowResetPasswordModal(false)}
        onConfirm={handleResetPassword}
        title="Restablecer contraseña"
        message={`Se enviará un email a ${user.email} con instrucciones para crear una nueva contraseña.`}
        variant="warning"
        confirmText="Enviar email"
        isLoading={isProcessing}
      />
    </div>
  );
}
export default UserDetailPage;
