// pages/Users.js
import { useEffect, useMemo, useState } from "react";
import axios from "axios";

import UsersHeader from "@/Components/Users/UsersHeader";
import UsersFilters from "@/Components/Users/UsersFilters";
import UsersTable from "@/Components/Users/UsersTable";
import UserModal from "@/Components/Users/UserModal";
import ConfirmDialog from "@/Components/Users/ConfirmDialog";

const ROLE_ADMIN = 1;
const ROLE_USER = 2;

const token = process.env.NEXT_PUBLIC_SECRET_TOKEN;

// Axios client (Bearer token)
const api = axios.create({
  headers: {
    Authorization: token ? `Bearer ${token}` : "",
  },
});

export default function UsersPage() {
  const [users, setUsers] = useState([]);
  const [loadingList, setLoadingList] = useState(true);

  const [query, setQuery] = useState("");
  const [roleFilter, setRoleFilter] = useState("all");

  const [modalOpen, setModalOpen] = useState(false);
  const [editing, setEditing] = useState(null);
  const [saving, setSaving] = useState(false);

  const [confirmOpen, setConfirmOpen] = useState(false);
  const [deleting, setDeleting] = useState(null);
  const [deletingBusy, setDeletingBusy] = useState(false);

  const fetchUsers = async () => {
    setLoadingList(true);
    try {
      const res = await api.get("/api/Users");
      setUsers(res.data?.users || []);
    } catch (e) {
      console.error("fetch users error:", e);
      setUsers([]);
    } finally {
      setLoadingList(false);
    }
  };

  // ✅ initial fetch
  useEffect(() => {
    fetchUsers();
  }, []);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();

    return users.filter((u) => {
      const matchesQuery =
        !q ||
        String(u.id).toLowerCase().includes(q) ||
        String(u.name || "").toLowerCase().includes(q);

      const matchesRole =
        roleFilter === "all"
          ? true
          : Number(roleFilter) === Number(u.role);

      return matchesQuery && matchesRole;
    });
  }, [users, query, roleFilter]);

  const openCreate = () => {
    setEditing(null);
    setModalOpen(true);
  };

  const openEdit = async (u) => {
    try {
      const res = await api.get(`/api/Users/${u.id}`);
      setEditing(res.data?.user || u);
    } catch (e) {
      console.error("fetch user error:", e);
      setEditing(u);
    } finally {
      setModalOpen(true);
    }
  };

  const askDelete = (u) => {
    setDeleting(u);
    setConfirmOpen(true);
  };

  // ✅ DELETE /api/users/:id
  const confirmDelete = async () => {
    if (!deleting) return;

    setDeletingBusy(true);
    try {
      await api.delete(`/api/Users/${deleting.id}`);
      setUsers((prev) => prev.filter((x) => x.id !== deleting.id));
      console.log("deleted user", deleting.id);
      setConfirmOpen(false);
      setDeleting(null);
    } catch (e) {
      console.error("delete user error:", e);
    } finally {
      setDeletingBusy(false);
    }
  };

  const onSubmitUser = async (payload) => {
    // payload: { name, pass, role }
    const safeRole =
      Number(payload.role) === ROLE_ADMIN ? ROLE_ADMIN : ROLE_USER;

    setSaving(true);
    try {
      if (editing) {
        const res = await api.put(`/api/Users/${editing.id}`, {
          name: payload.name,
          role: safeRole,
          // pass optional: only send if user typed it
          ...(payload.pass ? { pass: payload.pass } : {}),
        });

        const updated = res.data?.user;
        if (updated) {
          setUsers((prev) =>
            prev.map((u) => (u.id === updated.id ? updated : u))
          );
        } else {
          await fetchUsers();
        }
      } else {
        const res = await api.post("/api/Users", {
          name: payload.name,
          pass: payload.pass,
          role: safeRole,
        });

        const created = res.data?.user;
        if (created) {
          setUsers((prev) => [created, ...prev]);
        } else {
          await fetchUsers();
        }
      }

      setModalOpen(false);
      setEditing(null);
    } catch (e) {
      console.error("save user error:", e);
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="min-h-screen bg-[#fafafa] p-4 sm:p-6 lg:p-8">
      <UsersHeader onCreate={openCreate} />

      <UsersFilters
        query={query}
        onQuery={setQuery}
        roleFilter={roleFilter}
        onRole={setRoleFilter}
        total={filtered.length}
      />

      <UsersTable
        users={filtered}
        onEdit={openEdit}
        onDelete={askDelete}
        loading={loadingList} // optional: if your table supports it
      />

      <UserModal
        open={modalOpen}
        mode={editing ? "edit" : "create"}
        initialData={editing}
        saving={saving} // optional: if your modal supports it
        onClose={() => {
          setModalOpen(false);
          setEditing(null);
        }}
        onSubmit={onSubmitUser}
      />

      <ConfirmDialog
        open={confirmOpen}
        title="Kullanıcıyı Sil"
        description={
          deleting ? `"${deleting.name}" kullanıcısını silmek istiyor musunuz?` : ""
        }
        confirmText={deletingBusy ? "Siliniyor..." : "Sil"}
        cancelText="İptal"
        danger
        disabled={deletingBusy} // optional: if your dialog supports it
        onCancel={() => {
          if (deletingBusy) return;
          setConfirmOpen(false);
          setDeleting(null);
        }}
        onConfirm={confirmDelete}
      />
    </div>
  );
}