"use client";
import { useState } from "react";
import { Plus, Trash2 } from "lucide-react";
import { Badge, Button, Card, Field, Input, PageHeader, Select, Sheet, api, useAction, useUI } from "@/components/ui";
import { useApi } from "@/components/hooks";

export default function FieldsPage() {
  const fields = useApi<{ data: any[] }>("/custom-fields");
  const objects = useApi<{ data: any[] }>("/custom-objects");
  const [newField, setNewField] = useState(false);
  const [newObj, setNewObj] = useState(false);
  const [records, setRecords] = useState<any | null>(null);
  const { confirm } = useUI();
  return (
    <>
      <PageHeader title="Fields & objects" subtitle="Custom fields are usable in filters, segments, journeys, forms and the API" />
      <div className="space-y-4">
        <Card title="Contact custom fields" actions={<Button size="sm" variant="primary" icon={<Plus className="h-3.5 w-3.5" />} onClick={() => setNewField(true)}>Add field</Button>} bodyClass="p-0">
          <table className="table-mac">
            <thead><tr><th>Label</th><th>Key (API)</th><th>Type</th><th>Options</th><th /></tr></thead>
            <tbody>{fields.data?.data.map((f) => (
              <tr key={f.id}><td className="font-medium">{f.label}</td><td className="font-mono text-[12px]">custom.{f.key}</td><td><Badge>{f.type}</Badge></td><td className="max-w-[300px] truncate text-ink-3">{f.options.join(", ") || "—"}</td>
                <td className="text-right"><button aria-label="Delete" className="text-ink-3 hover:text-bad" onClick={async () => { if (await confirm({ title: `Delete field “${f.label}”?`, body: "Existing values stay on contacts but the field disappears from forms and filters.", danger: true, confirmLabel: "Delete" })) { await api(`/custom-fields/${f.id}`, { method: "DELETE" }); fields.reload(); } }}><Trash2 className="h-4 w-4" /></button></td></tr>
            ))}</tbody>
          </table>
        </Card>
        <Card title="Custom objects" subtitle="E.g. Property, Unit, Booking — linked to contacts and shown on their profile" actions={<Button size="sm" variant="primary" icon={<Plus className="h-3.5 w-3.5" />} onClick={() => setNewObj(true)}>Define object</Button>}>
          <div className="grid gap-3 md:grid-cols-2">
            {objects.data?.data.map((o) => (
              <div key={o.id} className="rounded-[10px] border border-line p-3">
                <div className="flex items-center justify-between"><span className="font-semibold">{o.label}</span><code className="text-[11px] text-ink-3">{o.key}</code></div>
                <div className="mt-2 flex flex-wrap gap-1">{o.fields.map((f: any) => <Badge key={f.key}>{f.label} · {f.type}</Badge>)}</div>
                <Button size="sm" className="mt-3" onClick={() => setRecords(o)}>View records</Button>
              </div>
            ))}
          </div>
        </Card>
      </div>
      {newField && <FieldSheet onClose={() => setNewField(false)} onDone={() => { setNewField(false); fields.reload(); }} />}
      {newObj && <ObjectSheet onClose={() => setNewObj(false)} onDone={() => { setNewObj(false); objects.reload(); }} />}
      {records && <RecordsSheet obj={records} onClose={() => setRecords(null)} />}
    </>
  );
}

function FieldSheet({ onClose, onDone }: { onClose: () => void; onDone: () => void }) {
  const [f, setF] = useState({ label: "", key: "", type: "text", options: "" });
  const { busy, run } = useAction();
  return (
    <Sheet open onClose={onClose} width={440} title="Add custom field" footer={<><Button onClick={onClose}>Cancel</Button><Button variant="primary" loading={busy} onClick={() => run(async () => { await api("/custom-fields", { body: { label: f.label, key: f.key || f.label.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, ""), type: f.type, options: f.options.split(",").map((x) => x.trim()).filter(Boolean) } }); onDone(); }, "Field added")}>Add</Button></>}>
      <div className="space-y-3">
        <Field label="Label"><Input value={f.label} onChange={(e) => setF({ ...f, label: e.target.value })} placeholder="Preferred floor" /></Field>
        <Field label="Key" hint="Auto-generated from the label if empty"><Input value={f.key} onChange={(e) => setF({ ...f, key: e.target.value.toLowerCase().replace(/[^a-z0-9_]/g, "_") })} /></Field>
        <Field label="Type"><Select value={f.type} onChange={(e) => setF({ ...f, type: e.target.value })}><option value="text">Text</option><option value="number">Number</option><option value="date">Date</option><option value="dropdown">Dropdown</option><option value="multiselect">Multi-select</option></Select></Field>
        {(f.type === "dropdown" || f.type === "multiselect") && <Field label="Options" hint="Comma separated"><Input value={f.options} onChange={(e) => setF({ ...f, options: e.target.value })} /></Field>}
      </div>
    </Sheet>
  );
}

function ObjectSheet({ onClose, onDone }: { onClose: () => void; onDone: () => void }) {
  const [label, setLabel] = useState("");
  const [fields, setFields] = useState([{ key: "name", label: "Name", type: "text" }]);
  const { busy, run } = useAction();
  return (
    <Sheet open onClose={onClose} width={520} title="Define custom object" footer={<><Button onClick={onClose}>Cancel</Button><Button variant="primary" loading={busy} onClick={() => run(async () => { await api("/custom-objects", { body: { label, fields } }); onDone(); }, "Object defined")}>Create</Button></>}>
      <div className="space-y-3">
        <Field label="Object name"><Input value={label} onChange={(e) => setLabel(e.target.value)} placeholder="Booking" /></Field>
        {fields.map((f, i) => (
          <div key={i} className="flex gap-2"><Input placeholder="Label" value={f.label} onChange={(e) => setFields(fields.map((x, j) => (j === i ? { ...x, label: e.target.value, key: e.target.value.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "") || x.key } : x)))} />
            <Select className="w-[130px]" value={f.type} onChange={(e) => setFields(fields.map((x, j) => (j === i ? { ...x, type: e.target.value } : x)))}><option value="text">Text</option><option value="number">Number</option><option value="date">Date</option></Select>
            <button aria-label="Remove" onClick={() => setFields(fields.filter((_, j) => j !== i))} className="text-ink-3 hover:text-bad"><Trash2 className="h-4 w-4" /></button></div>
        ))}
        <Button size="sm" variant="ghost" icon={<Plus className="h-3.5 w-3.5" />} onClick={() => setFields([...fields, { key: `field_${fields.length + 1}`, label: "", type: "text" }])}>Add field</Button>
      </div>
    </Sheet>
  );
}

function RecordsSheet({ obj, onClose }: { obj: any; onClose: () => void }) {
  const r = useApi<{ data: any[] }>(`/custom-objects/${obj.key}/records`);
  return (
    <Sheet open onClose={onClose} width={760} title={`${obj.label} records`}>
      <table className="table-mac"><thead><tr><th>Contact</th>{obj.fields.map((f: any) => <th key={f.key}>{f.label}</th>)}</tr></thead>
        <tbody>{r.data?.data.map((x) => <tr key={x.id}><td>{x.contact ? <a className="text-brand" href={`/contacts/${x.contact.id}`}>{x.contact.name}</a> : "—"}</td>{obj.fields.map((f: any) => <td key={f.key}>{String(x.data[f.key] ?? "—")}</td>)}</tr>)}</tbody></table>
      {r.data && !r.data.data.length && <p className="py-6 text-center text-[13px] text-ink-3">No records yet — create them via the API (POST /v1/custom-objects/{obj.key}/records).</p>}
    </Sheet>
  );
}
