"use client";

import { useEffect, useState } from "react";
import { FormField, SelectField } from "@/components/shared/form-field";
import type { Connector } from "../types";
import { fetchChargepointProfiles } from "./client-api";
import type { ChargingProfileOption } from "./profiles-contract.ts";

const sampleProfileId = "e4eb049b-90f1-4673-9a2a-dc0585fe9b40";
const previewProfile: ChargingProfileOption = {
  id: sampleProfileId,
  label: `Profile - TxProfile - ${sampleProfileId}`,
  data: {
    id: sampleProfileId,
    connector_id: 1,
    ocpp_charging_profile_id: 1001,
    status: "Accepted",
    charging_profile: {
      chargingProfileId: 1001,
      chargingProfilePurpose: "TxProfile",
      chargingProfileKind: "Absolute",
      stackLevel: 0,
      chargingSchedule: {
        chargingRateUnit: "W",
        chargingSchedulePeriod: [{ startPeriod: 0, limit: 7_200 }],
      },
    },
  },
};

export function RemoteStartFields({
  ocppIdentity,
  connectors,
  source,
  invalidField,
}: {
  ocppIdentity?: string;
  connectors: Connector[];
  source: "api" | "preview";
  invalidField?: string;
}) {
  const [profiles, setProfiles] = useState<ChargingProfileOption[]>(source === "preview" ? [previewProfile] : []);
  const [selectedProfileId, setSelectedProfileId] = useState(source === "preview" ? sampleProfileId : "");
  const [loading, setLoading] = useState(source === "api");
  const [loadError, setLoadError] = useState<string>();

  useEffect(() => {
    if (source !== "api") return;
    let active = true;
    fetchChargepointProfiles(ocppIdentity)
      .then(options => {
        if (!active) return;
        setProfiles(options);
        setSelectedProfileId(options.find(option => option.id === sampleProfileId)?.id ?? options[0]?.id ?? "");
      })
      .catch(error => {
        if (active) setLoadError(error instanceof Error ? error.message : "Unable to load charging profiles.");
      })
      .finally(() => {
        if (active) setLoading(false);
      });
    return () => { active = false; };
  }, [ocppIdentity, source]);

  const field = (name: string) => ({ name, id: `operation-${name}`, "aria-invalid": invalidField === name, "aria-describedby": invalidField === name ? "operation-error" : undefined });
  const profileOptions = profiles.length
    ? profiles.map(profile => ({ value: profile.id, label: profile.label }))
    : [{ value: "", label: loading ? "Loading profiles…" : "No charging profiles available" }];
  const selectedProfile = profiles.find(profile => profile.id === selectedProfileId);

  return <div className="flex flex-col gap-4">
    <div className="grid gap-4 sm:grid-cols-2">
      <FormField {...field("connectorId")} label="Connector ID" type="number" required min={0} max={2_147_483_647} step={1} defaultValue={connectors[0]?.number ?? 1} />
      <FormField {...field("idTag")} label="ID tag" type="text" required maxLength={20} defaultValue="validtag1" autoComplete="off" />
    </div>
    <SelectField
      {...field("chargingProfileId")}
      label="Charging profile"
      required
      disabled={loading || profiles.length === 0}
      value={selectedProfileId}
      onChange={event => setSelectedProfileId(event.target.value)}
      options={profileOptions}
    />
    {selectedProfile && <section className="rounded-lg border bg-muted/20 p-3" aria-label="Selected profile data">
      <h3 className="text-sm font-medium">Selected profile data</h3>
      <pre className="mt-2 max-h-64 overflow-auto whitespace-pre-wrap break-all rounded-md bg-muted/50 p-3 font-mono text-xs leading-relaxed">{JSON.stringify(selectedProfile.data, null, 2)}</pre>
    </section>}
    {loading && <p role="status" className="text-sm text-muted-foreground">Loading charging profiles…</p>}
    {loadError && <p role="alert" className="text-sm text-destructive">{loadError}</p>}
    {!loading && !loadError && profiles.length === 0 && <p role="alert" className="text-sm text-muted-foreground">Add a charging profile to this chargepoint before starting a transaction.</p>}
    {source === "preview" && <p className="text-sm text-muted-foreground">Preview mode validates the sample profile only. No device request will be sent.</p>}
  </div>;
}
