'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeft, Trash2, UserCog, Pencil } from 'lucide-react';
import { toast } from 'sonner';

import { adminUsersApi } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { useState } from 'react';
import { useAuthStore } from '@/store/auth';

const roleColors: Record<string, 'default' | 'secondary' | 'destructive'> = {
  super_admin: 'destructive',
  admin: 'default',
};

export default function AdminUserDetailPage() {
  const params = useParams();
  const router = useRouter();
  const queryClient = useQueryClient();
  const { user: currentUser } = useAuthStore();
  const adminUserId = Number(params.id);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);

  const isSuperAdmin = currentUser?.role === 'super_admin';
  const isSelf = currentUser?.id === adminUserId;

  const { data: adminUser, isLoading, error } = useQuery({
    queryKey: ['admin-user', adminUserId],
    queryFn: () => adminUsersApi.get(adminUserId),
    enabled: !!adminUserId,
  });

  const deleteMutation = useMutation({
    mutationFn: () => adminUsersApi.delete(adminUserId),
    onSuccess: () => {
      toast.success('Admin user deleted successfully');
      queryClient.invalidateQueries({ queryKey: ['admin-users'] });
      router.push('/admin-users');
    },
    onError: () => {
      toast.error('Failed to delete admin user');
    },
  });

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-muted-foreground">Loading...</div>
      </div>
    );
  }

  if (error || !adminUser) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-red-500">Failed to load admin user</div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon" asChild>
            <Link href="/admin-users">
              <ArrowLeft className="h-4 w-4" />
            </Link>
          </Button>
          <div>
            <div className="flex items-center gap-2">
              <UserCog className="h-5 w-5 text-muted-foreground" />
              <h1 className="text-2xl font-bold">{adminUser.email}</h1>
              <Badge variant={roleColors[adminUser.role] || 'secondary'} className="capitalize">
                {adminUser.role.replace('_', ' ')}
              </Badge>
            </div>
            <p className="text-muted-foreground">
              {adminUser.first_name} {adminUser.last_name}
            </p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          {(isSuperAdmin || isSelf) && (
            <Button variant="outline" asChild>
              <Link href={`/admin-users/${adminUserId}/edit`}>
                <Pencil className="mr-2 h-4 w-4" />
                Edit
              </Link>
            </Button>
          )}
          {isSuperAdmin && !isSelf && (
            <Button
              variant="destructive"
              onClick={() => setShowDeleteDialog(true)}
              disabled={deleteMutation.isPending}
            >
              <Trash2 className="mr-2 h-4 w-4" />
              Delete
            </Button>
          )}
        </div>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        {/* Admin Details */}
        <Card>
          <CardHeader>
            <CardTitle>Account Details</CardTitle>
            <CardDescription>Administrator account information</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <div className="text-sm font-medium text-muted-foreground">Email</div>
                <div className="font-medium">{adminUser.email}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Status</div>
                <Badge variant={adminUser.is_active ? 'default' : 'secondary'}>
                  {adminUser.is_active ? 'Active' : 'Inactive'}
                </Badge>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">First Name</div>
                <div>{adminUser.first_name || '-'}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Last Name</div>
                <div>{adminUser.last_name || '-'}</div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Role</div>
                <Badge variant={roleColors[adminUser.role] || 'secondary'} className="capitalize">
                  {adminUser.role.replace('_', ' ')}
                </Badge>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Activity */}
        <Card>
          <CardHeader>
            <CardTitle>Activity</CardTitle>
            <CardDescription>Login and account activity</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <div className="text-sm font-medium text-muted-foreground">Last Login</div>
                <div>
                  {adminUser.last_login
                    ? new Date(adminUser.last_login).toLocaleString()
                    : 'Never'}
                </div>
              </div>
              <div>
                <div className="text-sm font-medium text-muted-foreground">Created</div>
                <div>{new Date(adminUser.created_at).toLocaleString()}</div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Admin User</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete the admin user &quot;{adminUser.email}&quot;?
              This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => deleteMutation.mutate()}
              className="bg-red-600 hover:bg-red-700"
            >
              {deleteMutation.isPending ? 'Deleting...' : 'Delete'}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
