"use client";

import { useMemo, useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { Trash2, Plus } from "lucide-react";
import { apiGet } from "@/lib/api/client";
import {
  listBranchRoles,
  assignBranchRole,
  updateBranchRole,
  removeBranchRole,
  type BranchRoleAssignment,
} from "@/lib/api/branch-roles";
import { roleKey } from "@/lib/role-label";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";

interface Employee {
  id: string;
  name: string;
  phone: string;
  role: string;
}

interface Branch {
  id: string;
  name: string;
}

/** Branch-level roles an employee can be assigned (Owner is café-wide, excluded). */
const ASSIGNABLE_ROLES = ["Manager", "Cashier", "Waiter", "Chef", "Delivery"] as const;

export function BranchAccessPanel({ cafeId }: { cafeId: string }) {
  const t = useTranslations("branchAccess");
  const tRoles = useTranslations("roles");
  const queryClient = useQueryClient();
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [newBranchId, setNewBranchId] = useState("");
  const [newRole, setNewRole] = useState<string>("Cashier");

  const { data: employees = [] } = useQuery({
    queryKey: ["employees", cafeId],
    queryFn: () => apiGet<Employee[]>(`/api/cafes/${cafeId}/employees`),
    enabled: !!cafeId,
  });

  const { data: branches = [] } = useQuery({
    queryKey: ["branches", cafeId],
    queryFn: () => apiGet<Branch[]>(`/api/cafes/${cafeId}/branches`),
    enabled: !!cafeId,
  });

  const selected = employees.find((e) => e.id === selectedId) ?? null;
  const isOwner = selected?.role === "Owner";

  const { data: assignments = [], isPending: loadingAssignments } = useQuery({
    queryKey: ["branch-roles", cafeId, selectedId],
    queryFn: () => listBranchRoles(cafeId, selectedId!),
    enabled: !!cafeId && !!selectedId && !isOwner,
  });

  const invalidate = () =>
    queryClient.invalidateQueries({ queryKey: ["branch-roles", cafeId, selectedId] });

  const assign = useMutation({
    mutationFn: () => assignBranchRole(cafeId, selectedId!, { branchId: newBranchId, role: newRole }),
    onSuccess: () => {
      setNewBranchId("");
      invalidate();
    },
  });

  const update = useMutation({
    mutationFn: (vars: { assignmentId: string; role: string }) =>
      updateBranchRole(cafeId, selectedId!, vars.assignmentId, vars.role),
    onSuccess: invalidate,
  });

  const remove = useMutation({
    mutationFn: (assignmentId: string) => removeBranchRole(cafeId, selectedId!, assignmentId),
    onSuccess: invalidate,
  });

  const assignedBranchIds = useMemo(
    () => new Set(assignments.map((a) => a.branchId)),
    [assignments]
  );
  const availableBranches = branches.filter((b) => !assignedBranchIds.has(b.id));

  return (
    <div className="grid gap-4 lg:grid-cols-[260px_1fr]">
      {/* Employee picker */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">{t("staff")}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-1">
          {employees.length === 0 ? (
            <p className="text-sm text-muted-foreground">{t("noStaff")}</p>
          ) : (
            employees.map((e) => (
              <button
                key={e.id}
                type="button"
                onClick={() => setSelectedId(e.id)}
                className={`flex w-full items-center justify-between rounded-md px-3 py-2 text-start text-sm transition-colors cursor-pointer ${
                  selectedId === e.id ? "bg-accent" : "hover:bg-accent/50"
                }`}
              >
                <span className="truncate">{e.name}</span>
                <Badge variant="outline" className="shrink-0">
                  {tRoles(roleKey(e.role))}
                </Badge>
              </button>
            ))
          )}
        </CardContent>
      </Card>

      {/* Assignment editor */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">{t("title")}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {!selected ? (
            <p className="text-sm text-muted-foreground">{t("selectStaff")}</p>
          ) : isOwner ? (
            <p className="text-sm text-muted-foreground">{t("ownerNote")}</p>
          ) : (
            <>
              {loadingAssignments ? (
                <p className="text-sm text-muted-foreground">{t("loading")}</p>
              ) : assignments.length === 0 ? (
                <p className="text-sm text-muted-foreground">{t("noAssignments")}</p>
              ) : (
                <ul className="space-y-2">
                  {assignments.map((a: BranchRoleAssignment) => (
                    <li
                      key={a.id}
                      className="flex items-center justify-between gap-2 rounded-md border border-border px-3 py-2"
                    >
                      <span className="min-w-0 flex-1 truncate text-sm font-medium">
                        {a.branchName}
                      </span>
                      <select
                        className="rounded-md border border-input bg-background px-2 py-1 text-sm"
                        value={a.role}
                        onChange={(e) => update.mutate({ assignmentId: a.id, role: e.target.value })}
                        disabled={update.isPending}
                        aria-label={t("role")}
                      >
                        {ASSIGNABLE_ROLES.map((r) => (
                          <option key={r} value={r}>
                            {tRoles(roleKey(r))}
                          </option>
                        ))}
                      </select>
                      <Button
                        variant="ghost"
                        size="sm"
                        className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive cursor-pointer"
                        onClick={() => remove.mutate(a.id)}
                        disabled={remove.isPending}
                        title={t("remove")}
                      >
                        <Trash2 className="h-3.5 w-3.5" aria-hidden />
                        <span className="sr-only">{t("remove")}</span>
                      </Button>
                    </li>
                  ))}
                </ul>
              )}

              {/* Add new assignment */}
              <div className="flex flex-wrap items-end gap-2 border-t border-border pt-4">
                <div className="flex-1 min-w-[140px]">
                  <label className="mb-1 block text-xs text-muted-foreground">{t("branch")}</label>
                  <select
                    className="w-full rounded-md border border-input bg-background px-2 py-2 text-sm"
                    value={newBranchId}
                    onChange={(e) => setNewBranchId(e.target.value)}
                  >
                    <option value="">{t("selectBranch")}</option>
                    {availableBranches.map((b) => (
                      <option key={b.id} value={b.id}>
                        {b.name}
                      </option>
                    ))}
                  </select>
                </div>
                <div className="min-w-[120px]">
                  <label className="mb-1 block text-xs text-muted-foreground">{t("role")}</label>
                  <select
                    className="w-full rounded-md border border-input bg-background px-2 py-2 text-sm"
                    value={newRole}
                    onChange={(e) => setNewRole(e.target.value)}
                  >
                    {ASSIGNABLE_ROLES.map((r) => (
                      <option key={r} value={r}>
                        {tRoles(roleKey(r))}
                      </option>
                    ))}
                  </select>
                </div>
                <Button
                  onClick={() => assign.mutate()}
                  disabled={!newBranchId || assign.isPending}
                  className="gap-1.5"
                >
                  <Plus className="h-3.5 w-3.5" aria-hidden />
                  {t("add")}
                </Button>
              </div>
            </>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
