"use client";

import { useState, useMemo } from "react";
import {
  UserCog,
  Plus,
  Search,
  Edit3,
  Trash2,
  Mail,
  ChevronLeft,
  ChevronRight,
  MoreVertical,
  Shield,
  Loader2,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import type {
  ManageUserResponseDTO,
  SystemRole,
  UserStatus,
} from "../dtos/manage-users.dto";

// ============================================
// Role Badge
// ============================================
function RoleBadge({ role }: { role: SystemRole }) {
  const styles: Record<SystemRole, string> = {
    super_admin: "bg-purple-50 text-purple-700 border-purple-200",
    it_team: "bg-blue-50 text-blue-700 border-blue-200",
    delivery_management: "bg-orange-50 text-orange-700 border-orange-200",
    department_user: "bg-emerald-50 text-emerald-700 border-emerald-200",
  };

  const labels: Record<SystemRole, string> = {
    super_admin: "Super Admin",
    it_team: "IT Team",
    delivery_management: "Delivery Mgmt",
    department_user: "Dept User",
  };

  return (
    <span
      className={`inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-xs font-medium ${styles[role]}`}
    >
      <Shield className="h-3 w-3" />
      {labels[role] ?? String(role).replace(/_/g, " ").replace(/\b\w/g, (letter) => letter.toUpperCase())}
    </span>
  );
}

// ============================================
// Status Badge
// ============================================
function StatusBadge({ status }: { status: UserStatus }) {
  const styles: Record<UserStatus, string> = {
    active: "bg-emerald-50 text-emerald-700 border-emerald-200",
    inactive: "bg-red-50 text-red-700 border-red-200",
  };

  return (
    <span
      className={`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium capitalize ${styles[status]}`}
    >
      {status}
    </span>
  );
}

// ============================================
// Skeleton Loader
// ============================================
function SkeletonTable() {
  return (
    <div className="space-y-3">
      {Array.from({ length: 5 }).map((_, i) => (
        <div
          key={i}
          className="flex items-center gap-4 rounded-lg border border-gray-200 bg-gray-50 p-4"
        >
          <div className="h-10 w-10 animate-pulse rounded-full bg-gray-200" />
          <div className="flex-1 space-y-2">
            <div className="h-4 w-32 animate-pulse rounded bg-gray-200" />
            <div className="h-3 w-48 animate-pulse rounded bg-gray-200" />
          </div>
          <div className="h-6 w-20 animate-pulse rounded-full bg-gray-200" />
        </div>
      ))}
    </div>
  );
}

// ============================================
// Empty State
// ============================================
function EmptyState({ searchQuery }: { searchQuery?: string }) {
  return (
    <div className="flex flex-col items-center justify-center py-16">
      <div className="mb-4 inline-flex h-16 w-16 items-center justify-center rounded-2xl bg-gray-100">
        <UserCog className="h-8 w-8 text-gray-400" />
      </div>
      <h3 className="mb-1 text-lg font-semibold text-gray-900">
        {searchQuery ? "No users found" : "No users yet"}
      </h3>
      <p className="text-sm text-gray-500">
        {searchQuery
          ? "Try adjusting your search criteria."
          : "Add your first user to get started."}
      </p>
    </div>
  );
}

// ============================================
// Actions Dropdown
// ============================================
function ActionsDropdown({
  user,
  onEdit,
  onDelete,
}: {
  user: ManageUserResponseDTO;
  onEdit: (user: ManageUserResponseDTO) => void;
  onDelete: (user: ManageUserResponseDTO) => void;
}) {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <div className="relative">
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600"
      >
        <MoreVertical className="h-4 w-4" />
      </button>
      {isOpen && (
        <>
          <div
            className="fixed inset-0 z-10"
            onClick={() => setIsOpen(false)}
          />
          <div className="absolute right-0 z-20 mt-1 w-48 rounded-lg border border-gray-200 bg-white py-1 shadow-lg">
            <button
              onClick={() => {
                onEdit(user);
                setIsOpen(false);
              }}
              className="flex w-full items-center gap-2 px-3 py-2 text-sm text-gray-700 hover:bg-gray-50"
            >
              <Edit3 className="h-4 w-4" />
              Edit User
            </button>
            <button
              onClick={() => {
                onDelete(user);
                setIsOpen(false);
              }}
              className="flex w-full items-center gap-2 px-3 py-2 text-sm text-red-600 hover:bg-red-50"
            >
              <Trash2 className="h-4 w-4" />
              Delete User
            </button>
          </div>
        </>
      )}
    </div>
  );
}

// ============================================
// Manage Users List Props
// ============================================
interface ManageUsersListProps {
  users: ManageUserResponseDTO[];
  isLoading: boolean;
  error: string | null;
  searchQuery: string;
  onSearchChange: (query: string) => void;
  onAdd: () => void;
  onEdit: (user: ManageUserResponseDTO) => void;
  onDelete: (user: ManageUserResponseDTO) => void;
  page: number;
  totalPages: number;
  totalUsers: number;
  onPageChange: (page: number) => void;
}

