"use client";

import { PageLoading } from "@/components/page-loading";

import { displayValue, formatDate, statusLabel } from "@/lib/display-format";

import { useState } from "react";
import {
  UserCog,
  Plus,
  Search,
  Edit3,
  Eye,
  Mail,
  ChevronLeft,
  ChevronRight,
  Shield,
  Power,
} from "lucide-react";
import { ActionMenu } from "@/components/ui/action-menu";
import { Button } from "@/components/ui/button";
import type {
  ManageUserResponseDTO,
  UserStatus,
} from "../dtos/manage-users.dto";

// ============================================
// Role Badge
// ============================================
function RoleBadge({ role, name }: { role: string; name?: string }) {
  const styles: Record<string, 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<string, string> = {
    super_admin: "Super Admin",
    it_team: "IT Team",
    delivery_management: "Delivery Mgmt",
    department_user: "Community 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] ?? "bg-gray-50 text-gray-700 border-gray-200"}`}
    >
      <Shield className="h-3 w-3" />
      {role === "department_user" ? labels.department_user : name ?? 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]}`}
    >
      {statusLabel(status)}
    </span>
  );
}

// ============================================
// Skeleton Loader
// ============================================
function SkeletonTable() {
  return <PageLoading label="Loading users..." />;
}

// ============================================
// 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,
  onView,
  onEdit,
  onStatusChange,
}: {
  user: ManageUserResponseDTO;
  onView: (user: ManageUserResponseDTO) => void;
  onEdit: (user: ManageUserResponseDTO) => void;
  onStatusChange: (user: ManageUserResponseDTO) => void;
}) {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <ActionMenu open={isOpen} onOpenChange={setIsOpen} label={"Actions for " + user.name}>

      {user.canView && <button type="button" onClick={() => { onView(user); setIsOpen(false); }} className="flex w-full items-center gap-2 px-3 py-2 text-sm text-gray-700 hover:bg-gray-50"><Eye className="h-4 w-4" />View User</button>}
      {user.canEdit && <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>}
      {user.canEdit && <button type="button" onClick={() => { onStatusChange(user); setIsOpen(false); }} className="flex w-full items-center gap-2 px-3 py-2 text-sm text-gray-700 hover:bg-gray-50"><Power className="h-4 w-4" />{user.status === "active" ? "Deactivate User" : "Reactivate User"}</button>}

    </ActionMenu>
  );
}

// ============================================
// Manage Users List Props
// ============================================
interface ManageUsersListProps {
  onStatusChange: (user: ManageUserResponseDTO) => void;
  users: ManageUserResponseDTO[];
  isLoading: boolean;
  error: string | null;
  searchQuery: string;
  onSearchChange: (query: string) => void;
  onAdd: () => void;
  onView: (user: ManageUserResponseDTO) => void;
  canCreate?: boolean;
  companyContext?: boolean;
  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({
  onStatusChange,
  users,
  isLoading,
  error,
  searchQuery,
  onSearchChange,
  onAdd,
  onView,
  canCreate = false,
  companyContext = false,
  onEdit,
  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">{companyContext ? "Company Users" : "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 */}
            {canCreate && <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 && users.length === 0 ? (
          <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>
                    {companyContext && <><th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Company</th><th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Community</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">
                              {displayValue(user.name)}
                            </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" />
                          {displayValue(user.email)}
                        </div>
                      </td>
                      <td className="whitespace-nowrap px-4 py-4">
                        <RoleBadge role={user.role} name={user.roleName} />
                      </td>
                      {companyContext && <><td className="px-4 py-4 text-sm text-gray-600">{displayValue(user.companyName)}</td><td className="px-4 py-4 text-sm text-gray-600">{displayValue(user.communityNames?.join(", ") || user.communityName)}</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
                          ? formatDate(user.lastLoginAt)
                          : "Never"}
                      </td>
                      <td className="whitespace-nowrap px-4 py-4 text-right">
                        {(user.canView || user.canEdit) && <ActionsDropdown
                          user={user}
                          onView={onView}
                          onEdit={onEdit}
                          onStatusChange={onStatusChange}
                        />}
                      </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>
  );
}

