"use client";

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

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

type FormValues = {
  code: string;
  name: string;
  address: string;
  phone: string;
  website: string;
  email: string;
  status: MasterStatus;
};

const emptyForm: FormValues = {
  code: "",
  name: "",
  address: "",
  phone: "",
  website: "",
  email: "",
  status: "ACTIVE"
};

export function CouriersClient() {
  const { dict } = useLocale();
  const { canEditCode } = useCurrentUser();
  const [items, setItems] = useState<CourierRecord[]>([]);
  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.phone ?? "",
        item.email ?? "",
        item.website ?? "",
        item.address ?? ""
      ].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/couriers", { cache: "no-store" });
      const payload = (await response.json()) as { data: CourierRecord[] };
      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: CourierRecord) {
    setEditingId(item.id);
    setForm({
      code: item.code,
      name: item.name,
      address: item.address ?? "",
      phone: item.phone ?? "",
      website: item.website ?? "",
      email: item.email ?? "",
      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/couriers/${editingId}` : "/api/v1/couriers", {
        method: editingId ? "PUT" : "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form)
      });
      const payload = (await response.json()) as DetailResponse<CourierRecord> | 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} jasa pengiriman ini?`)) return;
    try {
      const response = await fetch(`/api/v1/couriers/${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} Jasa Pengiriman`
                : `${dict.master.add} Jasa Pengiriman`}
            </h2>
            <p className="mt-3 text-[13px] leading-6 text-slate-500">
              Master jasa pengiriman untuk pengiriman, penjemputan, dan referensi kontak operasional.
            </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.code} value={form.code} readOnly={!canEditCode} placeholder={canEditCode ? "CUR00001" : "Auto"} onChange={(value) => setForm((current) => ({ ...current, code: value }))} />
            <Field label={dict.master.name} value={form.name} onChange={(value) => setForm((current) => ({ ...current, name: value }))} />
            <Field label="Telepon" value={form.phone} onChange={(value) => setForm((current) => ({ ...current, phone: value }))} />
            <Field label="Website" value={form.website} onChange={(value) => setForm((current) => ({ ...current, website: value }))} />
            <Field label="Email" value={form.email} onChange={(value) => setForm((current) => ({ ...current, email: value }))} />
          </div>

          <label className="block">
            <span className="ops-label">{dict.master.address}</span>
            <textarea value={form.address} onChange={(event) => setForm((current) => ({ ...current, address: event.target.value }))} rows={4} className="ops-textarea" />
          </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} jasa pengiriman`
                : `${dict.master.add} jasa pengiriman`}
          </button>
        </form>
      </div>

      <div className="ops-table-shell">
        <div className="ops-section-head">
          <div>
            <p className="ops-title">{dict.master.list} Jasa Pengiriman</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 jasa pengiriman</span>
              <input
                value={search}
                onChange={(event) => setSearch(event.target.value)}
                placeholder="Cari kode, nama, kontak, website..."
                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 jasa pengiriman 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>Kontak</th>
                  <th>{dict.master.address}</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">
                      <div>{item.phone || "-"}</div>
                      <div className="mt-1 text-xs">{item.email || "-"}</div>
                      <div className="mt-1 text-xs">{item.website || "-"}</div>
                    </td>
                    <td className="text-slate-600">{item.address || "-"}</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>
        )}
        {!loading && items.length > 0 ? (
          <PaginationFooter
            page={pagination.page}
            totalPages={pagination.totalPages}
            rangeStart={pagination.rangeStart}
            rangeEnd={pagination.rangeEnd}
            totalItems={pagination.totalItems}
            itemLabel="jasa pengiriman"
            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>
  );
}
