"use client";
import { useState } from "react";
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, LocationWritePayload } from "./types";
export function LocationEditor({
  open,
  onOpenChange,
  location,
  onSave,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  location?: Location;
  onSave: (value: Partial<LocationWritePayload>) => Promise<void>;
}) {
  const [error, setError] = useState("");
  const [saving, setSaving] = useState(false);
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-[750px]">
        <DialogHeader>
          <DialogTitle>
            {location ? "Edit Location" : "Create New Location"}
          </DialogTitle>
          <DialogDescription className="sr-only">
            Location details and geographic coordinates
          </DialogDescription>
        </DialogHeader>
        {error && (
          <p role="alert" className="text-destructive">
            {error}
          </p>
        )}
        <form
          onSubmit={async (event) => {
            event.preventDefault();
            const data = new FormData(event.currentTarget);
            const value = (key: string) => String(data.get(key) ?? "").trim();
            const city = value("city");
            const payload: Partial<LocationWritePayload> = {
              code: value("code"),
              name: value("name"),
              phone: value("phone"),
              email: value("email"),
              avatar_url: value("avatar_url"),
              address: value("address"),
              ...(city ? { city } : {}),
              latitude: Number(value("latitude")),
              longitude: Number(value("longitude")),
              currency: value("currency"),
              public: value("public") === "true",
              active: value("active") === "true",
            };
            setSaving(true);
            try {
              await onSave(payload);
              setError("");
              onOpenChange(false);
            } catch (cause) {
              setError(
                cause instanceof Error
                  ? cause.message
                  : "Unable to save this location. Please try again.",
              );
            } finally {
              setSaving(false);
            }
          }}
        >
          <h3 className="metric-label mb-3">General Information</h3>
          <div className="grid gap-4 sm:grid-cols-2">
            <FormField
              name="code"
              label="Code"
              required
              defaultValue={location?.code}
            />
            <FormField
              name="name"
              label="Name"
              required
              defaultValue={location?.name}
            />
            <FormField
              name="phone"
              label="Phone"
              type="tel"
              defaultValue={location?.phone}
            />
            <FormField
              name="email"
              label="Email"
              type="email"
              defaultValue={location?.email}
            />
            <FormField
              name="avatar_url"
              label="Avatar URL"
              type="url"
              defaultValue={location?.avatarUrl}
            />
          </div>
          <h3 className="metric-label mt-6 mb-3">Address</h3>
          <div className="grid gap-4 sm:grid-cols-2">
            <FormField
              name="address"
              label="Street & Number"
              required
              defaultValue={location?.address}
            />
            <FormField
              name="city"
              label="City"
              required={!location}
              defaultValue={location?.city}
            />
            <FormField
              name="currency"
              label="Currency"
              required
              defaultValue={location?.currency ?? "IDR"}
            />
          </div>
          <h3 className="metric-label mt-6 mb-3">Coordinates</h3>
          <div className="mb-6 grid gap-4 sm:grid-cols-2">
            <FormField
              name="longitude"
              label="Longitude"
              type="number"
              step="any"
              min={-180}
              max={180}
              required
              defaultValue={location?.longitude ?? 106.82}
            />
            <FormField
              name="latitude"
              label="Latitude"
              type="number"
              step="any"
              min={-90}
              max={90}
              required
              defaultValue={location?.latitude ?? -6.2}
            />
          </div>
          <div className="mb-6 grid gap-4 sm:grid-cols-2">
            <SelectField
              name="public"
              label="Visibility"
              options={[
                { value: "false", label: "Private" },
                { value: "true", label: "Public" },
              ]}
              defaultValue={String(location?.public ?? false)}
            />
            <SelectField
              name="active"
              label="Status"
              options={[
                { value: "true", label: "Active" },
                { value: "false", label: "Inactive" },
              ]}
              defaultValue={String(location?.active ?? true)}
            />
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              type="button"
              onClick={() => onOpenChange(false)}
            >
              Cancel
            </Button>
            <Button disabled={saving}>
              {saving
                ? "Saving..."
                : location
                  ? "Save Changes"
                  : "Create Location"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
