"use client";

import { useState } from "react";
import { PageHeader, Card, Spinner, ErrorState, Badge } from "@/components/ui";
import { useApi } from "@/hooks/useApi";
import { api, StaffRole } from "@/lib/api";
import { useLocale } from "@/i18n/LocaleProvider";

const ROLES: StaffRole[] = ["SUPER_ADMIN", "OPS", "FINANCE", "SUPPORT"];

export default function StaffPage() {
  const { t } = useLocale();
  const { data, loading, error, reload } = useApi(() => api.listStaff());

  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [role, setRole] = useState<StaffRole>("OPS");
  const [submitting, setSubmitting] = useState(false);
  const [formError, setFormError] = useState<string | null>(null);

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    setFormError(null);
    try {
      await api.createStaff({ name, email, role });
      setName("");
      setEmail("");
      setRole("OPS");
      reload();
    } catch (err) {
      setFormError(err instanceof Error ? err.message : String(err));
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div>
      <PageHeader titleKey="staff.title" />

      <div className="grid gap-6 lg:grid-cols-3">
        {/* Create form */}
        <Card className="lg:col-span-1">
          <div className="mb-4 text-sm font-semibold">{t("staff.new")}</div>
          <form onSubmit={submit} className="space-y-3">
            <div>
              <label className="mb-1 block text-xs text-muted">{t("staff.name")}</label>
              <input
                className="field"
                value={name}
                onChange={(e) => setName(e.target.value)}
                required
              />
            </div>
            <div>
              <label className="mb-1 block text-xs text-muted">{t("staff.email")}</label>
              <input
                className="field"
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
              />
            </div>
            <div>
              <label className="mb-1 block text-xs text-muted">{t("staff.role")}</label>
              <select
                className="field"
                value={role}
                onChange={(e) => setRole(e.target.value as StaffRole)}
              >
                {ROLES.map((r) => (
                  <option key={r} value={r}>
                    {r}
                  </option>
                ))}
              </select>
            </div>
            {formError && <p className="text-xs text-red-600">{formError}</p>}
            <button className="btn-primary w-full" disabled={submitting}>
              {t("staff.create")}
            </button>
          </form>
        </Card>

        {/* List */}
        <div className="lg:col-span-2">
          {loading && <Spinner />}
          {!loading && !!error && <ErrorState onRetry={reload} />}
          {!loading && !error && (
            <Card className="overflow-x-auto p-0">
              <table className="w-full text-start text-sm">
                <thead className="border-b border-line text-xs text-muted">
                  <tr>
                    <th className="px-4 py-3 text-start font-medium">{t("staff.name")}</th>
                    <th className="px-4 py-3 text-start font-medium">{t("staff.role")}</th>
                    <th className="px-4 py-3 text-start font-medium">{t("staff.active")}</th>
                  </tr>
                </thead>
                <tbody>
                  {(data ?? []).map((s) => (
                    <tr key={s.id} className="border-b border-line last:border-0">
                      <td className="px-4 py-3">
                        <div className="font-medium">{s.name}</div>
                        <div className="text-xs text-muted">{s.email}</div>
                      </td>
                      <td className="px-4 py-3">
                        <Badge>{s.role}</Badge>
                      </td>
                      <td className="px-4 py-3">
                        <span
                          className={`inline-block h-2.5 w-2.5 rounded-full ${
                            s.active ? "bg-emerald-500" : "bg-muted"
                          }`}
                        />
                      </td>
                    </tr>
                  ))}
                  {(data ?? []).length === 0 && (
                    <tr>
                      <td colSpan={3} className="px-4 py-8 text-center text-sm text-muted">
                        -
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
}
