"use client";
import { useState } from "react";
import { chargepointFromForm } from "./form-value";
import { saveDraft } from "@/mocks/drafts";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { FormField, SelectField } from "@/components/shared/form-field";
import type { Location } from "@/features/locations/types";
import type { Chargepoint } from "./types";
export function ChargepointEditor({
  open,
  onOpenChange,
  chargepoint,
  locations,
  onSave,
  defaultLocationId,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  chargepoint?: Chargepoint;
  locations: Location[];
  onSave: (value: Chargepoint) => void;
  defaultLocationId?: string;
}) {
  const [error, setError] = useState("");
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-[750px]">
        <DialogHeader>
          <DialogTitle>
            {chargepoint ? "Edit Chargestation" : "Create New Chargestation"}
          </DialogTitle>
          <DialogDescription className="sr-only">
            Device, organization and location settings
          </DialogDescription>
        </DialogHeader>
        {error && (
          <p role="alert" className="text-destructive">
            {error}
          </p>
        )}
        <form
          onSubmit={(event) => {
            event.preventDefault();
            const data = new FormData(event.currentTarget);
            const value = (key: string) => String(data.get(key) ?? "").trim();
            const location = locations.find(
              (item) => item.id === value("location"),
            );
            if (!location) {
              setError("Select a location.");
              return;
            }
            try {
              const row = chargepointFromForm(data, location, chargepoint);
              if (row.id.includes("-demo-")) saveDraft(row);
              onSave(row);
              setError("");
            } catch (error) {
              setError(
                error instanceof Error
                  ? error.message
                  : "Unable to save this preview.",
              );
              return;
            }
            onOpenChange(false);
          }}
        >
          <h3 className="metric-label mb-3">Station Configuration</h3>
          <div className="grid gap-4 sm:grid-cols-3">
            <SelectField
              label="Chargestation Type"
              name="type"
              options={["AC", "DC"]}
              defaultValue={
                chargepoint?.stationType ??
                (chargepoint?.connectors.some((c) => c.type === "CCS2")
                  ? "DC"
                  : "AC")
              }
            />
            <SelectField
              label="Protocol"
              name="protocol"
              options={["OCPP1.6", "OCPP2.0.1"]}
              defaultValue={chargepoint?.protocol}
            />
            <SelectField
              label="Chargestation Security"
              name="security"
              options={["None", "Basic Auth"]}
              defaultValue={chargepoint?.security}
            />
          </div>
          <h3 className="metric-label mt-6 mb-3">Organization & Visibility</h3>
          <div className="grid gap-4 sm:grid-cols-2">
            <SelectField
              label="Organization"
              name="organization"
              options={["SANDBOX"]}
            />
            <SelectField
              label="Public"
              name="visibility"
              options={["Public", "Private"]}
              defaultValue={chargepoint?.visibility}
            />
          </div>
          <h3 className="metric-label mt-6 mb-3">Station Information</h3>
          <FormField
            name="name"
            label="Name"
            required
            defaultValue={chargepoint?.name}
          />
          <FormField
            className="mt-4"
            name="description"
            label="Description"
            defaultValue={chargepoint?.description}
          />
          <h3 className="metric-label mt-6 mb-3">Location</h3>
          <SelectField
            name="location"
            label="Location"
            required
            options={locations.map((location) => ({
              value: location.id,
              label: location.name,
            }))}
            defaultValue={chargepoint?.locationId ?? defaultLocationId}
          />
          <div className="my-5 grid gap-4 sm:grid-cols-2">
            <FormField
              name="latitude"
              label="Latitude"
              type="number"
              min={-90}
              max={90}
              step="any"
              defaultValue={chargepoint?.latitude}
            />
            <FormField
              name="longitude"
              label="Longitude"
              type="number"
              min={-180}
              max={180}
              step="any"
              defaultValue={chargepoint?.longitude}
            />
          </div>
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
            >
              Cancel
            </Button>
            <Button>
              {chargepoint ? "Save Changes" : "Create Chargestation"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
