import { useState, useEffect } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { createDockerBuildConfig } from "@/pages/repos/store/build";
import { usePackageStore } from "../../store";
import { useShallow } from "zustand/shallow";

interface AddDockerDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  slug: string;
}

export function AddDockerDialog({ open, onOpenChange, slug }: AddDockerDialogProps) {
  const [repo, setRepo] = useState(() => {
    return slug;
  });
  const [dockerImage, setDockerImage] = useState(() => {
    return localStorage.getItem("add-docker-image") || "";
  });
  useEffect(() => {
    localStorage.setItem("add-docker-image", dockerImage);
  }, [dockerImage]);
  const cnbPackageSore = usePackageStore(useShallow((state) => ({ repo: state.repo, dockerBuild: state.dockerBuild })));
  const handleConfirm = async () => {
    console.log("repo:", repo, "docker image:", dockerImage);
    onOpenChange(false);
    const config = createDockerBuildConfig({ repo, image: dockerImage });
    await cnbPackageSore.dockerBuild({ repo, config });
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>添加 Docker 镜像</DialogTitle>
        </DialogHeader>
        <div className="space-y-2">
          <label className="text-sm font-medium">Repo</label>
          <Input
            placeholder="kevisual/dev-env"
            value={repo}
            onChange={(e) => setRepo(e.target.value)}
          />
        </div>
        <div className="space-y-2">
          <label className="text-sm font-medium">Docker</label>
          <Input
            placeholder="redis:latest"
            value={dockerImage}
            onChange={(e) => setDockerImage(e.target.value)}
          />
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button onClick={handleConfirm}>确定</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}