"use client";

import { FormEvent, useEffect, useMemo, useState } from "react";

import { useLocale } from "@/components/providers/locale-provider";
import { PaginationFooter } from "@/components/shared/pagination-footer";
import { usePagination } from "@/hooks/use-pagination";
import type { ApiErrorResponse, DetailResponse } from "@/types/api";
import type {
  AdjustmentReasonCategory,
  AdjustmentReasonRecord,
  MasterStatus
} from "@/types/master-data";

type FormValues = {
  name: string;
  description: string;
  category: AdjustmentReasonCategory;
  status: MasterStatus;
};

const emptyForm: FormValues = {
  name: "",
  description: "",
  category: "ADJUSTMENT",
  status: "ACTIVE"
};

const categoryOptions: Array<{ value: AdjustmentReasonCategory; label: string }> = [
  { value: "ADJUSTMENT", label: "Penyesuaian / Adjustment" },
  { value: "SHRINKAGE", label: "Penyusutan / Shrinkage" },
  { value: "DAMAGE", label: "Kerusakan / Damage" },
  { value: "REGRADE", label: "Regrade / Regrade" }
];

function getCategoryLabel(category: AdjustmentReasonCategory) {
  return categoryOptions.find((option) => option.value === category)?.label ?? category;
}

export function AdjustmentReasonsClient() {
  const { dict } = useLocale();
  const [items, setItems] = useState<AdjustmentReasonRecord[]>([]);
  const [search, setSearch] = useState("");
  const [form, setForm] = useState<FormValues>(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 filteredItems = useMemo(() => {
    const keyword = search.trim().toLowerCase();
    if (!keyword) return items;

    return items.filter((item) =>
      [item.code, item.name, item.description ?? "", item.category].some((value) =>
        value.toLowerCase().includes(keyword)
      )
    );
  }, [items, search]);

  const pagination = usePagination(filteredItems, 20);

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

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

  function resetForm() {
    setEditingId(null);
    setForm(emptyForm);
    setError(null);
  }

  function startEdit(item: AdjustmentReasonRecord) {
    setEditingId(item.id);
    setForm({
      name: item.name,
      description: item.description ?? "",
      category: item.category,
      status: item.status as MasterStatus
    });
    setError(null);
  }

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setSubmitting(true);
    setError(null);

    try {
      const response = await fetch(
        editingId ? `/api/v1/adjustment-reasons/${editingId}` : "/api/v1/adjustment-reasons",
        {
          method: editingId ? "PUT" : "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ ...form, code: "" })
        }
      );

      const payload =
        (await response.json()) as DetailResponse<AdjustmentReasonRecord> | ApiErrorResponse;

      if (!response.ok) {
        if ("errors" in payload && payload.errors) {
          const firstError = Object.values(payload.errors)[0]?.[0];
          throw new Error(firstError ?? payload.message ?? dict.common.requestFailed);
        }
        throw new Error("message" in payload ? payload.message : dict.common.requestFailed);
      }

      resetForm();
      await loadItems();
    } catch (err) {
      setError(err instanceof Error ? err.message : dict.master.saveError);
    } finally {
      setSubmitting(false);
    }
  }

  async function handleDelete(id: string) {
    if (!window.confirm(`${dict.common.delete} adjustment reason ini?`)) return;

    try {
      const response = await fetch(`/api/v1/adjustment-reasons/${id}`, {
        method: "DELETE"
      });
      if (!response.ok) {
        const payload = (await response.json()) as ApiErrorResponse;
        throw new Error(payload.message);
      }
      if (editingId === id) resetForm();
      await loadItems();
    } catch (err) {
      setError(err instanceof Error ? err.message : dict.master.deleteError);
    }
  }

  return (
    <section className="grid gap-6 xl:grid-cols-[0.92fr_1.08fr]">
      <div className="ops-card p-6">
        <div className="flex items-start justify-between gap-4">
          <div>
            <p className="ops-overline">{dict.master.overline}</p>
            <h2 className="mt-2 text-[28px] font-semibold tracking-tight text-ink">
              {editingId
                ? `${dict.common.edit} Alasan Penyesuaian`
                : `${dict.master.add} Alasan Penyesuaian`}
            </h2>
            <p className="mt-3 text-[13px] leading-6 text-slate-500">
              Master alasan untuk penyesuaian, penyusutan, kerusakan, dan stok opname.
            </p>
          </div>
          {editingId ? (
            <button type="button" onClick={resetForm} className="ops-btn-secondary">
              {dict.common.cancelEdit}
            </button>
          ) : null}
        </div>
        <form className="mt-6 space-y-4" onSubmit={handleSubmit}>
          <div className="grid gap-4 md:grid-cols-2">
            <Field
              label={dict.master.name}
              value={form.name}
              onChange={(value) => setForm((current) => ({ ...current, name: value }))}
            />
            <label className="block">
              <span className="ops-label">Kategori</span>
              <select
                value={form.category}
                onChange={(event) =>
                  setForm((current) => ({
                    ...current,
                    category: event.target.value as AdjustmentReasonCategory
                  }))
                }
                className="ops-select"
              >
                {categoryOptions.map((option) => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
            </label>
          </div>

          <label className="block">
            <span className="ops-label">{dict.master.description}</span>
            <textarea
              value={form.description}
              onChange={(event) =>
                setForm((current) => ({ ...current, description: event.target.value }))
              }
              rows={4}
              className="ops-textarea"
              placeholder="Penjelasan kapan alasan ini dipakai"
            />
          </label>

          <label className="block">
            <span className="ops-label">{dict.master.status}</span>
            <select
              value={form.status}
              onChange={(event) =>
                setForm((current) => ({
                  ...current,
                  status: event.target.value as MasterStatus
                }))
              }
              className="ops-select"
            >
              <option value="ACTIVE">{dict.master.active}</option>
              <option value="INACTIVE">{dict.master.inactive}</option>
            </select>
          </label>

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

          <button type="submit" disabled={submitting} className="ops-btn-primary">
            {submitting
              ? dict.common.processing
              : editingId
                ? `${dict.master.update} alasan penyesuaian`
                : `${dict.master.add} alasan penyesuaian`}
          </button>
        </form>
      </div>

      <div className="ops-table-shell">
        <div className="ops-section-head">
          <div>
            <p className="ops-title">{dict.master.list} Alasan Penyesuaian</p>
            <p className="ops-copy">Master alasan untuk transaksi persediaan.</p>
          </div>
          <div className="ops-chip-muted">
            {items.length} {dict.master.dataCount}
          </div>
        </div>

        {!loading && items.length > 0 ? (
          <div className="border-t border-line/70 px-6 py-4">
            <label className="block">
              <span className="ops-label">Cari alasan penyesuaian</span>
              <input
                value={search}
                onChange={(event) => setSearch(event.target.value)}
                placeholder="Cari kode, nama, deskripsi, atau kategori..."
                className="ops-input"
              />
            </label>
          </div>
        ) : null}

        {loading ? (
          <div className="px-6 py-8 text-sm text-ink/60">{dict.common.loading}</div>
        ) : items.length === 0 ? (
          <div className="px-6 py-8 text-sm text-ink/60">{dict.master.noData}</div>
        ) : filteredItems.length === 0 ? (
          <div className="px-6 py-8 text-sm text-ink/60">
            Tidak ada alasan penyesuaian yang cocok dengan pencarian.
          </div>
        ) : (
          <>
            <div className="overflow-x-auto">
              <table className="ops-table">
                <thead>
                  <tr>
                    <th>{dict.master.code}</th>
                    <th>{dict.master.name}</th>
                    <th>{dict.master.description}</th>
                    <th>Kategori</th>
                    <th>{dict.master.status}</th>
                    <th>{dict.common.actions}</th>
                  </tr>
                </thead>
                <tbody>
                  {pagination.pagedItems.map((item) => (
                    <tr key={item.id}>
                      <td className="font-semibold text-ink">{item.code}</td>
                      <td>{item.name}</td>
                      <td className="text-slate-600">{item.description || "-"}</td>
                      <td className="text-slate-600">{getCategoryLabel(item.category)}</td>
                      <td>
                        <span
                          className={
                            item.status === "INACTIVE" ? "ops-chip-danger" : "ops-chip-active"
                          }
                        >
                          {item.status === "INACTIVE"
                            ? dict.master.inactive
                            : dict.master.active}
                        </span>
                      </td>
                      <td>
                        <div className="flex gap-2">
                          <button
                            type="button"
                            onClick={() => startEdit(item)}
                            className="ops-btn-secondary"
                          >
                            {dict.common.edit}
                          </button>
                          <button
                            type="button"
                            onClick={() => void handleDelete(item.id)}
                            className="ops-btn-danger"
                          >
                            {dict.common.delete}
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <PaginationFooter
              page={pagination.page}
              totalPages={pagination.totalPages}
              rangeStart={pagination.rangeStart}
              rangeEnd={pagination.rangeEnd}
              totalItems={pagination.totalItems}
              itemLabel="adjustment reason"
              onPrev={() => pagination.setPage((page) => Math.max(1, page - 1))}
              onNext={() =>
                pagination.setPage((page) => Math.min(pagination.totalPages, page + 1))
              }
            />
          </>
        )}
      </div>
    </section>
  );
}

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