"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Pencil, Trash2, Zap } from "lucide-react";
import { toast } from "react-hot-toast";
import Image from "next/image";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { StatusBadge } from "@/components/shared/status-badge";
import { Input } from "@/components/ui/input";
import type { Location } from "@/features/locations/types";
import type { Chargepoint } from "./types";
import { ChargepointEditor } from "./chargepoint-editor";
import { EditChargepointDialog } from "./edit-chargepoint-dialog";
import { DeleteChargepointDialog } from "./delete-chargepoint-dialog";
export function DetailHeader({
  data,
  locations,
  source = "preview",
}: {
  data: Chargepoint;
  locations: Location[];
  source?: "api" | "preview";
}) {
  const router = useRouter();
  const [previewPoint, setPreviewPoint] = useState(data);
  const [edit, setEdit] = useState(false);
  const [apiEdit, setApiEdit] = useState(false);
  const [apiDelete, setApiDelete] = useState(false);
  const [imageDialog, setImageDialog] = useState(false);
  const [image, setImage] = useState("");
  const [error, setError] = useState("");
  const [notice, setNotice] = useState("");
  const point = source === "api" ? data : previewPoint;
  useEffect(
    () => () => {
      if (image) URL.revokeObjectURL(image);
    },
    [image],
  );
  return (
    <>
      <section className="detail-panel flex flex-wrap items-center justify-between gap-4 p-6">
        <div className="flex min-w-0 items-start gap-4">
          {image ? (
            <Image
              src={image}
              alt="Chargestation"
              width={48}
              height={48}
              unoptimized
              className="size-12 rounded-xl object-cover"
            />
          ) : (
            <span className="flex size-12 shrink-0 items-center justify-center rounded-xl bg-accent text-primary">
              <Zap className="size-6" />
            </span>
          )}
          <div className="min-w-0">
            <h2 className="text-xl font-semibold">{point.name}</h2>
            <div className="my-2 flex flex-wrap gap-2">
              <StatusBadge tone="neutral">{point.online}</StatusBadge>
              <StatusBadge>{point.visibility}</StatusBadge>
              <StatusBadge>{point.status}</StatusBadge>
              <StatusBadge>{point.protocol}</StatusBadge>
            </div>
            <p className="text-xs text-muted-foreground">
              {point.protocol} · {point.endpoint}
            </p>
          </div>
        </div>
        {source === "api" ? (
          <div className="flex flex-wrap gap-3">
            <Button
              variant="outline"
              size="sm"
              aria-label={`Edit ${point.name}`}
              onClick={() => setApiEdit(true)}
            >
              <Pencil aria-hidden="true" />
              Edit chargepoint
            </Button>
            <Button
              variant="outline"
              size="sm"
              className="text-destructive hover:text-destructive"
              aria-label={`Delete ${point.name}`}
              onClick={() => setApiDelete(true)}
            >
              <Trash2 aria-hidden="true" />
              Delete chargepoint
            </Button>
          </div>
        ) : (
          <div className="flex gap-3">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setImageDialog(true)}
            >
              Edit Image
            </Button>
            <Button size="sm" onClick={() => setEdit(true)}>
              Edit
            </Button>
          </div>
        )}
      </section>
      {source === "api" && (
        <EditChargepointDialog
          key={`${point.id}:${point.locationId}`}
          open={apiEdit}
          onOpenChange={setApiEdit}
          chargepoint={point}
          locations={locations}
          onSaved={() => {
            setNotice("Chargepoint updated successfully.");
            router.refresh();
          }}
        />
      )}
      {source === "api" && apiDelete && (
        <DeleteChargepointDialog
          key={point.id}
          chargepoint={point}
          onOpenChange={setApiDelete}
          onDeleted={() => {
            setApiDelete(false);
            toast.success("Chargepoint deleted successfully.");
            router.replace("/chargepoints");
            router.refresh();
          }}
        />
      )}
      {source === "preview" && (
        <ChargepointEditor
          open={edit}
          onOpenChange={setEdit}
          chargepoint={point}
          locations={locations}
          onSave={setPreviewPoint}
        />
      )}
      {notice && (
        <p role="status" className="text-sm text-muted-foreground">
          {notice}
        </p>
      )}
      {source === "preview" && <Dialog open={imageDialog} onOpenChange={setImageDialog}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Edit Image</DialogTitle>
            <DialogDescription>
              Select an image for this chargestation preview.
            </DialogDescription>
          </DialogHeader>
          <label htmlFor="station-image" className="field-label">
            Station image
          </label>
          <Input
            id="station-image"
            type="file"
            accept="image/png,image/jpeg,image/webp"
            onChange={(event) => {
              const file = event.target.files?.[0];
              if (!file) return;
              if (
                !["image/png", "image/jpeg", "image/webp"].includes(
                  file.type,
                ) ||
                file.size > 5 * 1024 * 1024
              ) {
                setError("Choose a PNG, JPG or WebP image smaller than 5 MB.");
                return;
              }
              setError("");
              setImage(URL.createObjectURL(file));
            }}
          />
          {error && (
            <p role="alert" className="text-destructive">
              {error}
            </p>
          )}
          <DialogFooter>
            <Button onClick={() => setImageDialog(false)}>Done</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>}
    </>
  );
}
