"use client";

import { useEffect, useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { PlantForm } from "@/modules/garden/components/plant-form";
import { listContainers, type ContainerDto } from "@/modules/garden/server/queries";

type Props = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
};

export function PlantCreateDialog({ open, onOpenChange }: Props) {
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-lg max-h-[90dvh] overflow-y-auto">
        {open ? <PlantCreateForm onDone={() => onOpenChange(false)} /> : null}
      </DialogContent>
    </Dialog>
  );
}

function PlantCreateForm({ onDone }: { onDone: () => void }) {
  const [containers, setContainers] = useState<ContainerDto[]>([]);

  useEffect(() => {
    listContainers()
      .then(setContainers)
      .catch(() => setContainers([]));
  }, []);

  return (
    <>
      <DialogHeader>
        <DialogTitle>Add plant</DialogTitle>
      </DialogHeader>
      <PlantForm containers={containers} onSuccess={() => onDone()} onCancel={onDone} />
    </>
  );
}
