"use client";

import { useState } from "react";
import Link from "next/link";
import { FormField, SelectField } from "@/components/shared/form-field";
import type { Connector } from "../types";
import { isSensitiveConfigurationKey, triggerMessages, type ReadyCommand } from "./contract.ts";
import { certificateTypeOptions } from "./certificate-contract.ts";
import { InstalledCertificates } from "./installed-certificates";
import { LocalListFields } from "./local-list-fields";
import { ChargingProfileFields, CompositeScheduleFields, ClearChargingProfileFields } from "./charging-profile-fields";
import { FirmwareFields } from "./firmware-fields";

export function CommandFields({ command, connectors, chargepointId, source, invalidField, onCertificateSelection, onConfirmationScopeChange }: { command: ReadyCommand; connectors: Connector[]; chargepointId: string; source: "api" | "preview"; invalidField?: string; onCertificateSelection?: (value: string) => void; onConfirmationScopeChange?: (value: string) => void }) {
  const [configurationKey, setConfigurationKey] = useState("");
  const field = (name: string) => ({ name, id: `operation-${name}`, "aria-invalid": invalidField === name, "aria-describedby": invalidField === name ? "operation-error" : undefined });
  if (command === "set-charging-profile") return <ChargingProfileFields invalidField={invalidField} defaultConnector={connectors[0]?.number} />;
  if (command === "get-composite-schedule") return <CompositeScheduleFields invalidField={invalidField} defaultConnector={connectors[0]?.number} />;
  if (command === "clear-charging-profile") return <ClearChargingProfileFields invalidField={invalidField} onScopeChange={onConfirmationScopeChange} />;
  if (command === "signed-update-firmware") return <FirmwareFields invalidField={invalidField} />;
  if (command === "clear-cache") return <p className="text-sm text-muted-foreground">This clears cached authorizations on this chargepoint. Existing RFID records in the dashboard are preserved.</p>;
  if (command === "get-local-list-version") return <p className="text-sm text-muted-foreground">Read the version of the charger’s local authorization list. Use the returned version when preparing a Full or Differential update.</p>;
  if (command === "send-local-list") return <LocalListFields invalidField={invalidField} />;
  if (command === "remote-stop") return <div className="flex flex-col gap-3">
    <FormField {...field("transactionId")} label="OCPP transaction ID" type="number" required step={1} min={-2_147_483_648} max={2_147_483_647} placeholder="e.g. 789005640" />
    <p className="text-sm text-muted-foreground">Use the numeric OCPP transaction ID shown in Sessions. Sending this request can end active charging.</p>
    <Link href={`/chargepoints/${encodeURIComponent(chargepointId)}?tab=sessions`} target="_blank" rel="noreferrer" className="text-sm font-medium text-primary underline underline-offset-4">View chargepoint sessions<span className="sr-only"> (opens a new tab)</span></Link>
  </div>;
  if (command === "delete-certificate") return <InstalledCertificates chargepointId={chargepointId} source={source} selectable invalidField={invalidField} onSelectionChange={onCertificateSelection} />;
  if (command === "install-certificate") return <div className="flex flex-col gap-3">
    <SelectField {...field("certificateType")} label="Certificate type" required defaultValue="CentralSystemRootCertificate" options={certificateTypeOptions} />
    <label className="field-label" htmlFor="operation-certificate">PEM certificate <span className="text-destructive">*</span></label>
    <textarea {...field("certificate")} required rows={7} maxLength={11_000} autoComplete="off" spellCheck={false} className="w-full rounded-lg border border-input bg-card px-3 py-2.5 font-mono text-xs leading-relaxed outline-none focus-visible:ring-2 focus-visible:ring-ring" placeholder={"-----BEGIN CERTIFICATE-----\nPaste the certificate content here\n-----END CERTIFICATE-----"} />
    <p className="text-sm text-muted-foreground">Paste the trusted root certificate, including its PEM markers, up to 5,500 characters. After acceptance, check the installed certificate list to verify the charger’s response.</p>
  </div>;
  if (command === "get-log") return <div className="flex flex-col gap-4">
    <div className="grid gap-4 sm:grid-cols-2">
      <SelectField {...field("logType")} label="Log type" required defaultValue="SecurityLog" options={[{ value: "SecurityLog", label: "Security log" }, { value: "DiagnosticsLog", label: "Diagnostics log" }]} />
      <FormField {...field("requestId")} label="Request ID" required type="number" step={1} min={-2_147_483_648} max={2_147_483_647} placeholder="e.g. 1001" />
    </div>
    <FormField {...field("remoteLocation")} label="Upload destination" required maxLength={512} autoComplete="off" placeholder="https://server.example.com/logs/" />
    <p className="-mt-2 text-sm text-muted-foreground">The charger uploads the file to this FTP, HTTP, or HTTPS destination. The request ID identifies its upload status events.</p>
    <details className="rounded-lg border p-3"><summary className="cursor-pointer text-sm font-medium focus-visible:outline-2 focus-visible:outline-ring">Upload options</summary><div className="mt-4 grid gap-4 sm:grid-cols-2">
      <FormField {...field("retries")} label="Retries" type="number" min={0} max={10} step={1} defaultValue={3} />
      <FormField {...field("retryInterval")} label="Retry interval (seconds)" type="number" min={1} max={86_400} step={1} defaultValue={60} />
      <FormField {...field("oldestTimestamp")} label="From (optional)" type="datetime-local" />
      <FormField {...field("latestTimestamp")} label="To (optional)" type="datetime-local" />
      <p className="text-sm text-muted-foreground sm:col-span-2">Times use your browser’s local timezone. Leave the range blank to request the available logs.</p>
    </div></details>
  </div>;
  if (command === "reset") return <div className="flex flex-col gap-3">
    <SelectField {...field("type")} label="Reset type" required defaultValue="Soft" options={[{ value: "Soft", label: "Soft — restart chargepoint software" }, { value: "Hard", label: "Hard — restart the chargepoint" }]} />
    <p className="text-sm text-muted-foreground">A reset can interrupt charging and briefly disconnect the charger.</p>
  </div>;
  if (command === "get-configuration") return <div className="flex flex-col gap-2">
    <label className="field-label" htmlFor="operation-key">Configuration keys <span className="font-normal text-muted-foreground">(optional)</span></label>
    <textarea {...field("key")} rows={3} maxLength={2_550} className="w-full rounded-lg border border-input bg-card px-3 py-2.5 outline-none focus-visible:ring-2 focus-visible:ring-ring" placeholder="HeartbeatInterval, MeterValueSampleInterval" />
    <p className="text-sm text-muted-foreground">Leave blank to read all settings. Separate specific keys with commas or new lines.</p>
  </div>;
  if (command === "change-configuration") return <div className="flex flex-col gap-4">
    <FormField {...field("key")} label="Configuration key" required maxLength={50} value={configurationKey} onChange={event => setConfigurationKey(event.target.value)} placeholder="HeartbeatInterval" />
    <FormField {...field("value")} label="New value" maxLength={4_096} type={isSensitiveConfigurationKey(configurationKey) ? "password" : "text"} autoComplete="off" placeholder="Enter the requested value" />
    <p className="text-sm text-muted-foreground">Use the exact key supported by this charger. Leave the value blank only if the setting supports it. Some changes require a restart.</p>
  </div>;
  if (command === "update-password") return <div className="flex flex-col gap-3">
    <FormField {...field("value")} label="New authorization key" type="password" autoComplete="new-password" required minLength={32} maxLength={40} />
    <p className="text-sm text-muted-foreground">Use 32–40 characters for Security Profile 1. The key is cleared from this form after the request.</p>
  </div>;
  if (command === "unlock-connector" || command === "trigger-message") return <div className="flex flex-col gap-4">
    {command === "trigger-message" && <SelectField {...field("requestedMessage")} label="OCPP message" required options={triggerMessages.map(value => ({ value, label: value.replace(/([a-z])([A-Z])/g, "$1 $2") }))} defaultValue="StatusNotification" />}
    <FormField {...field("connectorId")} label={command === "unlock-connector" ? "Connector / nozzle number" : "Connector / nozzle number (optional)"} type="number" step={1} min={command === "unlock-connector" ? 1 : 0} max={2_147_483_647} required={command === "unlock-connector"} defaultValue={command === "unlock-connector" ? connectors[0]?.number : undefined} placeholder={command === "trigger-message" ? "Leave blank for chargepoint scope" : "e.g. 1"} />
    <p className="text-sm text-muted-foreground">{command === "unlock-connector" ? "Use the connector number printed on the charger, rather than its dashboard ID." : "The connector field can be left blank. Zero targets all connectors for messages that support it."}</p>
  </div>;
  return <div className="flex flex-col gap-4">
    <FormField {...field("location")} label="Upload destination" required maxLength={2_048} autoComplete="off" placeholder="ftp://server.example.com/diagnostics/" />
    <p className="-mt-2 text-sm text-muted-foreground">The chargepoint uploads files to this FTP, HTTP, or HTTPS location.</p>
    <div className="grid gap-4 sm:grid-cols-2">
      <FormField {...field("retries")} label="Retries" type="number" min={0} max={10} step={1} defaultValue={3} />
      <FormField {...field("retryInterval")} label="Retry interval (seconds)" type="number" min={1} max={86_400} step={1} defaultValue={60} />
      <FormField {...field("startTime")} label="From (optional)" type="datetime-local" />
      <FormField {...field("stopTime")} label="To (optional)" type="datetime-local" />
    </div>
    <p className="text-sm text-muted-foreground">Times use your browser’s local timezone and are sent with an explicit timezone. Leave the range blank to use the charger’s available logs.</p>
  </div>;
}
