'use client';

import React, { useEffect, useState } from 'react';
import {
  X,
  Shield,
  User,
  Mail,
  Phone,
  Building,
  FileText,
  CheckCircle2,
  XCircle,
  Trash2,
  UserCheck,
  RefreshCw,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import ConfirmationDialog from '@/components/ui/confirmationDialog';
import { UserRecord } from '@/services/users/types';
import { useDeleteUser, useToggleUserStatus, useUpdateUserRole } from '@/services/users/mutations';

interface UserRoleDrawerProps {
  user: UserRecord | null;
  onClose: () => void;
}

const AVAILABLE_ROLES = [
  { value: 'ADMIN', label: 'System Admin' },
  { value: 'HR', label: 'HR Department' },
  { value: 'BDM', label: 'BDM Manager' },
  { value: 'KYC_OFFICER', label: 'KYC Officer' },
  { value: 'ACCOUNTS', label: 'ACCOUNTant Officer' },
  { value: 'INVENTORY_MANAGER', label: 'Inventory Manager' },
];

export default function UserRoleManagementDrawer({ user, onClose }: UserRoleDrawerProps) {
  const [isMounted, setIsMounted] = useState(false);
  const [selectedRole, setSelectedRole] = useState<string>('');
  const [confirmDelete, setConfirmDelete] = useState(false);

  // React Query Mutations
  const updateRoleMutation = useUpdateUserRole();
  const toggleStatusMutation = useToggleUserStatus();
  const deleteUserMutation = useDeleteUser();

  useEffect(() => {
    if (user) {
      setSelectedRole(user.role);
      setIsMounted(true);
      document.body.style.overflow = 'hidden';
    }
    return () => {
      document.body.style.overflow = 'unset';
    };
  }, [user]);

  if (!user) return null;

  const handleSafeClose = () => {
    setIsMounted(false);
    setTimeout(() => {
      onClose();
    }, 250);
  };

  const handleRoleUpdate = async () => {
    if (selectedRole === user.role) return;
    await updateRoleMutation.mutateAsync({ userId: user.id, role: selectedRole });
  };

  const handleStatusToggle = async () => {
    await toggleStatusMutation.mutateAsync({
      userId: user.id,
      targetState: !user.isActive,
    });
  };

  const handleDeleteUser = async () => {
    await deleteUserMutation.mutateAsync(user.id);
    setConfirmDelete(false);
    handleSafeClose();
  };

  return (
    <>
      {/* Backdrop Fog Overlay Canvas */}
      <div
        className={`fixed inset-0 bg-black/40 backdrop-blur-xs z-40 transition-opacity duration-300 ease-in-out ${
          isMounted ? 'opacity-100' : 'opacity-0'
        }`}
        onClick={handleSafeClose}
      />

      {/* Hardware-Accelerated Sliding Panel Container */}
      <div
        className={`fixed right-0 top-0 bottom-0 w-full max-w-xl bg-background border-l border-border shadow-2xl z-50 p-6 flex flex-col justify-between transform transition-transform duration-300 ease-in-out ${
          isMounted ? 'translate-x-0' : 'translate-x-full'
        } select-none`}
      >
        {/* Main Scrolling Workspace Section */}
        <div className="space-y-5 flex-1 overflow-y-auto pr-1">
          {/* Header */}
          <div className="flex items-center justify-between border-b border-border/10 pb-4">
            <div className="flex items-center gap-2.5">
              <div className="h-9 w-9 rounded-xl bg-primary/10 border border-primary/20 flex items-center justify-center text-sm font-black text-primary">
                {user.firstName?.[0] || 'U'}
                {user.lastName?.[0] || ''}
              </div>
              <div className="flex flex-col text-left">
                <h2 className="text-sm font-bold text-foreground leading-tight">
                  User Account & Role Governance
                </h2>
                <span className="text-[10px] text-muted-foreground">
                  Update RBAC privilege assignments or alter system access state
                </span>
              </div>
            </div>
            <button
              onClick={handleSafeClose}
              className="p-1.5 rounded-lg hover:bg-muted text-muted-foreground/70 hover:text-foreground transition-colors cursor-pointer"
            >
              <X className="h-4 w-4" />
            </button>
          </div>

          {/* Profile Quick-Info Block */}
          <div className="bg-muted/30 border border-border/40 rounded-xl p-3.5 flex items-center justify-between gap-4 text-left">
            <div className="space-y-1.5 min-w-0">
              <div className="flex items-center gap-2 text-xs font-semibold text-foreground">
                <User className="h-3.5 w-3.5 text-muted-foreground/60" />
                <span className="truncate">
                  {user.firstName} {user.lastName}
                </span>
              </div>
              <div className="flex items-center gap-2 text-[11px] font-mono text-muted-foreground/80">
                <Mail className="h-3.5 w-3.5 text-muted-foreground/60" />
                <span className="truncate">{user.email}</span>
              </div>
              {user.phone && (
                <div className="flex items-center gap-2 text-[11px] font-mono text-muted-foreground/80">
                  <Phone className="h-3.5 w-3.5 text-muted-foreground/60" />
                  <span>{user.phone}</span>
                </div>
              )}
            </div>

            {/* Account Status Badge */}
            <div className="shrink-0 flex flex-col items-end gap-1">
              <span
                className={`inline-flex items-center gap-1 px-2.5 py-1 text-[10px] font-bold rounded-full ${
                  user.isActive
                    ? 'bg-emerald-500/10 text-emerald-500 border border-emerald-500/20'
                    : 'bg-rose-500/10 text-rose-500 border border-rose-500/20'
                }`}
              >
                <span
                  className={`h-1.5 w-1.5 rounded-full ${
                    user.isActive ? 'bg-emerald-500' : 'bg-rose-500'
                  }`}
                />
                {user.isActive ? 'Active Account' : 'Suspended'}
              </span>
            </div>
          </div>

          {/* Role Assignment Card */}
          <div className="border border-border/40 bg-surface/50 rounded-xl p-4 space-y-3 text-left shadow-xs">
            <div className="flex items-center gap-1.5 text-[10px] font-extrabold uppercase tracking-wider text-muted-foreground">
              <Shield className="h-3.5 w-3.5 text-primary" /> Role Tier Assignment
            </div>

            <div className="space-y-2 pt-1">
              <label className="text-xs font-medium text-foreground block">
                Select System Privilege Tier
              </label>
              <div className="flex items-center gap-2">
                <select
                  value={selectedRole}
                  onChange={(e) => setSelectedRole(e.target.value)}
                  className="w-full text-xs font-medium px-3 py-2 border border-border/40 bg-background rounded-lg text-foreground focus:outline-none focus:border-primary cursor-pointer"
                >
                  {AVAILABLE_ROLES.map((r) => (
                    <option key={r.value} value={r.value}>
                      {r.label} ({r.value})
                    </option>
                  ))}
                </select>
                <Button
                  onClick={handleRoleUpdate}
                  disabled={selectedRole === user.role || updateRoleMutation.isPending}
                  size="sm"
                  className="h-9 px-3 text-xs font-bold shrink-0 cursor-pointer"
                >
                  {updateRoleMutation.isPending ? (
                    <RefreshCw className="h-3.5 w-3.5 animate-spin" />
                  ) : (
                    'Save Role'
                  )}
                </Button>
              </div>
            </div>
          </div>

          {/* Extended Corporate Metadata (if present) */}
          {user.userProfile && (
            <div className="border border-border/40 bg-surface/50 rounded-xl p-3.5 space-y-3 text-left shadow-xs">
              <div className="flex items-center gap-1.5 text-[10px] font-extrabold uppercase tracking-wider text-muted-foreground">
                <Building className="h-3 w-3 text-primary" /> Profile Details
              </div>

              <div className="grid grid-cols-2 gap-x-4 gap-y-2.5 text-xs border-t border-border/10 pt-2.5">
                <div className="col-span-2">
                  <span className="text-[10px] block text-muted-foreground/60 font-medium">
                    Registered Office Address
                  </span>
                  <span className="font-medium text-foreground leading-tight block">
                    {user.userProfile.registeredOfficeAddress || '—'}, {user.userProfile.city},{' '}
                    {user.userProfile.state} - {user.userProfile.postalCode}
                  </span>
                </div>

                <div>
                  <span className="text-[10px] text-muted-foreground/60 font-medium flex items-center gap-1">
                    <FileText className="h-2.5 w-2.5" /> Corporate Reg / CIN
                  </span>
                  <span className="font-mono text-[11px] font-semibold text-foreground/90">
                    {user.userProfile.corporateRegNumber || '—'}
                  </span>
                </div>

                <div>
                  <span className="text-[10px] text-muted-foreground/60 font-medium flex items-center gap-1">
                    <FileText className="h-2.5 w-2.5" /> Tax ID / GSTIN
                  </span>
                  <span className="font-mono text-[11px] font-semibold text-foreground/90">
                    {user.userProfile.taxIdentifier || '—'}
                  </span>
                </div>
              </div>
            </div>
          )}

          {/* Account Governance Actions */}
          <div className="space-y-2 text-left pt-2">
            <span className="block text-[10px] font-bold uppercase tracking-wider text-muted-foreground">
              Administrative Control Operations
            </span>
            <div className="grid grid-cols-2 gap-2">
              <Button
                variant="outline"
                onClick={handleStatusToggle}
                disabled={toggleStatusMutation.isPending}
                className={`h-9 rounded-lg text-xs font-bold gap-1.5 transition-colors cursor-pointer ${
                  user.isActive
                    ? 'border-amber-500/20 bg-amber-500/5 hover:bg-amber-500/10 text-amber-500'
                    : 'border-emerald-500/20 bg-emerald-500/5 hover:bg-emerald-500/10 text-emerald-500'
                }`}
              >
                {user.isActive ? (
                  <>
                    <XCircle className="h-3.5 w-3.5" /> Deactivate Account
                  </>
                ) : (
                  <>
                    <UserCheck className="h-3.5 w-3.5" /> Reactivate Account
                  </>
                )}
              </Button>

              <Button
                variant="outline"
                onClick={() => setConfirmDelete(true)}
                className="h-9 rounded-lg border-rose-500/20 bg-rose-500/5 hover:bg-rose-500/10 text-rose-500 text-xs font-bold gap-1.5 transition-colors cursor-pointer"
              >
                <Trash2 className="h-3.5 w-3.5" /> Purge User
              </Button>
            </div>
          </div>
        </div>

        {/* Bottom Control Bar */}
        <div className="border-t border-border/10 pt-4 flex items-center justify-end">
          <Button variant="ghost" onClick={handleSafeClose} className="h-8 text-xs font-semibold cursor-pointer">
            Close Panel
          </Button>
        </div>
      </div>

      {/* Permanent Deletion Dialog */}
      <ConfirmationDialog
        isOpen={confirmDelete}
        title="Confirm User Account Purge"
        description={`Are you sure you want to permanently delete user account "${user.firstName} ${user.lastName}" (${user.email})? This action drops all assigned roles and authorization tokens instantly.`}
        confirmLabel="Permanently Delete User"
        cancelLabel="Cancel"
        variant="danger"
        isLoading={deleteUserMutation.isPending}
        onConfirm={handleDeleteUser}
        onCancel={() => setConfirmDelete(false)}
      />
    </>
  );
}