'use client';

import React, { useState } from 'react';
import {
  Plus,
  Search,
  CheckCircle2,
  XCircle,
  Clock,
  Shield,
  ChevronRight,
  Filter,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { PermissionGuard } from '@/features/auth/guards';
import { PERMISSIONS } from '@/constants/permissions';
import { DataTable, Column } from '@/components/ui/data-table';
import { TableSkeleton } from '@/components/ui/tableSkeleton';
import { useUsers } from '@/services/users/queries';
import { UserRecord } from '@/services/users/types';
import UserManagementDrawer from './_components/UserManagementDrawer';

const KYC_EXEMPT_ROLES = ['STATE_OWNER'];

export default function UsersManagementPage() {
  const [search, setSearch] = useState('');
  const [roleFilter, setRoleFilter] = useState('');
  const [page, setPage] = useState(1);
  const [selectedUser, setSelectedUser] = useState<UserRecord | null>(null);

  const { data, isLoading, refetch } = useUsers({ page, limit: 10, search, role: roleFilter });

  console.log("USER DATA:", data)

  // Handles nested payload shape gracefully
  // const usersData = response?.items || response;

  const columns: Column<UserRecord>[] = [
    {
      header: 'System Username / ID',
      className: 'w-44 font-mono font-bold text-primary tracking-tight text-xs',
      cell: (user) => (
        <div className="flex flex-col">
          <span className="font-mono text-xs text-primary font-bold">
            {user.username || user.uuid.slice(0, 8).toUpperCase()}
          </span>
          <span className="text-[10px] text-muted-foreground/60 font-mono">
            ID: {user.id.slice(0, 8)}
          </span>
        </div>
      ),
    },
    {
      header: 'User Identity & Contact',
      className: 'min-w-[220px]',
      cell: (user) => (
        <div className="flex items-center gap-2.5 text-left">
          <div className="h-7 w-7 rounded-lg bg-primary/10 border border-primary/20 flex items-center justify-center text-xs font-bold text-primary shrink-0">
            {user.firstName[0]}
            {user.lastName[0]}
          </div>
          <div className="flex flex-col">
            <span className="text-foreground font-semibold tracking-tight text-xs">
              {user.firstName} {user.lastName}
            </span>
            <span className="text-[10px] text-muted-foreground/70 font-medium">
              {user.email} {user.phone ? `• ${user.phone}` : ''}
            </span>
          </div>
        </div>
      ),
    },
    {
      header: 'Assigned Role Tier',
      className: 'w-44',
      cell: (user) => (
        <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md bg-muted/40 border border-border/40 text-[10px] font-bold tracking-wider text-foreground uppercase">
          <Shield className="h-3 w-3 text-primary" />
          <span>{user.role.replace(/_/g, ' ')}</span>
        </span>
      ),
    },
    {
      header: 'KYC Verification',
      className: 'w-44',
      cell: (user) => {
        // Check if user role is exempt from personal KYC
        if (KYC_EXEMPT_ROLES.includes(user.role)) {
          return (
            <span className="inline-flex items-center gap-1 px-2.5 py-0.5 text-[10px] font-bold rounded-full bg-muted/30 text-muted-foreground/70 border border-border/30">
              <span>Not Applicable</span>
            </span>
          );
        }

        // Handle roles where KYC IS required but no record exists yet
        if (!user.kycRecord) {
          return (
            <span className="inline-flex items-center gap-1 px-2 py-0.5 text-[10px] font-bold rounded-full bg-amber-500/10 text-amber-500 border border-amber-500/20">
              <Clock className="h-3 w-3" />
              <span>Pending Upload</span>
            </span>
          );
        }
        
        const kycStatus = user.kycRecord?.status || 'PENDING';

        if (kycStatus === 'APPROVED') {
          return (
            <span className="inline-flex items-center gap-1 px-2 py-0.5 text-[10px] font-bold rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20">
              <CheckCircle2 className="h-3 w-3" />
              <span>Approved</span>
            </span>
          );
        }

        if (kycStatus === 'UNDER_REVIEW') {
          return (
            <div className="flex flex-col gap-0.5">
              <span className="inline-flex items-center gap-1 px-2 py-0.5 text-[10px] font-bold rounded-full bg-amber-500/10 text-amber-500 border border-amber-500/20 w-fit">
                <Clock className="h-3 w-3 animate-spin" />
                <span>Under Review</span>
              </span>
              {user.kycRecord?.assignedTo && (
                <span className="text-[9px] text-muted-foreground/60 pl-1">
                  Assigned: {user.kycRecord.assignedTo.firstName} (
                  {user.kycRecord.assignedTo.role})
                </span>
              )}
            </div>
          );
        }

        return (
          <span className="inline-flex items-center gap-1 px-2 py-0.5 text-[10px] font-bold rounded-full bg-destructive/10 text-destructive border border-destructive/20">
            <XCircle className="h-3 w-3" />
            <span>{kycStatus.replace(/_/g, ' ')}</span>
          </span>
        );
      },
    },
    {
      header: 'Account Status',
      className: 'w-28',
      cell: (user) => (
        <span
          className={`inline-flex items-center gap-1 px-2 py-0.5 text-[10px] font-bold rounded-full ${
            user.isActive
              ? 'bg-emerald-500/10 text-emerald-500 border border-emerald-500/20'
              : 'bg-muted/30 text-muted-foreground/70 border border-border/40'
          }`}
        >
          <span
            className={`h-1.5 w-1.5 rounded-full ${
              user.isActive ? 'bg-emerald-500' : 'bg-muted-foreground/40'
            }`}
          />
          <span>{user.isActive ? 'Active' : 'Inactive'}</span>
        </span>
      ),
    },
    {
      header: 'Actions',
      className: 'w-24 text-right',
      cell: (user) => (
        <Button
          variant="ghost"
          size="sm"
          onClick={() => setSelectedUser(user)}
          className="h-7 px-2 text-[10px] font-bold gap-1 text-primary hover:text-primary hover:bg-primary/10 cursor-pointer"
        >
          <span>Manage</span>
          <ChevronRight className="h-3 w-3" />
        </Button>
      ),
    },
  ];

  if (isLoading) return <TableSkeleton />;

  return (
    <>
    <div className="space-y-4 max-w-7xl mx-auto animate-in fade-in duration-300 select-none">
      <div className="flex items-center justify-between border-b border-border/10 pb-4">
        <div className="space-y-0.5">
          <h1 className="text-sm font-black tracking-widest text-foreground uppercase">
            System User Accounts
          </h1>
          <p className="text-[11px] font-medium text-muted-foreground/70">
            Manage provisioned users, monitor KYC verifications, and enforce RBAC access.
          </p>
        </div>

        {/* <PermissionGuard permission={PERMISSIONS.ROLES_CREATE}>
          <Button className="h-8 rounded-md px-3 text-[11px] font-bold tracking-wider uppercase shadow-sm gap-1.5 transition-all bg-foreground text-background hover:bg-foreground/90 cursor-pointer">
            <Plus className="h-3.5 w-3.5 stroke-[2.5]" /> Provision New User
          </Button>
        </PermissionGuard> */}
      </div>

      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="flex items-center max-w-xs w-full relative group">
          <Search className="absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground/60 transition-colors group-focus-within:text-primary" />
          <input
            type="text"
            placeholder="Search by name, email, or system code..."
            value={search}
            onChange={(e) => {
              setSearch(e.target.value);
              setPage(1);
            }}
            className="w-full text-xs font-medium pl-8 pr-3 py-2 border border-border/40 bg-surface rounded-lg text-foreground focus:outline-none focus:border-primary"
          />
        </div>

        <div className="flex items-center gap-2">
          <Filter className="h-3.5 w-3.5 text-muted-foreground/60" />
          <select
            value={roleFilter}
            onChange={(e) => {
              setRoleFilter(e.target.value);
              setPage(1);
            }}
            className="text-xs font-medium px-3 py-2 border border-border/40 bg-surface rounded-lg text-foreground focus:outline-none focus:border-primary cursor-pointer"
          >
            <option value="">All Role Tiers</option>
            <option value="STATE_OWNER">State Owner</option>
            <option value="DISTRICT_OWNER">District Owner</option>
            <option value="DISTRICT_SECTOR_OWNER">District-Sector Owner</option>
            <option value="INSTITUTE_ADMIN">Institute Admin</option>
            <option value="CAREER_ADVISOR">Career Advisor</option>
          </select>
        </div>
      </div>

      <DataTable
        data={data?.items || []}
        columns={columns}
        emptyMessage="No system users found matching current filters."
        pagination={
          data
            ? {
                page: data.page,
                pages: data.pages,
                total: data.total,
                onPageChange: setPage,
              }
            : undefined
        }
      />
    </div>

    {selectedUser && (
      <UserManagementDrawer
        user={selectedUser}
        onClose={() => setSelectedUser(null)}
        onRefresh={() => {
          refetch();
        }}
      />
      
    )}
    </>
  );
}