"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 { useCurrentUser } from "@/hooks/use-current-user";
import type { ApiErrorResponse, DetailResponse } from "@/types/api";
import type {
  WarehouseLocationRecord,
  WarehouseRecord,
  MasterStatus
} from "@/types/master-data";

type FormValues = {
  warehouse_id: string;
  code: string;
  name: string;
  location_type: string;
  status: MasterStatus;
};

const emptyForm: FormValues = {
  warehouse_id: "",
  code: "",
  name: "",
  location_type: "",
  status: "ACTIVE"
};

export function WarehouseLocationsClient() {
  const { locale } = useLocale();
  const [items, setItems] = useState<WarehouseLocationRecord[]>([]);
  const [search, setSearch] = useState("");
  const [warehouses, setWarehouses] = useState<WarehouseRecord[]>([]);
  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 { canEditCode } = useCurrentUser();
  const filteredItems = useMemo(() => {
    const keyword = search.trim().toLowerCase();
    if (!keyword) return items;
    return items.filter((item) =>
      [
        item.warehouse_name,
        item.code,
        item.name,
        item.location_type ?? ""
      ].some((value) => value.toLowerCase().includes(keyword))
    );
  }, [items, search]);
  const pagination = usePagination(filteredItems, 20);

  async function loadAll() {
    setLoading(true);
    setError(null);
    try {
      const [locationsResponse, warehousesResponse] = await Promise.all([
        fetch("/api/v1/warehouse-locations", { cache: "no-store" }),
        fetch("/api/v1/warehouses", { cache: "no-store" })
      ]);
      const locationsPayload = (await locationsResponse.json()) as {
        data: WarehouseLocationRecord[];
      };
      const warehousesPayload = (await warehousesResponse.json()) as {
        data: WarehouseRecord[];
      };

      if (!locationsResponse.ok || !warehousesResponse.ok) {
        throw new Error(locale === "id" ? "Gagal memuat data lokasi gudang" : "Failed to load warehouse locations");
      }

      setItems(locationsPayload.data);
      setWarehouses(warehousesPayload.data);
    } catch (err) {
      setError(
        err instanceof Error ? err.message : locale === "id" ? "Gagal memuat data lokasi gudang" : "Failed to load warehouse locations"
      );
    } finally {
      setLoading(false);
    }
  }

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

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

  function startEdit(item: WarehouseLocationRecord) {
    setEditingId(item.id);
    setForm({
      warehouse_id: item.warehouse_id,
      code: item.code,
      name: item.name,
      location_type: item.location_type ?? "",
      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/warehouse-locations/${editingId}` : "/api/v1/warehouse-locations",
        {
          method: editingId ? "PUT" : "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(form)
        }
      );
      const payload =
        (await response.json()) as DetailResponse<WarehouseLocationRecord> | 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
            : locale === "id"
              ? "Permintaan gagal"
              : "Request failed"
        );
      }
      resetForm();
      await loadAll();
    } catch (err) {
      setError(
        err instanceof Error ? err.message : "Gagal menyimpan lokasi gudang"
      );
    } finally {
      setSubmitting(false);
    }
  }

  async function handleDelete(id: string) {
    if (!window.confirm("Hapus lokasi gudang ini?")) return;
    try {
      const response = await fetch(`/api/v1/warehouse-locations/${id}`, {
        method: "DELETE"
      });
      if (!response.ok) {
        const payload = (await response.json()) as ApiErrorResponse;
        throw new Error(payload.message);
      }
      if (editingId === id) resetForm();
      await loadAll();
    } catch (err) {
      setError(
        err instanceof Error ? err.message : locale === "id" ? "Gagal menghapus lokasi gudang" : "Failed to delete warehouse location"
      );
    }
  }

  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">{locale === "id" ? "Master data" : "Master data"}</p>
            <h2 className="mt-2 text-[28px] font-semibold tracking-tight text-ink">
              {editingId ? (locale === "id" ? "Edit Lokasi Gudang" : "Edit Warehouse Location") : (locale === "id" ? "Tambah Lokasi Gudang" : "Add Warehouse Location")}
            </h2>
            <p className="mt-3 text-[13px] leading-6 text-slate-500">
              {locale === "id" ? "Lokasi digunakan saat penerimaan, penyimpanan lot, transfer, dan picking." : "Locations are used for receiving, lot storage, transfers, and picking."}
            </p>
          </div>
          {editingId ? (
            <button type="button" onClick={resetForm} className="ops-btn-secondary">{locale === "id" ? "Batal edit" : "Cancel edit"}</button>
          ) : null}
        </div>
        <form className="mt-6 space-y-4" onSubmit={handleSubmit}>
          <label className="block">
            <span className="ops-label">{locale === "id" ? "Gudang" : "Warehouse"}</span>
            <select
              value={form.warehouse_id}
              onChange={(event) =>
                setForm((current) => ({ ...current, warehouse_id: event.target.value }))
              }
              className="ops-select"
            >
              <option value="">{locale === "id" ? "Pilih gudang" : "Choose warehouse"}</option>
              {warehouses.map((warehouse) => (
                <option key={warehouse.id} value={warehouse.id}>
                  {warehouse.code} - {warehouse.name}
                </option>
              ))}
            </select>
          </label>
          <div className="grid gap-4 md:grid-cols-2">
            <Field
              label={locale === "id" ? "Kode" : "Code"}
              value={form.code}
              readOnly={!canEditCode}
              placeholder={canEditCode ? "LOC00001" : locale === "id" ? "Otomatis oleh sistem" : "Generated automatically"}
              onChange={(value) => setForm((current) => ({ ...current, code: value }))}
            />
            <Field
              label={locale === "id" ? "Nama" : "Name"}
              value={form.name}
              onChange={(value) => setForm((current) => ({ ...current, name: value }))}
            />
            <Field
              label={locale === "id" ? "Tipe lokasi" : "Location type"}
              value={form.location_type}
              onChange={(value) =>
                setForm((current) => ({ ...current, location_type: value }))
              }
            />
          </div>
          <label className="block">
            <span className="ops-label">{locale === "id" ? "Status" : "Status"}</span>
            <select
              value={form.status}
              onChange={(event) =>
                setForm((current) => ({
                  ...current,
                  status: event.target.value as MasterStatus
                }))
              }
              className="ops-select"
            >
              <option value="ACTIVE">ACTIVE</option>
              <option value="INACTIVE">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
              ? (locale === "id" ? "Menyimpan..." : "Saving...")
              : editingId
                ? (locale === "id" ? "Update lokasi gudang" : "Update warehouse location")
                : (locale === "id" ? "Tambah lokasi gudang" : "Add warehouse location")}
          </button>
        </form>
      </div>
      <div className="ops-table-shell">
        <div className="ops-section-head">
          <div>
            <p className="ops-title">{locale === "id" ? "Daftar Lokasi Gudang" : "Warehouse Location List"}</p>
            <p className="ops-copy">
              {locale === "id" ? "Relasi ke gudang utama sudah aktif." : "The relation to the main warehouse is active."}
            </p>
          </div>
          <div className="ops-chip-muted">
            {items.length} data
          </div>
        </div>
        {!loading && items.length > 0 ? (
          <div className="border-t border-line/70 px-6 py-4">
            <label className="block">
              <span className="ops-label">{locale === "id" ? "Cari lokasi" : "Search location"}</span>
              <input
                value={search}
                onChange={(event) => setSearch(event.target.value)}
                placeholder={locale === "id" ? "Cari gudang, kode, nama, tipe..." : "Search warehouse, code, name, type..."}
                className="ops-input"
              />
            </label>
          </div>
        ) : null}
        {loading ? (
          <div className="px-6 py-8 text-sm text-ink/60">{locale === "id" ? "Memuat data..." : "Loading data..."}</div>
        ) : items.length === 0 ? (
          <div className="px-6 py-8 text-sm text-ink/60">
            {locale === "id" ? "Belum ada data. Tambahkan data pertama dari form di sebelah kiri." : "No data yet. Add the first record from the form on the left."}
          </div>
        ) : filteredItems.length === 0 ? (
          <div className="px-6 py-8 text-sm text-ink/60">{locale === "id" ? "Tidak ada lokasi yang cocok dengan pencarian." : "No locations match the search."}</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="ops-table">
              <thead>
                <tr>
                  <th>{locale === "id" ? "Gudang" : "Warehouse"}</th>
                  <th>{locale === "id" ? "Kode" : "Code"}</th>
                  <th>{locale === "id" ? "Nama / Tipe" : "Name / Type"}</th>
                  <th>{locale === "id" ? "Status" : "Status"}</th>
                  <th>{locale === "id" ? "Aksi" : "Actions"}</th>
                </tr>
              </thead>
              <tbody>
                {pagination.pagedItems.map((item) => (
                  <tr key={item.id}>
                    <td>{item.warehouse_name}</td>
                    <td className="font-semibold text-ink">{item.code}</td>
                    <td className="text-slate-600">
                      <div>{item.name}</div>
                      <div className="mt-1 text-xs">{item.location_type || "-"}</div>
                    </td>
                    <td>
                      <span className={item.status === "INACTIVE" ? "ops-chip-danger" : "ops-chip-active"}>
                        {item.status}
                      </span>
                    </td>
                    <td>
                      <div className="flex gap-2">
                        <button type="button" onClick={() => startEdit(item)} className="ops-btn-secondary">{locale === "id" ? "Edit" : "Edit"}</button>
                        <button type="button" onClick={() => void handleDelete(item.id)} className="ops-btn-danger">{locale === "id" ? "Hapus" : "Delete"}</button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
        {!loading && items.length > 0 ? (
          <PaginationFooter
            page={pagination.page}
            totalPages={pagination.totalPages}
            rangeStart={pagination.rangeStart}
            rangeEnd={pagination.rangeEnd}
            totalItems={pagination.totalItems}
            itemLabel={locale === "id" ? "lokasi" : "locations"}
            onPrev={() => pagination.setPage((current) => Math.max(1, current - 1))}
            onNext={() => pagination.setPage((current) => Math.min(pagination.totalPages, current + 1))}
          />
        ) : null}
      </div>
    </section>
  );
}

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