"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 { formatCurrencyAmount } from "@/lib/formatters";
import type { ApiErrorResponse, DetailResponse } from "@/types/api";
import type {
  AgentDetailRecord,
  AgentRecord,
  BankRecord,
  ProfitShareSchemeRecord
} from "@/types/master-data";

type BankAccountForm = {
  bank_id: string;
  account_number: string;
};

type AgentForm = {
  code: string;
  name: string;
  identity_type: "KTP" | "SIM" | "PASSPORT";
  identity_number: string;
  mobile_phone: string;
  email: string;
  address: string;
  notes: string;
  join_date: string;
  profit_share_scheme_id: string;
  profit_share_balance: string;
  capital_balance: string;
  bank_accounts: BankAccountForm[];
};

const emptyBankAccount = (): BankAccountForm => ({
  bank_id: "",
  account_number: ""
});

const emptyForm = (): AgentForm => ({
  code: "",
  name: "",
  identity_type: "KTP",
  identity_number: "",
  mobile_phone: "",
  email: "",
  address: "",
  notes: "",
  join_date: new Date().toISOString().slice(0, 10),
  profit_share_scheme_id: "",
  profit_share_balance: "0",
  capital_balance: "0",
  bank_accounts: [emptyBankAccount()]
});

export function AgentsClient() {
  const { dict, locale } = useLocale();
  const { canEditCode } = useCurrentUser();
  const [agents, setAgents] = useState<AgentRecord[]>([]);
  const [search, setSearch] = useState("");
  const [banks, setBanks] = useState<BankRecord[]>([]);
  const [schemes, setSchemes] = useState<ProfitShareSchemeRecord[]>([]);
  const [form, setForm] = useState<AgentForm>(emptyForm);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [selectedAgentId, setSelectedAgentId] = useState<string | null>(null);
  const [selectedAgentDetail, setSelectedAgentDetail] = useState<AgentDetailRecord | null>(null);
  const [detailLoading, setDetailLoading] = useState(false);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const filteredAgents = useMemo(() => {
    const keyword = search.trim().toLowerCase();
    if (!keyword) return agents;
    return agents.filter((agent) =>
      [
        agent.code,
        agent.name,
        agent.identity_type,
        agent.identity_number,
        agent.mobile_phone ?? "",
        agent.email ?? "",
        agent.address ?? "",
        agent.profit_share_scheme.code,
        agent.profit_share_scheme.name
      ].some((value) => value.toLowerCase().includes(keyword))
    );
  }, [agents, search]);
  const pagination = usePagination(filteredAgents, 20);

  async function loadData() {
    setLoading(true);
    setError(null);

    try {
      const [agentsResponse, banksResponse, schemesResponse] = await Promise.all([
        fetch("/api/v1/agents", { cache: "no-store" }),
        fetch("/api/v1/banks", { cache: "no-store" }),
        fetch("/api/v1/profit-share-schemes", { cache: "no-store" })
      ]);

      const agentsPayload = (await agentsResponse.json()) as { data: AgentRecord[] };
      const banksPayload = (await banksResponse.json()) as { data: BankRecord[] };
      const schemesPayload = (await schemesResponse.json()) as { data: ProfitShareSchemeRecord[] };

      if (!agentsResponse.ok || !banksResponse.ok || !schemesResponse.ok) {
        throw new Error(dict.master.loadError);
      }

      setAgents(agentsPayload.data);
      setBanks(banksPayload.data.filter((bank) => bank.status === "ACTIVE"));
      setSchemes(schemesPayload.data.filter((scheme) => scheme.status === "ACTIVE"));
    } catch (err) {
      setError(err instanceof Error ? err.message : dict.master.loadError);
    } finally {
      setLoading(false);
    }
  }

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

  async function openDetail(id: string) {
    setSelectedAgentId(id);
    setDetailLoading(true);

    try {
      const response = await fetch(`/api/v1/agents/${id}/detail`, { cache: "no-store" });
      const payload = (await response.json()) as DetailResponse<AgentDetailRecord> | ApiErrorResponse;

      if (!response.ok || !("data" in payload)) {
        throw new Error("message" in payload ? payload.message : dict.common.requestFailed);
      }

      setSelectedAgentDetail(payload.data);
    } catch (err) {
      setError(err instanceof Error ? err.message : dict.common.requestFailed);
    } finally {
      setDetailLoading(false);
    }
  }

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

  function startEdit(agent: AgentRecord) {
    setEditingId(agent.id);
    setForm({
      code: agent.code,
      name: agent.name,
      identity_type: agent.identity_type,
      identity_number: agent.identity_number,
      mobile_phone: agent.mobile_phone ?? "",
      email: agent.email ?? "",
      address: agent.address ?? "",
      notes: agent.notes ?? "",
      join_date: agent.join_date,
      profit_share_scheme_id: agent.profit_share_scheme.id,
      profit_share_balance: String(agent.profit_share_balance),
      capital_balance: String(agent.capital_balance),
      bank_accounts:
        agent.bank_accounts.length > 0
          ? agent.bank_accounts.map((account) => ({
              bank_id: account.bank_id,
              account_number: account.account_number
            }))
          : [emptyBankAccount()]
    });
    setError(null);
  }

  function updateBankAccount(index: number, patch: Partial<BankAccountForm>) {
    setForm((current) => ({
      ...current,
      bank_accounts: current.bank_accounts.map((account, itemIndex) =>
        itemIndex === index ? { ...account, ...patch } : account
      )
    }));
  }

  function addBankAccount() {
    setForm((current) => ({
      ...current,
      bank_accounts: [...current.bank_accounts, emptyBankAccount()]
    }));
  }

  function removeBankAccount(index: number) {
    setForm((current) => ({
      ...current,
      bank_accounts:
        current.bank_accounts.length === 1
          ? current.bank_accounts
          : current.bank_accounts.filter((_, itemIndex) => itemIndex !== index)
    }));
  }

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

    try {
      const response = await fetch(editingId ? `/api/v1/agents/${editingId}` : "/api/v1/agents", {
        method: editingId ? "PUT" : "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...form,
          profit_share_balance: Number(form.profit_share_balance || 0),
          capital_balance: Number(form.capital_balance || 0)
        })
      });

      const payload = (await response.json()) as DetailResponse<AgentRecord> | 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 loadData();
      if (selectedAgentId) {
        await openDetail(selectedAgentId);
      }
    } 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} agen ini?`)) return;

    try {
      const response = await fetch(`/api/v1/agents/${id}`, { method: "DELETE" });
      if (!response.ok) {
        const payload = (await response.json()) as ApiErrorResponse;
        throw new Error(payload.message);
      }

      if (editingId === id) resetForm();
      if (selectedAgentId === id) {
        setSelectedAgentId(null);
        setSelectedAgentDetail(null);
      }
      await loadData();
    } catch (err) {
      setError(err instanceof Error ? err.message : dict.master.deleteError);
    }
  }

  function getSchemeLabel(scheme: AgentRecord["profit_share_scheme"]) {
    return `${scheme.code} - ${scheme.name}`;
  }

  return (
    <section className="grid gap-6 xl:grid-cols-[1.02fr_0.98fr]">
      <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} Agen` : `${dict.master.add} Agen`}
            </h2>
            <p className="mt-3 text-[13px] leading-6 text-slate-500">
              Master agen dengan identitas, skema bagi hasil, saldo berjalan, dan multi rekening bank.
            </p>
          </div>
          {editingId ? <button type="button" onClick={resetForm} className="ops-btn-secondary">{dict.common.cancelEdit}</button> : null}
        </div>

        <form className="mt-6 space-y-5" onSubmit={handleSubmit}>
          <div className="grid gap-4 md:grid-cols-2">
            <Field
              label={dict.master.code}
              value={form.code}
              readOnly={!canEditCode}
              placeholder={canEditCode ? "AGT00001" : "Auto"}
              onChange={(value) => setForm((current) => ({ ...current, code: value }))}
            />
            <Field label="Nama" value={form.name} onChange={(value) => setForm((current) => ({ ...current, name: value }))} />
            <SelectField
              label="Jenis identitas"
              value={form.identity_type}
              onChange={(value) => setForm((current) => ({ ...current, identity_type: value as AgentForm["identity_type"] }))}
              options={[
                { value: "KTP", label: "KTP" },
                { value: "SIM", label: "SIM" },
                { value: "PASSPORT", label: locale === "id" ? "Paspor" : "Passport" }
              ]}
            />
            <Field label="Nomor identitas" value={form.identity_number} onChange={(value) => setForm((current) => ({ ...current, identity_number: value }))} />
            <Field label="Mobile phone" value={form.mobile_phone} onChange={(value) => setForm((current) => ({ ...current, mobile_phone: value }))} />
            <Field label="Email" value={form.email} onChange={(value) => setForm((current) => ({ ...current, email: value }))} />
            <Field label="Join date" type="date" value={form.join_date} onChange={(value) => setForm((current) => ({ ...current, join_date: value }))} />
            <Field label="Saldo bagi hasil" type="number" value={form.profit_share_balance} onChange={(value) => setForm((current) => ({ ...current, profit_share_balance: value }))} />
            <Field label="Saldo modal" type="number" value={form.capital_balance} onChange={(value) => setForm((current) => ({ ...current, capital_balance: value }))} />
            <div className="md:col-span-2">
              <SelectField
                label="Skema bagi hasil"
                value={form.profit_share_scheme_id}
                onChange={(value) => setForm((current) => ({ ...current, profit_share_scheme_id: value }))}
                options={schemes.map((scheme) => ({
                  value: scheme.id,
                  label: `${scheme.code} - ${scheme.name} (${scheme.share_agent}% / ${scheme.share_company}%)`
                }))}
                placeholder={locale === "id" ? "Pilih skema bagi hasil" : "Choose profit share scheme"}
              />
            </div>
          </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={3} className="ops-textarea" />
          </label>

          <label className="block">
            <span className="ops-label">{dict.common.notes}</span>
            <textarea value={form.notes} onChange={(event) => setForm((current) => ({ ...current, notes: event.target.value }))} rows={3} className="ops-textarea" />
          </label>

          <div className="rounded-lg border border-line/70 bg-slate-50/70 p-4">
            <div className="flex items-center justify-between">
              <h3 className="text-lg font-semibold text-ink">Daftar rekening bank</h3>
              <button type="button" onClick={addBankAccount} className="ops-btn-secondary">Tambah rekening</button>
            </div>
            <div className="mt-4 space-y-4">
              {form.bank_accounts.map((account, index) => (
                <div key={index} className="rounded border border-line/70 bg-white p-4">
                  <div className="grid gap-4 md:grid-cols-2">
                    <SelectField
                      label="Bank"
                      value={account.bank_id}
                      onChange={(value) => updateBankAccount(index, { bank_id: value })}
                      options={banks.map((bank) => ({ value: bank.id, label: `${bank.code} - ${bank.name}` }))}
                      placeholder={locale === "id" ? "Pilih bank" : "Choose bank"}
                    />
                    <Field
                      label="Nomor rekening"
                      value={account.account_number}
                      onChange={(value) => updateBankAccount(index, { account_number: value })}
                    />
                  </div>
                  <div className="mt-4 flex justify-end">
                    <button type="button" onClick={() => removeBankAccount(index)} className="ops-btn-danger">
                      Hapus rekening
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {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} agen` : `${dict.master.add} agen`}
          </button>
        </form>
      </div>

      <div className="ops-table-shell">
        <div className="ops-section-head">
          <div>
            <p className="ops-title">{dict.master.list} Agen</p>
            <p className="ops-copy">Master agen dan profil bagi hasil yang siap dipakai di tahap berikutnya.</p>
          </div>
          <div className="ops-chip-muted">{agents.length} {dict.master.dataCount}</div>
        </div>
        {!loading && agents.length > 0 ? (
          <div className="border-t border-line/70 px-6 py-4">
            <label className="block">
              <span className="ops-label">Cari agen</span>
              <input
                value={search}
                onChange={(event) => setSearch(event.target.value)}
                placeholder="Cari code, nama, identitas, skema..."
                className="ops-input"
              />
            </label>
          </div>
        ) : null}

        {loading ? (
          <div className="px-6 py-8 text-sm text-ink/60">{dict.common.loading}</div>
        ) : agents.length === 0 ? (
          <div className="px-6 py-8 text-sm text-ink/60">{dict.master.noData}</div>
        ) : filteredAgents.length === 0 ? (
          <div className="px-6 py-8 text-sm text-ink/60">Tidak ada agen yang cocok dengan pencarian.</div>
        ) : (
          <>
            <div className="overflow-x-auto">
            <table className="ops-table">
              <thead>
                <tr>
                  <th>{dict.master.code}</th>
                  <th>Agen</th>
                  <th>Identitas</th>
                  <th>Skema</th>
                  <th>Saldo bagi hasil</th>
                  <th>Saldo modal</th>
                  <th>Rekening</th>
                  <th>{dict.common.actions}</th>
                </tr>
              </thead>
              <tbody>
                {pagination.pagedItems.map((agent) => (
                  <tr key={agent.id}>
                    <td className="font-semibold text-ink">{agent.code}</td>
                    <td>
                      <div className="font-medium text-ink">{agent.name}</div>
                      <div className="mt-1 text-xs text-slate-500">
                        {agent.mobile_phone || "-"} · {agent.email || "-"}
                      </div>
                    </td>
                    <td className="text-slate-600">
                      <div>{agent.identity_type}</div>
                      <div className="mt-1 text-xs">{agent.identity_number}</div>
                    </td>
                    <td className="text-slate-600">
                      <div>{getSchemeLabel(agent.profit_share_scheme)}</div>
                      <div className="mt-1 text-xs">
                        {agent.profit_share_scheme.share_agent}% / {agent.profit_share_scheme.share_company}%
                      </div>
                    </td>
                    <td className="text-slate-600">{formatCurrencyAmount(agent.profit_share_balance, "id", "IDR", 0)}</td>
                    <td className="text-slate-600">{formatCurrencyAmount(agent.capital_balance, "id", "IDR", 0)}</td>
                    <td className="text-slate-600">
                      {agent.bank_accounts.length === 0 ? (
                        "-"
                      ) : (
                        agent.bank_accounts.map((account) => (
                          <div key={account.id} className="mt-1 first:mt-0">
                            <div>{account.bank_code} - {account.bank_name}</div>
                            <div className="text-xs">{account.account_number}</div>
                          </div>
                        ))
                      )}
                    </td>
                    <td>
                      <div className="flex gap-2">
                        <button type="button" onClick={() => void openDetail(agent.id)} className="ops-btn-secondary">Detail</button>
                        <button type="button" onClick={() => startEdit(agent)} className="ops-btn-secondary">{dict.common.edit}</button>
                        <button type="button" onClick={() => void handleDelete(agent.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="agen"
              onPrev={() => pagination.setPage((current) => Math.max(1, current - 1))}
              onNext={() => pagination.setPage((current) => Math.min(pagination.totalPages, current + 1))}
            />

            <div className="border-t border-line/70 px-6 py-5">
              {detailLoading ? (
                <div className="text-sm text-ink/60">Memuat detail agen...</div>
              ) : selectedAgentDetail ? (
                <AgentDetailPanel detail={selectedAgentDetail} />
              ) : (
                <div className="text-sm text-ink/60">Pilih agen untuk melihat detail informasi dan histori saldo.</div>
              )}
            </div>
          </>
        )}
      </div>
    </section>
  );
}

function AgentDetailPanel({ detail }: { detail: AgentDetailRecord }) {
  return (
    <div className="space-y-5">
      <div className="flex flex-wrap items-start justify-between gap-4">
        <div>
          <p className="ops-overline">Detail agen</p>
          <h3 className="mt-2 text-2xl font-semibold tracking-tight text-ink">{detail.code} · {detail.name}</h3>
          <p className="mt-2 text-sm text-slate-500">
            {detail.identity_type} · {detail.identity_number} · Join {formatDate(detail.join_date)}
          </p>
        </div>
        <div className="rounded-xl border border-line/70 bg-slate-50 px-4 py-3 text-right">
          <p className="text-xs font-semibold uppercase tracking-[0.24em] text-slate-500">Saldo bagi hasil</p>
          <p className="mt-2 text-2xl font-semibold text-ink">{formatCurrencyAmount(detail.profit_share_balance, "id", "IDR", 0)}</p>
          <p className="mt-3 text-xs font-semibold uppercase tracking-[0.24em] text-slate-500">Saldo modal</p>
          <p className="mt-2 text-xl font-semibold text-ink">{formatCurrencyAmount(detail.capital_balance, "id", "IDR", 0)}</p>
        </div>
      </div>

      <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
        <DetailCard label="Skema bagi hasil" value={`${detail.profit_share_scheme.code} · ${detail.profit_share_scheme.name}`} hint={`${detail.profit_share_scheme.share_agent}% agen / ${detail.profit_share_scheme.share_company}% perusahaan`} />
        <DetailCard label="Kontak" value={detail.mobile_phone || "-"} hint={detail.email || "Email tidak ada"} />
        <DetailCard label="Alamat" value={detail.address || "-"} hint={detail.notes || "Tidak ada catatan"} />
        <DetailCard
          label="Statistik"
          value={`${detail.stats.purchase_count} pembelian`}
          hint={`${detail.stats.consignment_close_count} titip jual closed · ${detail.stats.regular_sale_close_count} penjualan reguler closed`}
        />
      </div>

      <div className="rounded-xl border border-line/70 bg-white">
        <div className="border-b border-line/70 px-4 py-3">
          <p className="text-sm font-semibold text-ink">Rekening bank</p>
        </div>
        <div className="grid gap-3 p-4 md:grid-cols-2">
          {detail.bank_accounts.length === 0 ? (
            <div className="text-sm text-ink/60">Belum ada rekening bank.</div>
          ) : (
            detail.bank_accounts.map((account) => (
              <div key={account.id} className="rounded-lg border border-line/70 bg-slate-50/60 px-4 py-3">
                <div className="text-sm font-medium text-ink">{account.bank_code} · {account.bank_name}</div>
                <div className="mt-1 text-sm text-slate-600">{account.account_number}</div>
              </div>
            ))
          )}
        </div>
      </div>

      <div className="rounded-xl border border-line/70 bg-white">
        <div className="flex items-center justify-between gap-3 border-b border-line/70 px-4 py-3">
          <div>
            <p className="text-sm font-semibold text-ink">Histori saldo</p>
            <p className="mt-1 text-xs text-slate-500">
              Riwayat penambahan dan pengurangan saldo dari komisi agen maupun penyesuaian manual.
            </p>
          </div>
          <div className="rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-600">
            {detail.stats.history_count} mutasi
          </div>
        </div>

        {detail.balance_history.length === 0 ? (
          <div className="px-4 py-6 text-sm text-ink/60">Belum ada histori saldo.</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="ops-table">
              <thead>
                <tr>
                  <th>Tanggal</th>
                  <th>Jenis saldo</th>
                  <th>Sumber</th>
                  <th>Referensi</th>
                  <th>Keterangan</th>
                  <th>Mutasi</th>
                  <th>Saldo akhir</th>
                </tr>
              </thead>
              <tbody>
                {detail.balance_history
                  .slice()
                  .reverse()
                  .map((entry) => (
                    <tr key={entry.id}>
                      <td className="text-slate-600">{formatDate(entry.effective_date ?? entry.occurred_at.slice(0, 10))}</td>
                      <td className="text-slate-600">{getBalanceTypeLabel(entry.balance_type)}</td>
                      <td className="text-slate-600">{getHistorySourceLabel(entry.source)}</td>
                      <td className="text-slate-600">{entry.reference_no ?? "-"}</td>
                      <td className="text-slate-600">
                        <div>{entry.description}</div>
                        {entry.notes ? <div className="mt-1 text-xs text-slate-500">{entry.notes}</div> : null}
                      </td>
                      <td className={entry.direction === "IN" ? "font-medium text-moss-700" : "font-medium text-rose-700"}>
                        {entry.direction === "IN" ? "+" : "-"}{formatCurrencyAmount(entry.amount, "id", "IDR", 0)}
                      </td>
                      <td className="font-medium text-ink">{formatCurrencyAmount(entry.balance_after, "id", "IDR", 0)}</td>
                    </tr>
                  ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}

function DetailCard({
  label,
  value,
  hint
}: {
  label: string;
  value: string;
  hint?: string;
}) {
  return (
    <div className="rounded-xl border border-line/70 bg-slate-50/70 px-4 py-3">
      <p className="text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-500">{label}</p>
      <p className="mt-2 text-sm font-medium text-ink">{value}</p>
      {hint ? <p className="mt-1 text-xs leading-5 text-slate-500">{hint}</p> : null}
    </div>
  );
}

function formatDate(value: string) {
  const parsed = new Date(`${value}T00:00:00`);
  if (Number.isNaN(parsed.getTime())) return value;
  return new Intl.DateTimeFormat("id-ID", { day: "numeric", month: "short", year: "numeric" }).format(parsed);
}

function getHistorySourceLabel(source: AgentDetailRecord["balance_history"][number]["source"]) {
  switch (source) {
    case "OPENING_BALANCE":
      return "Saldo pembuka";
    case "MANUAL_ADJUSTMENT":
      return "Manual";
    case "CONSIGNMENT_COMMISSION":
      return "Titip jual";
    case "REGULAR_SALE_COMMISSION":
      return "Penjualan reguler";
    case "JIT_SALE_COMMISSION":
      return "Penjualan JIT";
    case "OFFICE_BUYOUT_COMMISSION":
      return "Buyout kantor";
    case "FUND_REQUEST_PROFIT_SHARE":
      return "Transfer bagi hasil";
    case "FUND_REQUEST_CAPITAL":
      return "Transfer modal";
    default:
      return source;
  }
}

function getBalanceTypeLabel(type: AgentDetailRecord["balance_history"][number]["balance_type"]) {
  switch (type) {
    case "PROFIT_SHARE":
      return "Bagi hasil";
    case "CAPITAL":
      return "Modal";
    default:
      return type;
  }
}

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>
  );
}

function SelectField({
  label,
  value,
  onChange,
  options,
  placeholder
}: {
  label: string;
  value: string;
  onChange: (value: string) => void;
  options: Array<{ value: string; label: string }>;
  placeholder?: string;
}) {
  const { locale } = useLocale();
  return (
    <label className="block">
      <span className="ops-label">{label}</span>
      <select value={value} onChange={(event) => onChange(event.target.value)} className="ops-select">
        {placeholder ? (
          <option value="">{placeholder}</option>
        ) : (
          <option value="">{locale === "id" ? "Pilih opsi" : "Choose option"}</option>
        )}
        {options.map((option) => (
          <option key={option.value} value={option.value}>
            {option.label}
          </option>
        ))}
      </select>
    </label>
  );
}