// ============================================
// Manage Users List Component
// ============================================
export function ManageUsersList({
  users,
  isLoading,
  error,
  searchQuery,
  onSearchChange,
  onAdd,
  onEdit,
  onDelete,
  page,
  totalPages,
  totalUsers,
  onPageChange,
}: ManageUsersListProps) {
  return (
    <div className="rounded-2xl border border-gray-200 bg-white">
      {/* Header */}
      <div className="border-b border-gray-200 px-6 py-4">
        <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <h2 className="text-lg font-semibold text-gray-900">Manage Users</h2>
            <p className="text-sm text-gray-500">
              {totalUsers} user{totalUsers !== 1 ? "s" : ""} total
            </p>
          </div>
          <div className="flex items-center gap-3">
            {/* Search */}
            <div className="relative">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
              <input
                type="text"
                placeholder="Search users..."
                value={searchQuery}
                onChange={(e) => onSearchChange(e.target.value)}
                className="w-64 rounded-lg border border-gray-200 bg-gray-50 py-2 pl-10 pr-4 text-sm text-gray-900 placeholder:text-gray-400 focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500"
              />
            </div>
            {/* Add Button */}
            <Button onClick={onAdd} className="flex items-center gap-2">
              <Plus className="h-4 w-4" />
              Add User
            </Button>
          </div>
        </div>
      </div>

      {/* Content */}
      <div className="p-6">
        {/* P3: Loading → skeleton */}
        {isLoading ? (
          <SkeletonTable />
        ) : error ? (
          <div className="rounded-xl border border-red-200 bg-red-50 p-4">
            <p className="text-sm text-red-600">{error}</p>
          </div>
        ) : users.length === 0 ? (
          <EmptyState searchQuery={searchQuery} />
        ) : (
          <>
            {/* Users Table */}
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-gray-100">
                    <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
                      User
                    </th>
                    <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
                      Contact
                    </th>
                    <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
                      Role
                    </th>
                    <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
                      Status
                    </th>
                    <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
                      Last Login
                    </th>
                    <th className="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500">
                      Actions
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100">
                  {users.map((user) => (
                    <tr key={user.id} className="hover:bg-gray-50">
                      <td className="whitespace-nowrap px-4 py-4">
                        <div className="flex items-center gap-3">
                          <div className="flex h-9 w-9 items-center justify-center rounded-full bg-blue-50 border border-blue-200 text-sm font-medium text-blue-600">
                            {user.name
                              .split(" ")
                              .map((n) => n[0])
                              .join("")
                              .toUpperCase()
                              .slice(0, 2)}
                          </div>
                          <div>
                            <p className="text-sm font-medium text-gray-900">
                              {user.name}
                            </p>
                            <p className="text-xs text-gray-500">{user.id}</p>
                          </div>
                        </div>
                      </td>
                      <td className="whitespace-nowrap px-4 py-4">
                        <div className="flex items-center gap-1.5 text-sm text-gray-600">
                          <Mail className="h-3.5 w-3.5 text-gray-400" />
                          {user.email}
                        </div>
                      </td>
                      <td className="whitespace-nowrap px-4 py-4">
                        <RoleBadge role={user.role} />
                      </td>
                      <td className="whitespace-nowrap px-4 py-4">
                        <StatusBadge status={user.status} />
                      </td>
                      <td className="whitespace-nowrap px-4 py-4 text-sm text-gray-500">
                        {user.lastLoginAt
                          ? new Date(user.lastLoginAt).toLocaleDateString(
                              "en-IN",
                              {
                                day: "numeric",
                                month: "short",
                                year: "numeric",
                              }
                            )
                          : "Never"}
                      </td>
                      <td className="whitespace-nowrap px-4 py-4 text-right">
                        <ActionsDropdown
                          user={user}
                          onEdit={onEdit}
                          onDelete={onDelete}
                        />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {/* Pagination */}
            {totalPages > 1 && (
              <div className="mt-4 flex items-center justify-between border-t border-gray-100 pt-4">
                <p className="text-sm text-gray-500">
                  Page {page} of {totalPages}
                </p>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => onPageChange(page - 1)}
                    disabled={page <= 1}
                    className="inline-flex items-center gap-1 rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50"
                  >
                    <ChevronLeft className="h-4 w-4" />
                    Previous
                  </button>
                  <button
                    onClick={() => onPageChange(page + 1)}
                    disabled={page >= totalPages}
                    className="inline-flex items-center gap-1 rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50"
                  >
                    Next
                    <ChevronRight className="h-4 w-4" />
                  </button>
                </div>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}
