"use client";

import { getBranches, deleteBranch } from "@/Services/Branches/ApiBranches";
import { useQuery } from "@tanstack/react-query";
import { DataTable } from "@/components/ui/DataTableNew";
import { useModal } from "@/context/ModalProvider";
import AddBranchForm from "./AddBranch";

export default function BranchManagement() {
  const { openModal, closeModal } = useModal();

  const { data: branches = [] } = useQuery({
    queryKey: ["branches"],
    queryFn: getBranches,
  });

  const columns = [
    {
      accessorKey: "location_type",
      header: "Type",
      cell: (info) => (
        <span
          className={`inline-block px-2 py-1 rounded-full text-xs font-medium ${
            info.getValue() === "branch"
              ? "bg-brand-gold/20 text-brand-gold"
              : info.getValue() === "franchise"
              ? "bg-blue-500/20 text-blue-600"
              : "bg-purple-500/20 text-purple-600"
          }`}
        >
          {info.getValue().charAt(0).toUpperCase() + info.getValue().slice(1)}
        </span>
      ),
    },
    {
      accessorKey: "name",
      header: "Name",
      cell: (info) => info.getValue() || "-",
    },
    {
      accessorKey: "city",
      header: "City",
      cell: (info) => info.getValue(),
    },
    {
      accessorKey: "state",
      header: "State",
      cell: (info) => info.getValue() || "-",
    },
    {
      accessorKey: "phone",
      header: "Phone",
      cell: (info) => info.getValue() || "-",
    },
    {
      accessorKey: "is_active",
      header: "Status",
      cell: (info) => (info.getValue() == 1 ? "Active" : "Inactive"),
    },
  ];

  return (
    <div>
      <AddBranchForm type="add" onClose={closeModal} />

      <DataTable
        title="Manage Branches"
        fetchData={getBranches}
        columnsConfig={columns}
        tag="branches"
        onDelete={deleteBranch}
        EditComponent={AddBranchForm}
      />
    </div>
  );
}
