"use client";

import { useState, useCallback } from "react";
import { Card, Badge, Button, ConfirmModal } from "@/shared/components";
import AddUserModal from "./AddUserModal";
import Link from "next/link";
import { format } from "date-fns";

export default function UsersPage({ initialUsers = [] }) {
  const [users, setUsers] = useState(initialUsers);
  const [error, setError] = useState("");
  const [confirmState, setConfirmState] = useState(null);
  const [addUserOpen, setAddUserOpen] = useState(false);

  const fetchUsers = useCallback(async () => {
    try {
      setError("");
      const res = await fetch("/api/users");
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || "Failed to fetch users");
      }
      const data = await res.json();
      setUsers(data.users || []);
    } catch (err) {
      setError(err.message || "An error occurred");
    }
  }, []);

  const handleApprove = async (id) => {
    try {
      const res = await fetch(`/api/users/${id}/approve`, { method: "POST" });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || "Failed to approve user");
      }
      await fetchUsers();
    } catch (err) {
      setError(err.message);
    }
  };

  const handleDelete = (user) => {
    setConfirmState({
      title: "Delete User",
      message: `Delete user "${user.username}"? This will also remove their API keys and rate limits.`,
      variant: "danger",
      onConfirm: async () => {
        setConfirmState(null);
        try {
          const res = await fetch(`/api/users/${user.id}`, { method: "DELETE" });
          if (!res.ok) {
            const data = await res.json();
            throw new Error(data.error || "Failed to delete user");
          }
          await fetchUsers();
        } catch (err) {
          setError(err.message);
        }
      },
    });
  };

  if (error) {
    return (
      <div className="flex min-w-0 flex-col gap-6 px-1 sm:px-0">
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
          <div className="min-w-0">
            <h1 className="text-2xl font-semibold">Team Members</h1>
            <p className="text-sm text-text-muted mt-1">Manage team access and permissions</p>
          </div>
          <Button variant="primary" icon="person_add" onClick={() => setAddUserOpen(true)}>
            Add User
          </Button>
        </div>
        <Card>
          <div className="text-center py-12">
            <p className="text-red-500 mb-4">{error}</p>
            <Button variant="outline" onClick={fetchUsers}>Retry</Button>
          </div>
        </Card>
      </div>
    );
  }

  return (
    <div className="flex min-w-0 flex-col gap-6 px-1 sm:px-0">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div className="min-w-0">
          <h1 className="text-2xl font-semibold">Users</h1>
          <p className="text-sm text-text-muted mt-1">
            Manage user accounts and permissions
          </p>
        </div>
        <Button variant="primary" icon="person_add" onClick={() => setAddUserOpen(true)}>
          Add User
        </Button>
      </div>

      {users.length === 0 ? (
        <Card>
          <div className="text-center py-12">
            <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/10 text-primary mb-4">
              <span className="material-symbols-outlined text-[32px]">group</span>
            </div>
            <p className="text-text-main font-medium mb-1">No users yet</p>
            <p className="text-sm text-text-muted">
              Users will appear here once registered and approved
            </p>
          </div>
        </Card>
      ) : (
        <div className="flex flex-col gap-4" data-testid="users-table">
          {users.map((user) => (
            <UserRow
              key={user.id}
              user={user}
              onApprove={() => handleApprove(user.id)}
              onDelete={() => handleDelete(user)}
            />
          ))}
        </div>
      )}

      <ConfirmModal
        isOpen={!!confirmState}
        onClose={() => setConfirmState(null)}
        onConfirm={confirmState?.onConfirm}
        title={confirmState?.title || "Confirm"}
        message={confirmState?.message}
        variant={confirmState?.variant || "danger"}
      />

      <AddUserModal
        isOpen={addUserOpen}
        onClose={() => setAddUserOpen(false)}
        onSuccess={fetchUsers}
      />
    </div>
  );
}

function UserRow({ user, onApprove, onDelete }) {
  const statusVariant = user.is_approved ? "success" : user.is_active ? "warning" : "error";
  const statusLabel = user.is_approved ? "Approved" : user.is_active ? "Pending" : "Disabled";

  return (
    <Card padding="sm" className="group">
      <div className="flex min-w-0 flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex min-w-0 flex-1 items-start gap-3 sm:items-center">
          <div className="size-8 rounded-lg bg-primary/10 flex items-center justify-center shrink-0">
            <span className="material-symbols-outlined text-primary text-[18px]">person</span>
          </div>
          <div className="min-w-0 flex-1">
            <div className="flex items-center gap-2">
              <span className="font-medium text-sm text-text-main truncate">
                {user.username}
              </span>
              <Badge variant={user.role === "admin" ? "primary" : "default"} size="sm">
                {user.role}
              </Badge>
              <Badge variant={statusVariant} size="sm" dot>
                {statusLabel}
              </Badge>
            </div>
            <p className="text-xs text-text-muted mt-0.5">
              Created {format(new Date(user.created_at), "MMM d, yyyy")}
            </p>
          </div>
        </div>

        <div className="flex items-center gap-2 shrink-0">
          {!user.is_approved && (
            <Button size="sm" variant="success" icon="check" onClick={onApprove} data-testid={`approve-btn-${user.id}`}>
              Approve
            </Button>
          )}
          <Link href={`/dashboard/users/${user.id}`}>
            <Button size="sm" variant="ghost" icon="edit">Edit</Button>
          </Link>
          <Button size="sm" variant="danger" icon="delete" onClick={onDelete} data-testid={`delete-btn-${user.id}`}>
            Delete
          </Button>
        </div>
      </div>
    </Card>
  );
}
