"use client";

import { useEffect, useState } from "react";

import { useLocale } from "@/components/providers/locale-provider";
import { appRoles } from "@/config/access-control";
import type { ApiErrorResponse, DetailResponse } from "@/types/api";
import type { UserManagementRecord } from "@/types/user-management";

type UserForm = {
  name: string;
  email: string;
  username: string;
  phone: string;
  password: string;
  role_code: string;
  status: "ACTIVE" | "INACTIVE";
};

const emptyForm = (): UserForm => ({
  name: "",
  email: "",
  username: "",
  phone: "",
  password: "",
  role_code: "WAREHOUSE",
  status: "ACTIVE"
});

export function UsersClient() {
  const { dict, locale } = useLocale();
  const [items, setItems] = useState<UserManagementRecord[]>([]);
  const [form, setForm] = useState<UserForm>(emptyForm);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null);

  async function loadUsers() {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch("/api/v1/users", { cache: "no-store" });
      const payload = (await response.json()) as { data: UserManagementRecord[] } | ApiErrorResponse;
      if (!response.ok || !("data" in payload)) {
        throw new Error("message" in payload ? payload.message : dict.master.loadError);
      }
      setItems(payload.data);
    } catch (err) {
      setError(err instanceof Error ? err.message : dict.master.loadError);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    void loadUsers();
  }, []);

  function startEditUser(item: UserManagementRecord) {
    setEditingId(item.id);
    setForm({
      name: item.name,
      email: item.email ?? "",
      username: item.username ?? "",
      phone: item.phone ?? "",
      password: "",
      role_code: item.role.code,
      status: item.status as "ACTIVE" | "INACTIVE"
    });
    setError(null);
    setMessage(null);
  }

  function cancelEdit() {
    setEditingId(null);
    setForm(emptyForm());
    setError(null);
    setMessage(null);
  }

  async function submitUser() {
    setSubmitting(true);
    setError(null);
    setMessage(null);
    try {
      const response = await fetch(editingId ? `/api/v1/users/${editingId}` : "/api/v1/users", {
        method: editingId ? "PUT" : "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(
          editingId
            ? {
                name: form.name,
                email: form.email,
                username: form.username,
                phone: form.phone,
                role_code: form.role_code,
                status: form.status
              }
            : form
        )
      });
      const payload = (await response.json()) as DetailResponse<UserManagementRecord> | ApiErrorResponse;
      if (!response.ok) {
        if ("errors" in payload && payload.errors) {
          const firstError = Object.values(payload.errors)[0]?.[0];
          throw new Error(
            firstError ??
              payload.message ??
              (locale === "id" ? "Validasi gagal" : "Validation failed")
          );
        }
        throw new Error("message" in payload ? payload.message : dict.common.requestFailed);
      }
      setForm(emptyForm());
      setEditingId(null);
      setMessage(
        "message" in payload && payload.message
          ? payload.message
          : editingId
            ? dict.users.updatedMessage
            : dict.users.createdMessage
      );
      await loadUsers();
    } catch (err) {
      setError(err instanceof Error ? err.message : dict.common.requestFailed);
    } finally {
      setSubmitting(false);
    }
  }

  async function deleteUser(id: string) {
    if (!window.confirm(`${dict.common.delete} user ini?`)) return;
    setError(null);
    setMessage(null);
    try {
      const response = await fetch(`/api/v1/users/${id}`, { method: "DELETE" });
      const payload = (await response.json()) as ApiErrorResponse & { message: string };
      if (!response.ok) {
        throw new Error(payload.message ?? dict.master.deleteError);
      }
      setMessage(payload.message);
      await loadUsers();
    } catch (err) {
      setError(err instanceof Error ? err.message : dict.master.deleteError);
    }
  }

  async function sendVerification(id: string) {
    setError(null);
    setMessage(null);
    try {
      const response = await fetch(`/api/v1/users/${id}/send-verification`, { method: "POST" });
      const payload = (await response.json()) as { message: string };
      if (!response.ok) {
        throw new Error(payload.message ?? dict.common.requestFailed);
      }
      setMessage(payload.message);
      await loadUsers();
    } catch (err) {
      setError(err instanceof Error ? err.message : dict.common.requestFailed);
    }
  }

  async function forceReset(id: string) {
    setError(null);
    setMessage(null);
    try {
      const response = await fetch(`/api/v1/users/${id}/force-reset`, { method: "POST" });
      const payload = (await response.json()) as { message: string };
      if (!response.ok) {
        throw new Error(payload.message ?? dict.common.requestFailed);
      }
      setMessage(payload.message);
    } catch (err) {
      setError(err instanceof Error ? err.message : dict.common.requestFailed);
    }
  }

  return (
    <section className="grid gap-6 xl:grid-cols-[0.92fr_1.08fr]">
      <div className="ops-card p-6">
        <div>
          <p className="ops-overline">{dict.users.overline}</p>
          <h2 className="mt-2 text-[28px] font-semibold tracking-tight text-ink">
            {editingId ? dict.users.editTitle : dict.users.createTitle}
          </h2>
          <p className="mt-3 text-[13px] leading-6 text-slate-500">
            {editingId ? dict.users.editCopy : dict.users.createCopy}
          </p>
        </div>

        <div className="mt-6 grid gap-4 md:grid-cols-2">
          <Field label={dict.users.name} value={form.name} onChange={(value) => setForm((current) => ({ ...current, name: value }))} />
          <Field label={dict.users.email} value={form.email} onChange={(value) => setForm((current) => ({ ...current, email: value }))} />
          <Field label={dict.users.username} value={form.username} onChange={(value) => setForm((current) => ({ ...current, username: value }))} />
          <Field label={dict.users.phone} value={form.phone} onChange={(value) => setForm((current) => ({ ...current, phone: value }))} />
          {!editingId ? (
            <Field label={dict.users.initialPassword} type="password" value={form.password} onChange={(value) => setForm((current) => ({ ...current, password: value }))} />
          ) : null}
          <SelectField
            label={dict.users.role}
            value={form.role_code}
            onChange={(value) => setForm((current) => ({ ...current, role_code: value }))}
            options={appRoles.map((role) => ({ value: role, label: role }))}
          />
          <SelectField
            label={dict.users.status}
            value={form.status}
            onChange={(value) => setForm((current) => ({ ...current, status: value as "ACTIVE" | "INACTIVE" }))}
            options={[
              { value: "ACTIVE", label: "ACTIVE" },
              { value: "INACTIVE", label: "INACTIVE" }
            ]}
          />
        </div>

        {error ? <div className="mt-6 rounded border border-ember/30 bg-ember/10 px-4 py-3 text-sm text-ember">{error}</div> : null}
        {message ? <div className="mt-6 rounded border border-moss/30 bg-moss/10 px-4 py-3 text-sm text-moss">{message}</div> : null}

        <div className="mt-6 flex flex-wrap gap-3">
          <button type="button" disabled={submitting} onClick={() => void submitUser()} className="ops-btn-primary">
            {submitting
              ? dict.common.processing
              : editingId
                ? dict.common.save
                : dict.users.create}
          </button>
          {editingId ? (
            <button type="button" onClick={cancelEdit} className="ops-btn-secondary">
              {dict.common.cancelEdit}
            </button>
          ) : null}
        </div>
      </div>

      <div className="ops-table-shell">
        <div className="ops-section-head">
          <div>
            <p className="ops-title">{dict.users.listTitle}</p>
            <p className="ops-copy">{dict.users.listCopy}</p>
          </div>
          <div className="ops-chip-muted">{items.length} user</div>
        </div>
        {loading ? (
          <div className="px-6 py-8 text-sm text-ink/60">{dict.common.loading}</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="ops-table">
              <thead>
                <tr>
                  <th>{dict.users.name}</th>
                  <th>{dict.users.role}</th>
                  <th>{dict.users.email}</th>
                  <th>{dict.users.status}</th>
                  <th>Verified</th>
                  <th>{dict.common.actions}</th>
                </tr>
              </thead>
              <tbody>
                {items.map((item) => (
                  <tr key={item.id}>
                    <td>
                      <div className="font-semibold text-ink">{item.name}</div>
                      <div className="mt-1 text-xs text-slate-500">{item.username ?? "-"}</div>
                    </td>
                    <td className="text-slate-600">{item.role.code}</td>
                    <td className="text-slate-600">{item.email ?? "-"}</td>
                    <td>
                      <span className={item.status === "ACTIVE" ? "ops-chip-active" : "ops-chip-muted"}>
                        {item.status}
                      </span>
                    </td>
                    <td className="text-slate-600">
                      {item.email_verified_at ? dict.users.verified : dict.users.pending}
                    </td>
                    <td>
                      <div className="flex flex-wrap gap-2">
                        {!item.email_verified_at ? (
                          <button
                            type="button"
                            onClick={() => void sendVerification(item.id)}
                            className="whitespace-nowrap rounded border border-line/80 px-3 py-1.5 text-[11px] font-semibold text-ink/80 transition hover:bg-slate-50"
                          >
                            {dict.users.sendVerification}
                          </button>
                        ) : null}
                        <button
                          type="button"
                          onClick={() => startEditUser(item)}
                          className="whitespace-nowrap rounded border border-line/80 px-3 py-1.5 text-[11px] font-semibold text-ink/80 transition hover:bg-slate-50"
                        >
                          {dict.common.edit}
                        </button>
                        <button
                          type="button"
                          onClick={() => void forceReset(item.id)}
                          className="whitespace-nowrap rounded border border-line/80 px-3 py-1.5 text-[11px] font-semibold text-ink/80 transition hover:bg-slate-50"
                        >
                          {dict.users.forceReset}
                        </button>
                        <button
                          type="button"
                          onClick={() => void deleteUser(item.id)}
                          className="whitespace-nowrap rounded border border-red-200 px-3 py-1.5 text-[11px] font-semibold text-red-600 transition hover:bg-red-50"
                        >
                          {dict.users.delete}
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </section>
  );
}

function Field({
  label,
  value,
  onChange,
  type = "text"
}: {
  label: string;
  value: string;
  onChange: (value: string) => void;
  type?: string;
}) {
  return (
    <label className="block">
      <span className="ops-label">{label}</span>
      <input type={type} value={value} onChange={(event) => onChange(event.target.value)} className="ops-input" />
    </label>
  );
}

function SelectField({
  label,
  value,
  onChange,
  options
}: {
  label: string;
  value: string;
  onChange: (value: string) => void;
  options: Array<{ value: string; label: string }>;
}) {
  return (
    <label className="block">
      <span className="ops-label">{label}</span>
      <select value={value} onChange={(event) => onChange(event.target.value)} className="ops-select">
        {options.map((option) => (
          <option key={`${label}-${option.value}`} value={option.value}>
            {option.label}
          </option>
        ))}
      </select>
    </label>
  );
}
