"use client";

import { useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { apiPut, apiDelete, ApiClientError } from "@/lib/api/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { LabeledField } from "@/components/ui/labeled-field";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

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

interface Props {
  cafeId: string;
  employees: Employee[];
}

export function EmployeeCredentialsPanel({ cafeId, employees }: Props) {
  const t = useTranslations("hr.credentials");

  const [selectedId, setSelectedId] = useState<string>("");
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [feedback, setFeedback] = useState<{ ok: boolean; msg: string } | null>(null);

  const setMutation = useMutation({
    mutationFn: () =>
      apiPut(`/api/cafes/${cafeId}/employees/${selectedId}/credentials`, {
        username,
        password,
      }),
    onSuccess: () => {
      setFeedback({ ok: true, msg: t("saved") });
      setPassword("");
    },
    onError: (err) => {
      if (err instanceof ApiClientError && err.code === "USERNAME_TAKEN") {
        setFeedback({ ok: false, msg: t("usernameTaken") });
      } else {
        setFeedback({ ok: false, msg: err instanceof Error ? err.message : String(err) });
      }
    },
  });

  const removeMutation = useMutation({
    mutationFn: () =>
      apiDelete(`/api/cafes/${cafeId}/employees/${selectedId}/credentials`),
    onSuccess: () => {
      setFeedback({ ok: true, msg: t("removed") });
      setUsername("");
      setPassword("");
    },
    onError: (err) => {
      setFeedback({ ok: false, msg: err instanceof Error ? err.message : String(err) });
    },
  });

  const handleRemove = () => {
    if (!window.confirm(t("removeConfirm"))) return;
    setFeedback(null);
    removeMutation.mutate();
  };

  const isPending = setMutation.isPending || removeMutation.isPending;

  return (
    <div className="space-y-4">
      <div>
        <p className="text-sm text-muted-foreground mb-3">{t("subtitle")}</p>
      </div>

      {/* Employee selector */}
      <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
        {employees.map((emp) => (
          <button
            key={emp.id}
            type="button"
            onClick={() => {
              setSelectedId(emp.id);
              setUsername("");
              setPassword("");
              setFeedback(null);
            }}
            className={`rounded-lg border p-3 text-start transition-colors cursor-pointer ${
              selectedId === emp.id
                ? "border-primary bg-primary/5"
                : "border-border hover:border-primary/50"
            }`}
          >
            <p className="font-medium text-sm">{emp.name}</p>
            <p className="text-xs text-muted-foreground" dir="ltr">{emp.phone}</p>
          </button>
        ))}
      </div>

      {/* Form */}
      {selectedId && (
        <Card>
          <CardHeader>
            <CardTitle className="text-base">
              {employees.find((e) => e.id === selectedId)?.name}
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <LabeledField label={t("username")} htmlFor="cred-username">
              <Input
                id="cred-username"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                placeholder={t("usernamePlaceholder")}
                dir="ltr"
                className="text-start"
                autoComplete="off"
              />
            </LabeledField>
            <LabeledField label={t("password")} htmlFor="cred-password">
              <Input
                id="cred-password"
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder={t("passwordPlaceholder")}
                dir="ltr"
                className="text-start"
                autoComplete="new-password"
              />
            </LabeledField>

            {feedback && (
              <p className={`text-sm ${feedback.ok ? "text-green-600" : "text-destructive"}`}>
                {feedback.msg}
              </p>
            )}

            <div className="flex flex-wrap gap-2">
              <Button
                onClick={() => {
                  setFeedback(null);
                  setMutation.mutate();
                }}
                disabled={isPending || !username.trim() || password.length < 8}
              >
                {isPending ? "..." : t("set")}
              </Button>
              <Button
                variant="outline"
                onClick={handleRemove}
                disabled={isPending}
              >
                {t("remove")}
              </Button>
            </div>
          </CardContent>
        </Card>
      )}

      {!selectedId && (
        <p className="text-sm text-muted-foreground">{t("selectEmployee")}</p>
      )}
    </div>
  );
}
