"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 { MasterStatus, ProfitShareSchemeRecord } from "@/types/master-data";

type FormValues = {
  code: string;
  name: string;
  share_agent: string;
  share_company: string;
  status: MasterStatus;
};

const emptyForm: FormValues = {
  code: "",
  name: "",
  share_agent: "",
  share_company: "",
  status: "ACTIVE"
};

export function ProfitShareSchemesClient() {
  const { dict } = useLocale();
  const [items, setItems] = useState<ProfitShareSchemeRecord[]>([]);
  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 { canEditCode } = useCurrentUser();
  const filteredItems = useMemo(() => {
    const keyword = search.trim().toLowerCase();
    if (!keyword) return items;
    return items.filter((item) =>
      [item.code, item.name, String(item.share_agent), String(item.share_company)].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/profit-share-schemes", { cache: "no-store" });
      const payload = (await response.json()) as { data: ProfitShareSchemeRecord[] };
      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();
  }, []);

  const totalShare = useMemo(() => {
    return (Number(form.share_agent) || 0) + (Number(form.share_company) || 0);
  }, [form.share_agent, form.share_company]);

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

  function startEdit(item: ProfitShareSchemeRecord) {
    setEditingId(item.id);
    setForm({
      code: item.code,
      name: item.name,
      share_agent: String(item.share_agent),
      share_company: String(item.share_company),
      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/profit-share-schemes/${editingId}` : "/api/v1/profit-share-schemes",
        {
          method: editingId ? "PUT" : "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            ...form,
            share_agent: Number(form.share_agent || 0),
            share_company: Number(form.share_company || 0)
          })
        }
      );
      const payload =
        (await response.json()) as DetailResponse<ProfitShareSchemeRecord> | 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} skema bagi hasil ini?`)) return;
    try {
      const response = await fetch(`/api/v1/profit-share-schemes/${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} Skema Bagi Hasil`
                : `${dict.master.add} Skema Bagi Hasil`}
            </h2>
            <p className="mt-3 text-[13px] leading-6 text-slate-500">
              Definisikan skema pembagian hasil antara agen dan perusahaan. Total persentase harus 100%.
            </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 ? "PSS00001" : "Auto"}
              onChange={(value) => setForm((current) => ({ ...current, code: value }))}
            />
            <Field
              label="Nama skema"
              value={form.name}
              onChange={(value) => setForm((current) => ({ ...current, name: value }))}
            />
            <Field
              label="Porsi agen (%)"
              value={form.share_agent}
              type="number"
              onChange={(value) => setForm((current) => ({ ...current, share_agent: value }))}
            />
            <Field
              label="Porsi perusahaan (%)"
              value={form.share_company}
              type="number"
              onChange={(value) => setForm((current) => ({ ...current, share_company: value }))}
            />
          </div>
          <div className={`rounded border px-4 py-3 text-sm ${totalShare === 100 ? "border-moss/30 bg-moss/10 text-moss" : "border-ember/30 bg-ember/10 text-ember"}`}>
            Total porsi: {totalShare.toFixed(2)}%
          </div>
          <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} skema bagi hasil`
                : `${dict.master.add} skema bagi hasil`}
          </button>
        </form>
      </div>

      <div className="ops-table-shell">
        <div className="ops-section-head">
          <div>
            <p className="ops-title">{dict.master.list} Skema Bagi Hasil</p>
            <p className="ops-copy">Master skema bagi hasil untuk kebutuhan komersial berikutnya.</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 skema</span>
              <input
                value={search}
                onChange={(event) => setSearch(event.target.value)}
                placeholder="Cari kode, nama, atau persentase..."
                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 skema yang cocok dengan pencarian.</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="ops-table">
              <thead>
                <tr>
                  <th>{dict.master.code}</th>
                  <th>Nama skema</th>
                  <th>Porsi Agen</th>
                  <th>Porsi Perusahaan</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>{item.share_agent}%</td>
                    <td>{item.share_company}%</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="skema"
            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,
  type = "text"
}: {
  label: string;
  value: string;
  onChange: (value: string) => void;
  readOnly?: boolean;
  placeholder?: string;
  type?: string;
}) {
  return (
    <label className="block">
      <span className="ops-label">{label}</span>
      <input
        type={type}
        value={value}
        readOnly={readOnly}
        placeholder={placeholder}
        onChange={(event) => onChange(event.target.value)}
        className="ops-input"
      />
    </label>
  );
}
