/* New recovery — opening a file against whoever caused a loss we have paid.
   Commit model: STAGED. Nothing exists until Save, Cancel appears once dirty,
   errors render on validation.
   Data state: the form, or the empty branch when every paid claim is already
   being pursued — one conditional, never both.

   The amount sought is never typed. It reads the settlement the claim actually
   paid, so the two sides of the same money can never drift apart (AGENTS §2:
   when two records describe the same money, one owns it and the other reads
   it). The clock on the right runs the same TimeBar geometry as everywhere. */
(() => {
  const {
    Card, CardHeader, CardTitle, CardDescription, CardPanel,
    Field, FieldLabel, FieldDescription, FieldError, Input, Textarea, Select, Button,
    Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription, EmptyContent,
  } = window.OriginDesignSystem_7c998b;

  const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
  const MIN_BASIS = 20;
  const EMPTY_DRAFT = { claimId: "", name: "", kind: "", contact: "", basis: "", fileBy: "" };

  const toDate = (value) => {
    if (!value) return null;
    const ms = Date.parse(value + "T09:00:00");
    return isNaN(ms) ? null : ms;
  };

  function NewRecoveryScreen({ data, now, onNavigate, onCreate }) {
    const [draft, setDraft] = React.useState(EMPTY_DRAFT);
    const [submitted, setSubmitted] = React.useState(false);
    const set = (fields) => setDraft(Object.assign({}, draft, fields));
    const dirty = JSON.stringify(draft) !== JSON.stringify(EMPTY_DRAFT);

    const eligible = claimsWithoutRecovery(data.claims);
    const claim = eligible.find((c) => c.id === draft.claimId) || null;
    const fileByAt = toDate(draft.fileBy);
    const daysLeft = fileByAt ? Math.round((fileByAt - now) / 864e5) : null;

    const errors = {};
    if (!draft.claimId) errors.claimId = "Pick the claim this recovery follows.";
    if (!draft.name.trim()) errors.name = "Name the party we are pursuing.";
    if (!draft.kind) errors.kind = "Say what they are — it decides which contract binds them.";
    if (!EMAIL.test(draft.contact)) errors.contact = "Enter the address notice will be served on.";
    if (draft.basis.trim().length < MIN_BASIS) errors.basis = "State the clause or liability the claim rests on.";
    if (!fileByAt) errors.fileBy = "Every recovery has a contractual deadline. Enter it.";
    else if (fileByAt <= now) errors.fileBy = "That deadline has already passed — there is nothing left to file.";
    const valid = Object.keys(errors).length === 0;

    const submit = () => {
      setSubmitted(true);
      if (!valid) return;
      onCreate({
        claimId: claim.id,
        counterparty: { name: draft.name.trim(), kind: draft.kind, contact: draft.contact.trim() },
        basis: draft.basis.trim(),
        fileByAt: fileByAt,
      });
    };

    if (eligible.length === 0) {
      return (
        <div className="cd-page">
          <PageHead path="/recovery/new" title="New recovery" lede="A recovery follows money that has already left the account." />
          <Empty>
            <EmptyHeader>
              <EmptyMedia variant="icon"><Icon name="check" size={18} /></EmptyMedia>
              <EmptyTitle>Every paid claim is already being pursued</EmptyTitle>
              <EmptyDescription>All {formatPlural(releasedClaims(data.claims).length, "settlement")} sent or cleared on this desk have a recovery file open against them. One opens here as soon as another payment is released.</EmptyDescription>
            </EmptyHeader>
            <EmptyContent>
              <Button onClick={() => onNavigate("/recovery")}>Open recovery</Button>
            </EmptyContent>
          </Empty>
        </div>
      );
    }

    return (
      <div className="cd-page">
        <PageHead
          path="/recovery/new"
          title="New recovery"
          lede={"A recovery follows money that has already left the account. " + formatPlural(eligible.length, "paid claim") + " on this desk " + (eligible.length === 1 ? "has" : "have") + " nobody being pursued for it."}
        />

        <div className="cd-split">
          <div className="cd-col">
            <Card>
              <CardHeader>
                <CardTitle>The claim we paid</CardTitle>
                <CardDescription>Only settlements the bank has taken can be recovered; the figure sought comes from the payment itself.</CardDescription>
              </CardHeader>
              <CardPanel>
                <Field>
                  <FieldLabel htmlFor="cd-r-claim">Claim</FieldLabel>
                  <Select
                    id="cd-r-claim"
                    placeholder="Pick a paid claim…"
                    items={eligible.map((c) => ({ value: c.id, label: c.id + " · " + c.customer + " · " + formatMoney(c.settlement.amountCents) }))}
                    value={draft.claimId}
                    invalid={submitted && !!errors.claimId}
                    onValueChange={(v) => set({ claimId: v })}
                  />
                  {submitted && errors.claimId ? <FieldError>{errors.claimId}</FieldError> : <FieldDescription>{formatPlural(eligible.length, "claim")} paid with no recovery open.</FieldDescription>}
                </Field>
              </CardPanel>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Who caused it</CardTitle>
                <CardDescription>Notice is served on this address, and the recovery rate is read by counterparty kind.</CardDescription>
              </CardHeader>
              <CardPanel>
                <div className="cd-fields">
                  <div className="cd-grid2">
                    <Field>
                      <FieldLabel htmlFor="cd-r-name">Counterparty</FieldLabel>
                      <Input id="cd-r-name" placeholder="Meridian Terminal Services" value={draft.name} invalid={submitted && !!errors.name} onChange={(e) => set({ name: e.target.value })} />
                      {submitted && errors.name ? <FieldError>{errors.name}</FieldError> : null}
                    </Field>
                    <Field>
                      <FieldLabel htmlFor="cd-r-kind">What they are</FieldLabel>
                      <Select id="cd-r-kind" placeholder="Pick one…" items={COUNTERPARTY_KINDS} value={draft.kind} invalid={submitted && !!errors.kind} onValueChange={(v) => set({ kind: v })} />
                      {submitted && errors.kind ? <FieldError>{errors.kind}</FieldError> : null}
                    </Field>
                  </div>
                  <Field>
                    <FieldLabel htmlFor="cd-r-contact">Where notice is served</FieldLabel>
                    <Input id="cd-r-contact" type="email" placeholder="liability@meridianterminal.example" value={draft.contact} invalid={submitted && !!errors.contact} onChange={(e) => set({ contact: e.target.value })} />
                    {submitted && errors.contact ? <FieldError>{errors.contact}</FieldError> : null}
                  </Field>
                  <Field>
                    <FieldLabel htmlFor="cd-r-basis">On what basis</FieldLabel>
                    <Textarea id="cd-r-basis" rows={3} placeholder="Terminal handling agreement, clause 8 — 12 months from the incident" value={draft.basis} invalid={submitted && !!errors.basis} onChange={(e) => set({ basis: e.target.value })} />
                    {submitted && errors.basis ? <FieldError>{errors.basis}</FieldError> : <FieldDescription>The clause or liability regime. It is the line the recovery file leads with.</FieldDescription>}
                  </Field>
                  <Field>
                    <FieldLabel htmlFor="cd-r-fileby">File notice by</FieldLabel>
                    <div style={{ maxWidth: "14rem" }}>
                      <Input id="cd-r-fileby" type="date" value={draft.fileBy} invalid={submitted && !!errors.fileBy} onChange={(e) => set({ fileBy: e.target.value })} />
                    </div>
                    {submitted && errors.fileBy ? <FieldError>{errors.fileBy}</FieldError> : <FieldDescription>The contract's own deadline — terminal agreements usually run 12 months from the incident, haulage subcontracts 40 days from payment.</FieldDescription>}
                  </Field>
                </div>
              </CardPanel>
            </Card>
          </div>

          <div className="cd-col">
            <Card>
              <CardHeader>
                <CardTitle>What the file will pursue</CardTitle>
                <CardDescription>Read from the settlement, never typed — the claim owns this money and the recovery reads it.</CardDescription>
              </CardHeader>
              <CardPanel>
                <div className="cd-col cd-col--tight">
                  <div>
                    <div className="cd-figure__label">Sought</div>
                    {claim ? (
                      <>
                        <div className="cd-figure" style={{ fontSize: "var(--text-2xl)" }}>{formatMoney(claim.settlement.amountCents)}</div>
                        <div className="cd-figure__note">The settlement {claim.id} paid {claim.customer}, cleared {formatWhen(claim.settlement.clearedAt || claim.settlement.sentAt, now)} on {claim.settlement.reference}.</div>
                      </>
                    ) : (
                      <div className="cd-figure__note">Pick a claim to see what this recovery is worth.</div>
                    )}
                  </div>

                  <div>
                    <div className="cd-figure__label">Deadline to serve notice</div>
                    {fileByAt && fileByAt > now ? (
                      <>
                        <div className={"cd-figure " + clockClass(timeTone(daysLeft))} style={{ fontSize: "var(--text-2xl)" }}>{formatCountdown(fileByAt, now)}</div>
                        <div style={{ marginBlock: "var(--space-2)" }}>
                          <TimeBar startAt={now} endAt={fileByAt} now={now} label={"Notice deadline: " + formatCountdown(fileByAt, now)} />
                        </div>
                        <div className="cd-figure__note">Expires {formatAbsolute(fileByAt).split(",")[0]}. The file opens as to file, and the recovery destination counts it.</div>
                      </>
                    ) : (
                      <div className="cd-figure__note">Set the contractual deadline to see the clock this file will run on.</div>
                    )}
                  </div>

                  {claim ? (
                    <p className="cd-note">
                      Nothing here changes {claim.id}. The claimant has been paid and the file stays closed; this pursues the {formatMoney(claim.settlement.amountCents)} from whoever caused the damage.
                    </p>
                  ) : null}
                </div>
              </CardPanel>
            </Card>
          </div>
        </div>

        <div className="cd-formbar">
          <span className="cd-formbar__note">
            {submitted && !valid
              ? formatPlural(Object.keys(errors).length, "field") + " still to fill in."
              : "The file opens as to file. Serving the notice is the next step, on the recovery itself."}
          </span>
          {dirty ? <Button variant="outline" onClick={() => onNavigate("/recovery")}>Cancel</Button> : null}
          <Button disabled={!dirty} onClick={submit}>Save recovery</Button>
        </div>
      </div>
    );
  }

  Object.assign(window, { NewRecoveryScreen });
})();
