import { Breadcrumb } from "@/layouts/Breadcrumb";
import { FieldLabel, cleanLabel } from "@/components/FieldLabel";
import type { RecordSpec, PageSpec, DataRow } from "@/types/spec";
import type { TableData } from "@/hooks/useData";

interface FormViewProps {
  page: PageSpec;
  rec: RecordSpec;
  allRecords: RecordSpec[];
  allData: TableData;
  tabName: string;
  onBack: () => void;
  onSubmit: (table: string, data: Record<string, unknown>) => void;
}

export function FormView({ page, rec, allRecords, allData, tabName, onBack, onSubmit }: FormViewProps) {
  const required = rec.required || [];

  function handleSubmit(e: Event) {
    e.preventDefault();
    const form = e.target as HTMLFormElement;
    const data: Record<string, unknown> = Object.fromEntries(new FormData(form));
    // Type coercion
    for (const [k, field] of Object.entries(rec.fields)) {
      if (field.type === "number" && data[k]) data[k] = parseFloat(String(data[k]));
      if (field.type === "boolean") data[k] = data[k] === "on" ? 1 : 0;
    }
    onSubmit(page.record!, data);
    form.reset();
  }

  const inputCls = "w-full rounded-[var(--z-radius-input)] px-3 py-2.5 text-[var(--z-font-md)] outline-none transition-all";
  const inputStyle = { background: "var(--z-card-bg)", border: "1px solid var(--z-border)", color: "var(--z-text)" };

  return (
    <div>
      <Breadcrumb items={[{ label: tabName, onClick: onBack }, { label: `New ${rec.name}` }]} />
      <h2 class="text-lg font-semibold mb-5">New {rec.name}</h2>

      <form onSubmit={handleSubmit} class="max-w-[480px] space-y-4">
        {Object.entries(rec.fields).map(([name, field]) => {
          if (field.type === "computed") return null;
          const isReq = required.includes(name);

          // FK selector
          if (field.type === "link" && field.link) {
            const linkedRec = allRecords.find((r) => r.table === field.link);
            const options = allData[field.link!] || [];
            const displayF = linkedRec?.display || "id";
            return (
              <div key={name}>
                <FieldLabel field={name} required={isReq} />
                <select name={`${name}_id`} required={isReq} class={`${inputCls} mt-1.5`} style={inputStyle}>
                  <option value="">Select {cleanLabel(name)}...</option>
                  {options.map((o: DataRow) => (
                    <option key={String(o.id)} value={String(o.id)}>{String(o[displayF] || o.id)}</option>
                  ))}
                </select>
              </div>
            );
          }

          // Choice chips
          if (field.type === "choice" && field.choices) {
            return (
              <div key={name}>
                <FieldLabel field={name} required={isReq} />
                <div class="flex flex-wrap gap-1.5 mt-1.5">
                  {field.choices.map((c, i) => (
                    <label
                      key={c}
                      class="px-3.5 py-1.5 rounded-full text-xs cursor-pointer transition-all"
                      style={{ border: "1px solid var(--z-border)", color: "var(--z-muted)" }}
                    >
                      <input type="radio" name={name} value={c} defaultChecked={i === 0} class="hidden peer" />
                      {c}
                    </label>
                  ))}
                </div>
              </div>
            );
          }

          if (field.type === "boolean") {
            return (
              <label key={name} class="flex items-center gap-3 cursor-pointer py-1">
                <input name={name} type="checkbox" class="w-4 h-4" style={{ accentColor: "var(--z-accent)" }} />
                <span class="text-[var(--z-font-md)]">{cleanLabel(name)}</span>
              </label>
            );
          }

          const inputType = field.type === "number" ? "number" : field.type === "date" ? "date" : "text";

          return (
            <div key={name}>
              <FieldLabel field={name} required={isReq} />
              <input
                name={name}
                type={inputType}
                step={field.type === "number" ? "any" : undefined}
                placeholder={`${cleanLabel(name)}...`}
                required={isReq}
                class={`${inputCls} mt-1.5`}
                style={inputStyle}
              />
            </div>
          );
        })}

        <button
          type="submit"
          class="w-full py-2.5 text-[var(--z-font-md)] font-medium rounded-[var(--z-radius-button)] text-white mt-2"
          style={{ background: "var(--z-accent)" }}
        >
          Add {rec.name}
        </button>
      </form>
    </div>
  );
}
