"use client";
import { useState } from "react";
import { Panel, PreviewNotice } from "@/components/shared/page";
import { Field, SelectField } from "@/components/shared/field";
import { Button } from "@/components/ui/button";
import { locations } from "@/features/locations/fixtures";
import { Participants } from "./participants";
import { Deductions } from "./deductions";
import {
  validateContract,
  contractTypes,
  contractTypeLabels,
  type BusinessContract,
} from "./model";
export function ContractForm({
  initial,
  existing,
  onSave,
  onCancel,
}: {
  initial: BusinessContract;
  existing: BusinessContract[];
  onSave: (row: BusinessContract) => void;
  onCancel: () => void;
}) {
  const [draft, setDraft] = useState(initial),
    [error, setError] = useState("");
  const change = (
    key: keyof BusinessContract,
    value: string | number | boolean,
  ) => setDraft({ ...draft, [key]: value });
  return (
    <div className="space-y-5">
      <PreviewNotice>
        Contract changes, participants, and terms are saved locally in this
        browser session.
      </PreviewNotice>
      <Panel title={initial.id ? "Edit Contract" : "Create Business Contract"}>
        <form
          id="contract-form"
          className="grid gap-5 p-5 md:grid-cols-2 xl:grid-cols-3"
          onSubmit={(event) => {
            event.preventDefault();
            const message = validateContract(draft, existing);
            if (message) {
              setError(message);
              return;
            }
            onSave({
              ...draft,
              id: draft.id || `contract-preview-${crypto.randomUUID()}`,
              name: draft.name.trim(),
              code: draft.code.trim(),
              updated: "2026-10-15",
            });
          }}
        >
          <SelectField
            label="Contract Status"
            value={draft.status}
            options={["DRAFT", "ACTIVE", "ENDED"]}
            onChange={(event) => change("status", event.target.value)}
          />
          <SelectField
            label="Contract Type"
            value={draft.type}
            options={contractTypes.map((value) => ({
              value,
              label: contractTypeLabels[value],
            }))}
            onChange={(event) => change("type", event.target.value)}
          />
          <Field label="Organization" value={draft.organization} readOnly />
          <Field
            label="Contract Name"
            value={draft.name}
            required
            onChange={(event) => change("name", event.target.value)}
          />
          <Field
            label="Contract Code"
            value={draft.code}
            required
            onChange={(event) => change("code", event.target.value)}
          />
          <SelectField
            label="Currency"
            value={draft.currency}
            options={["IDR"]}
            onChange={(event) => change("currency", event.target.value)}
          />
          <SelectField
            label="Settlement Cycle"
            value={draft.cycle}
            options={["MONTHLY", "QUARTAL", "SEMESTER", "YEARLY"]}
            onChange={(event) => change("cycle", event.target.value)}
          />
          <Field
            label="Start Date"
            type="date"
            required
            value={draft.start}
            onChange={(event) => change("start", event.target.value)}
          />
          <Field
            label="End Date (Optional)"
            type="date"
            min={draft.start}
            value={draft.end}
            onChange={(event) => change("end", event.target.value)}
          />
          <Field
            label="Settlement Lag Days"
            type="number"
            min={0}
            step={1}
            required
            value={draft.lag}
            onChange={(event) => change("lag", Number(event.target.value))}
          />
          <Field
            label="Priority"
            type="number"
            min={0}
            step={1}
            required
            value={draft.priority}
            onChange={(event) => change("priority", Number(event.target.value))}
          />
          <div>
            <Field
              label="Reference Contract PDF"
              type="file"
              accept="application/pdf,.pdf"
              onChange={(event) => {
                const file = event.target.files?.[0];
                if (
                  file &&
                  file.type !== "application/pdf" &&
                  !file.name.toLowerCase().endsWith(".pdf")
                ) {
                  setError("Choose a PDF document.");
                  return;
                }
                change("reference", file?.name ?? "");
              }}
            />
            {draft.reference && (
              <p className="mt-2 text-xs text-muted-foreground">
                {draft.reference} · filename preview only
              </p>
            )}
          </div>
          <fieldset className="space-y-3 md:col-span-2 xl:col-span-3">
            <legend className="mb-3 text-sm font-medium">Location IDs *</legend>
            <div className="grid gap-3 sm:grid-cols-2">
              {locations.map((location) => (
                <label
                  key={location.id}
                  className={`flex items-center gap-3 rounded-lg border p-4 text-sm ${draft.locationIds.includes(location.id) ? "border-primary bg-primary/5" : ""}`}
                >
                  <input
                    type="checkbox"
                    checked={draft.locationIds.includes(location.id)}
                    onChange={(event) =>
                      setDraft({
                        ...draft,
                        locationIds: event.target.checked
                          ? [...draft.locationIds, location.id]
                          : draft.locationIds.filter(
                              (id) => id !== location.id,
                            ),
                      })
                    }
                  />
                  <span>
                    {location.name}
                    <small className="block text-muted-foreground">
                      {location.city}
                    </small>
                  </span>
                </label>
              ))}
            </div>
            <label className="flex items-center gap-2 text-sm">
              <input
                type="checkbox"
                checked={draft.displayVat}
                onChange={(event) => change("displayVat", event.target.checked)}
              />
              Display BM Share VAT
            </label>
          </fieldset>
        </form>
      </Panel>
      <Participants
        participants={draft.participants}
        onChange={(participants) => setDraft({ ...draft, participants })}
      />
      <Deductions
        deductions={draft.deductions}
        onChange={(deductions) => setDraft({ ...draft, deductions })}
      />
      {error && (
        <p role="alert" className="text-sm text-destructive">
          {error}
        </p>
      )}
      <div className="flex justify-end gap-3">
        <Button variant="outline" onClick={onCancel}>
          Cancel
        </Button>
        <Button form="contract-form" type="submit">
          Save Contract Preview
        </Button>
      </div>
    </div>
  );
}
