"use client";

import { useEffect, useState } from "react";

import axios from "axios";

import Cookies from "js-cookie";

import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/shadcnui/card";

import { Button } from "@/components/shadcnui/button";

import { Input } from "@/components/shadcnui/input";

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/shadcnui/table";

interface SalesPersonType {
  _id: string;
  name: string;
  mobile: string;
}

interface UserType {
  _id: string;
  name: string;
  mobile: string;
  email: string;
  address: string;
  pin: string;
  role: string;
  status: string;
  isMobileVerified: boolean;
  isEmailVerified?: boolean;
  createdAt: string;
  salesPerson?: SalesPersonType | null;
}

interface PaginationType {
  currentPage: number;
  totalPages: number;
  totalUsers: number;
  limit: number;
}

const UsersForm = () => {
  const token = Cookies.get("kero_token");

  const [users, setUsers] = useState<UserType[]>([]);

  const [loading, setLoading] = useState(false);

  const [page, setPage] = useState(1);

  const [limit, setLimit] = useState(10);

  const [search, setSearch] = useState("");

  const [statusFilter, setStatusFilter] = useState<
    "ALL" | "ACTIVE" | "INACTIVE"
  >("ALL");

  const [updatingStatus, setUpdatingStatus] = useState<string | null>(null);

  const [pagination, setPagination] = useState<PaginationType>({
    currentPage: 1,
    totalPages: 1,
    totalUsers: 0,
    limit: 10,
  });

  const getAllUsers = async (currentPage = page) => {
    try {
      setLoading(true);

      const params = new URLSearchParams();

      params.append("page", currentPage.toString());

      params.append("limit", limit.toString());

      if (search.trim()) {
        params.append("search", search.trim());
      }

      if (statusFilter !== "ALL") {
        params.append("status", statusFilter);
      }

      const response = await axios.get(
        `${process.env.NEXT_PUBLIC_API_BASE_URL}/users/all_users?${params.toString()}`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      );

      if (response.data.success) {
        const usersWithDefaultStatus = response.data.data.map(
          (user: UserType) => ({
            ...user,
            status: user.status || "ACTIVE",
          }),
        );

        setUsers(usersWithDefaultStatus);

        setPagination(response.data.pagination);
      }
    } catch (error) {
      console.log("GET ALL USERS ERROR:", error);
    } finally {
      setLoading(false);
    }
  };

  /*
   * Initial load
   * Also reload when limit or status filter changes.
   */
  useEffect(() => {
    setPage(1);

    getAllUsers(1);
  }, [limit, statusFilter]);

  /*
   * When search is cleared,
   * automatically reload all users.
   */
  useEffect(() => {
    if (search.trim() === "") {
      setPage(1);

      getAllUsers(1);
    }
  }, [search]);

  /*
   * Search button
   */
  const handleSearch = () => {
    setPage(1);

    getAllUsers(1);
  };

  /*
   * Status filter
   */
  const handleStatusFilterChange = (value: "ALL" | "ACTIVE" | "INACTIVE") => {
    setStatusFilter(value);

    setPage(1);
  };

  /*
   * Change individual user's status
   */
  const handleStatusChange = async (
    userId: string,
    newStatus: "ACTIVE" | "INACTIVE",
  ) => {
    try {
      setUpdatingStatus(userId);

      const response = await axios.patch(
        `${process.env.NEXT_PUBLIC_API_BASE_URL}/users/${userId}/status`,
        {
          status: newStatus,
        },
        {
          headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json",
          },
        },
      );

      if (response.data.success) {
        setUsers((prevUsers) =>
          prevUsers.map((user) =>
            user._id === userId ?
              {
                ...user,
                status: newStatus,
              }
            : user,
          ),
        );
      }
    } catch (error) {
      console.log("UPDATE USER STATUS ERROR:", error);

      alert("Failed to update user status.");
    } finally {
      setUpdatingStatus(null);
    }
  };

  /*
   * Next page
   */
  const nextPage = () => {
    if (page < pagination.totalPages) {
      const next = page + 1;

      setPage(next);

      getAllUsers(next);
    }
  };

  /*
   * Previous page
   */
  const prevPage = () => {
    if (page > 1) {
      const prev = page - 1;

      setPage(prev);

      getAllUsers(prev);
    }
  };

  return (
    <Card className="mt-6">
      <CardHeader>
        <CardTitle>All Users</CardTitle>
      </CardHeader>

      <CardContent className="space-y-6">
        {/* SEARCH + FILTER + LIMIT */}
        <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
          {/* SEARCH */}
          <div className="flex w-full flex-col gap-3 md:flex-row">
            <Input
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Search by name, mobile, role"
              className="max-w-md"
            />

            <Button onClick={handleSearch}>Search</Button>

            <div className="">
              Filter User by Status : {/* STATUS FILTER */}
              <select
                value={statusFilter}

                onChange={(e) =>
                  handleStatusFilterChange(
                    e.target.value as "ALL" | "ACTIVE" | "INACTIVE",
                  )
                }
                className="bg-background h-9 rounded-md border px-3 text-sm">
                <option value="ALL">All Users</option>
                <option value="ACTIVE">ACTIVE</option>
                <option value="INACTIVE">INACTIVE</option>
              </select>
            </div>
          </div>

          <div className="flex flex-col items-end justify-end gap-3">
            {/* FILTER + TOTAL + LIMIT */}
            <div className="flex items-center gap-3">
              {/* LIMIT */}
              <div className="w-36"> Show User per page :</div>
              <select
                value={limit}
                onChange={(e) => setLimit(Number(e.target.value))}
                className="bg-background h-9 rounded-md border px-3 text-sm">
                <option value={10}>10</option>

                <option value={20}>20</option>

                <option value={50}>50</option>

                <option value={100}>100</option>
              </select>
              {/* TOTAL USERS */}
            </div>
            <p className="text-sm whitespace-nowrap">
              Total Users: {pagination.totalUsers}
            </p>
          </div>
        </div>

        {/* USERS TABLE */}
        <div className="overflow-x-auto rounded-xl border px-1">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Name</TableHead>

                <TableHead>Mobile</TableHead>

                <TableHead>Email</TableHead>

                <TableHead>Role</TableHead>

                <TableHead>Status</TableHead>

                <TableHead>Address</TableHead>

                <TableHead>Pin</TableHead>

                <TableHead>Mobile Verified</TableHead>

                <TableHead>Sales Person</TableHead>

                <TableHead>Created At</TableHead>
              </TableRow>
            </TableHeader>

            <TableBody>
              {users.map((item) => (
                <TableRow key={item._id}>
                  {/* NAME */}
                  <TableCell>{item.name || "-"}</TableCell>

                  {/* MOBILE */}
                  <TableCell>{item.mobile || "-"}</TableCell>

                  {/* EMAIL */}
                  <TableCell>{item.email || "-"}</TableCell>

                  {/* ROLE */}
                  <TableCell>{item.role || "-"}</TableCell>

                  {/* STATUS */}
                  <TableCell>
                    <select
                      value={item.status || "ACTIVE"}
                      disabled={updatingStatus === item._id}
                      onChange={(e) =>
                        handleStatusChange(
                          item._id,
                          e.target.value as "ACTIVE" | "INACTIVE",
                        )
                      }
                      className={`h-9 rounded-md border px-3 text-sm font-medium outline-none ${
                        item.status === "INACTIVE" ?
                          "border-red-300 bg-red-50 text-red-700"
                        : "border-green-300 bg-green-50 text-green-700"
                      }`}>
                      <option value="ACTIVE">ACTIVE</option>

                      <option value="INACTIVE">INACTIVE</option>
                    </select>

                    {updatingStatus === item._id && (
                      <span className="text-muted-foreground ml-2 text-xs">
                        Updating...
                      </span>
                    )}
                  </TableCell>

                  {/* ADDRESS */}
                  <TableCell className="min-w-52">
                    {item.address || "-"}
                  </TableCell>

                  {/* PIN */}
                  <TableCell>{item.pin || "-"}</TableCell>

                  {/* MOBILE VERIFIED */}
                  <TableCell>{item.isMobileVerified ? "YES" : "NO"}</TableCell>

                  {/* SALES PERSON */}
                  <TableCell>{item.salesPerson?.name || "-"}</TableCell>

                  {/* CREATED AT */}
                  <TableCell className="min-w-44">
                    {new Date(item.createdAt).toLocaleString()}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>

        {/* NO USERS */}
        {!loading && users.length === 0 && (
          <div className="text-muted-foreground py-6 text-center text-sm">
            No users found.
          </div>
        )}

        {/* PAGINATION */}
        <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
          <div className="text-muted-foreground text-sm">
            Page {pagination.currentPage} of {pagination.totalPages}
          </div>

          <div className="flex items-center gap-3">
            <Button
              variant="outline"
              onClick={prevPage}
              disabled={page === 1 || loading}>
              Previous
            </Button>

            <Button
              onClick={nextPage}
              disabled={page === pagination.totalPages || loading}>
              Next
            </Button>
          </div>
        </div>

        {/* LOADING */}
        {loading && <div className="text-center text-sm">Loading users...</div>}
      </CardContent>
    </Card>
  );
};

export default UsersForm;
