/**
 * User Detail Page
 * View user details (Managers & Admins only, or own profile)
 */

'use client';

import { useParams, useRouter } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { useAuth } from '@/contexts/AuthContext';
import { usersAPI } from '@/lib/api/users';
import {
  Button,
  Card,
  CardHeader,
  CardTitle,
  CardContent,
  Badge,
  LoadingPage,
} from '@/components/ui';
import { formatDate, formatDateTime } from '@/lib/utils/format';
import { ArrowLeft, Edit } from 'lucide-react';

export default function UserDetailPage() {
  const router = useRouter();
  const params = useParams();
  const userId = parseInt(params.id);
  const { user: currentUser } = useAuth();

  const isManagerOrAdmin = currentUser?.role === 'manager' || currentUser?.role === 'system_admin';
  const isOwnProfile = currentUser?.id === userId;

  // Fetch user details
  const { data: user, isLoading, error } = useQuery({
    queryKey: ['user', userId],
    queryFn: async () => {
      if (isNaN(userId)) {
        throw new Error('Invalid user ID');
      }
      const response = await usersAPI.getById(userId);
      return response?.data?.user || response?.data || response;
    },
    enabled: !isNaN(userId) && (isManagerOrAdmin || isOwnProfile),
  });

  const getRoleVariant = (role) => {
    switch (role) {
      case 'system_admin':
        return 'danger';
      case 'manager':
        return 'warning';
      case 'cashier':
        return 'default';
      default:
        return 'default';
    }
  };

  if (isLoading) {
    return <LoadingPage message="Loading user details..." />;
  }

  if (error) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950 text-center text-red-600">
        <p>Error: {error.message}</p>
        <Button onClick={() => router.back()} className="mt-4">
          Go Back
        </Button>
      </div>
    );
  }

  if (!user) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950 text-center text-gray-600">
        <p>User not found.</p>
        <Button onClick={() => router.back()} className="mt-4">
          Go Back
        </Button>
      </div>
    );
  }

  // If viewing own profile, redirect to profile settings
  if (isOwnProfile) {
    router.push('/settings/profile');
    return <LoadingPage message="Redirecting..." />;
  }

  if (!isManagerOrAdmin) {
    return (
      <div className="p-6 bg-gray-50 dark:bg-gray-950 text-center text-red-600">
        <p>Access denied. You can only view your own profile.</p>
        <Button onClick={() => router.push('/settings/profile')} className="mt-4">
          Go to Profile
        </Button>
      </div>
    );
  }

  return (
    <div className="container mx-auto p-6 max-w-4xl">
      <div className="flex justify-between items-center mb-6">
        <Button variant="ghost" onClick={() => router.back()} className="flex items-center">
          <ArrowLeft className="w-4 h-4 mr-2" /> Back to Users
        </Button>
        <Button
          variant="outline"
          onClick={() => router.push(`/settings/users/${userId}/edit`)}
          className="flex items-center gap-2"
        >
          <Edit className="w-4 h-4" />
          Edit
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>User Details</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <h3 className="font-semibold text-gray-700 dark:text-gray-300 mb-3">Basic Information</h3>
              <div className="space-y-3">
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Username</p>
                  <p className="font-medium">{user.username}</p>
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Full Name</p>
                  <p className="font-medium">{user.full_name}</p>
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Email</p>
                  <p className="font-medium">{user.email || '—'}</p>
                </div>
              </div>
            </div>

            <div>
              <h3 className="font-semibold text-gray-700 dark:text-gray-300 mb-3">Account Information</h3>
              <div className="space-y-3">
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Role</p>
                  <Badge variant={getRoleVariant(user.role)}>
                    {user.role?.replace('_', ' ').toUpperCase() || '—'}
                  </Badge>
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Status</p>
                  <Badge variant={user.active ? 'success' : 'danger'}>
                    {user.active ? 'Active' : 'Inactive'}
                  </Badge>
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">PIN Code</p>
                  <p className="font-medium">{user.pin_code ? 'Set' : 'Not set'}</p>
                </div>
              </div>
            </div>

            <div>
              <h3 className="font-semibold text-gray-700 dark:text-gray-300 mb-3">Activity</h3>
              <div className="space-y-3">
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Last Login</p>
                  <p className="font-medium">
                    {user.last_login ? formatDateTime(user.last_login) : 'Never'}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Created</p>
                  <p className="font-medium">
                    {user.created_at ? formatDateTime(user.created_at) : '—'}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-gray-600 dark:text-gray-400">Last Updated</p>
                  <p className="font-medium">
                    {user.updated_at ? formatDateTime(user.updated_at) : '—'}
                  </p>
                </div>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

