"use client";

import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { apiGet, apiPost } from "@/lib/api/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { LabeledField } from "@/components/ui/labeled-field";
import { notify } from "@/lib/notify";
import { useApiError } from "@/lib/use-api-error";

/** Roles that can be created from the dashboard (Owner is created only at signup). */
const ALL_ROLES = ["Manager", "Cashier", "Waiter", "Chef", "Delivery"] as const;
type Role = (typeof ALL_ROLES)[number];

type Branch = { id: string; name: string };

const selectClass =
  "h-9 w-full rounded-lg border border-border bg-background px-3 text-sm outline-none focus:ring-2 focus:ring-primary/30";

export function AddEmployeeForm({
  cafeId,
  canAddManager,
  onClose,
}: {
  cafeId: string;
  canAddManager: boolean;
  onClose: () => void;
}) {
  const t = useTranslations("hr");
  const apiError = useApiError();
  const queryClient = useQueryClient();

  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [role, setRole] = useState<Role>("Waiter");
  const [branchId, setBranchId] = useState("");
  const [baseSalary, setBaseSalary] = useState("");
  const [withLogin, setWithLogin] = useState(false);
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

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

  const roles = canAddManager ? ALL_ROLES : ALL_ROLES.filter((r) => r !== "Manager");

  const credsValid = !withLogin || (username.trim().length > 0 && password.length >= 8);
  const canSubmit = name.trim().length > 0 && phone.trim().length > 0 && credsValid;

  const createMut = useMutation({
    mutationFn: () =>
      apiPost(`/api/cafes/${cafeId}/employees`, {
        name: name.trim(),
        phone: phone.trim(),
        role,
        branchId: branchId || null,
        baseSalary: baseSalary ? Number(baseSalary) : null,
        username: withLogin ? username.trim() : null,
        password: withLogin ? password : null,
      }),
    onSuccess: () => {
      notify.success(t("employeeCreated"));
      queryClient.invalidateQueries({ queryKey: ["employees", cafeId] });
      onClose();
    },
    onError: (err) => notify.error(apiError(err)),
  });

  return (
    <div className="rounded-xl border border-border bg-card p-4 shadow-sm">
      <h3 className="mb-3 text-base font-semibold">{t("addEmployee")}</h3>
      <div className="grid gap-3 sm:grid-cols-2">
        <LabeledField label={t("fields.name")} htmlFor="emp-name">
          <Input id="emp-name" value={name} onChange={(e) => setName(e.target.value)} dir="rtl" />
        </LabeledField>
        <LabeledField label={t("fields.phone")} htmlFor="emp-phone">
          <Input id="emp-phone" value={phone} onChange={(e) => setPhone(e.target.value)} dir="ltr" placeholder="09xxxxxxxxx" />
        </LabeledField>
        <LabeledField label={t("fields.role")} htmlFor="emp-role">
          <select id="emp-role" className={selectClass} value={role} onChange={(e) => setRole(e.target.value as Role)}>
            {roles.map((r) => (
              <option key={r} value={r}>
                {t(`roles.${r}`)}
              </option>
            ))}
          </select>
        </LabeledField>
        <LabeledField label={t("fields.branch")} htmlFor="emp-branch" hint={t("fields.branchOptional")}>
          <select id="emp-branch" className={selectClass} value={branchId} onChange={(e) => setBranchId(e.target.value)}>
            <option value="">{t("fields.noBranch")}</option>
            {branches.map((b) => (
              <option key={b.id} value={b.id}>
                {b.name}
              </option>
            ))}
          </select>
        </LabeledField>
        <LabeledField label={t("fields.baseSalary")} htmlFor="emp-salary" hint={t("fields.optional")}>
          <Input
            id="emp-salary"
            value={baseSalary}
            onChange={(e) => setBaseSalary(e.target.value.replace(/[^\d]/g, ""))}
            dir="ltr"
            inputMode="numeric"
          />
        </LabeledField>
      </div>

      <label className="mt-3 flex cursor-pointer items-center gap-2 text-sm">
        <input type="checkbox" checked={withLogin} onChange={(e) => setWithLogin(e.target.checked)} className="size-4" />
        {t("fields.enableLogin")}
      </label>

      {withLogin && (
        <div className="mt-3 grid gap-3 sm:grid-cols-2">
          <LabeledField label={t("fields.username")} htmlFor="emp-username">
            <Input id="emp-username" value={username} onChange={(e) => setUsername(e.target.value)} dir="ltr" autoComplete="off" />
          </LabeledField>
          <LabeledField label={t("fields.password")} htmlFor="emp-password" hint={t("fields.passwordHint")}>
            <Input id="emp-password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} dir="ltr" autoComplete="new-password" />
          </LabeledField>
        </div>
      )}

      <div className="mt-4 flex justify-end gap-2">
        <Button variant="outline" size="sm" onClick={onClose} disabled={createMut.isPending}>
          {t("cancel")}
        </Button>
        <Button size="sm" onClick={() => createMut.mutate()} disabled={!canSubmit || createMut.isPending}>
          {t("save")}
        </Button>
      </div>
    </div>
  );
}
