File size: 6,429 Bytes
1067b6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
"use client";

import { FormEvent, useCallback, useEffect, useState } from "react";
import { TextInputWithLabel } from "../text-input-with-label";
import { Product } from "@/db/schema";
import { useRouter } from "next/navigation";
import { Button } from "../ui/button";
import { secondLevelNestedRoutes, singleLevelNestedRoutes } from "@/lib/routes";
import { toast } from "../ui/use-toast";
import { HeadingAndSubheading } from "./heading-and-subheading";
import { ProductImages } from "@/lib/types";
import { ProductImageUploader } from "./product-image-uploader";
import type { deleteProduct, updateProduct } from "@/server-actions/products";
import { Loader2 } from "lucide-react";

const defaultValues = {
  name: "",
  description: "",
  price: "",
  inventory: "",
  images: [],
};

export const ProductEditorElements = (props: {
  displayType?: "page" | "modal";
  productStatus: "new-product" | "existing-product";
  productActions: {
    updateProduct: typeof updateProduct;
    deleteProduct: typeof deleteProduct;
  };
  initialValues?: Product;
}) => {
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(false);
  const [imagesToDelete, setImagesToDelete] = useState([] as ProductImages[]);
  const [newImages, setNewImages] = useState([] as ProductImages[]);

  const [formValues, setFormValues] = useState<Omit<Product, "id" | "storeId">>(
    props.initialValues ?? defaultValues
  );

  const dismissModal = useCallback(() => {
    if (props.displayType === "modal") {
      router.back();
    } else {
      router.push(singleLevelNestedRoutes.account.products);
    }
  }, [router, props.displayType]);

  const onKeyDown = useCallback(
    (e: any) => {
      if (e.key === "Escape") dismissModal();
    },
    [dismissModal]
  );

  useEffect(() => {
    document.addEventListener("keydown", onKeyDown);
    return () => document.removeEventListener("keydown", onKeyDown);
  }, [onKeyDown]);

  const handleProductUpdate = async (
    e:
      | FormEvent<HTMLFormElement>
      | React.MouseEvent<HTMLButtonElement, MouseEvent>,
    buttonAction?: "delete"
  ) => {
    e.preventDefault();
    setIsLoading(true);

    let data;
    if (buttonAction === "delete") {
      // delete product
      data = await props.productActions.deleteProduct(props.initialValues?.id);
      if (!data.error) {
        router.refresh();
        router.push(singleLevelNestedRoutes.account.products);
      }
    } else if (props.initialValues) {
      // update product
      const updatedValues = {
        ...formValues,
        images: [
          ...(props.initialValues?.images as []),
          ...(newImages ?? []),
        ].filter((item) => imagesToDelete && !imagesToDelete.includes(item)),
      } as Omit<Product, "storeId">;
      data = await props.productActions.updateProduct(updatedValues);
      if (!data.error) {
        router.refresh();
        router.push(singleLevelNestedRoutes.account.products);
      }
    } else {
      // create new product
      const res = await fetch("/api/product", {
        method: "POST",
        body: JSON.stringify(formValues),
      });
      data = (await res.json()) as unknown as {
        error: boolean;
        message: string;
        action: string;
        productId?: string;
      };
      console.log(data);
      if (data.productId) {
        router.push(
          `${secondLevelNestedRoutes.product.base}/${data.productId}`
        );
      }
      setFormValues(defaultValues);
    }
    setIsLoading(false);
    toast({
      title: data.message,
      description: data.action,
    });
  };

  return (
    <>
      <HeadingAndSubheading
        heading={
          props.productStatus === "new-product"
            ? "Create a new product"
            : "Edit product"
        }
        subheading={
          props.productStatus === "new-product"
            ? "Enter the details of your new product below and click save."
            : "Edit the details of your product below and click save."
        }
      />

      <form onSubmit={handleProductUpdate}>
        <div className="flex flex-col gap-8 mt-2 mb-6">
          <TextInputWithLabel
            required
            id="name"
            label="Product Name"
            type="text"
            state={formValues}
            setState={setFormValues}
          />
          <TextInputWithLabel
            id="description"
            label="Description"
            type="text"
            inputType="textarea"
            rows={8}
            state={formValues}
            setState={setFormValues}
          />
          {props.productStatus === "existing-product" && (
            <ProductImageUploader
              product={
                props.initialValues as Omit<Product, "images"> & {
                  images: ProductImages[];
                }
              }
              newImages={newImages}
              setNewImages={setNewImages}
              imagesToDelete={imagesToDelete}
              setImagesToDelete={setImagesToDelete}
            />
          )}
          <div className="grid grid-cols-2 gap-4">
            <TextInputWithLabel
              id="price"
              label="Price"
              type="number"
              state={formValues}
              setState={setFormValues}
            />
            <TextInputWithLabel
              id="inventory"
              label="Quantity In Stock"
              type="number"
              state={formValues}
              setState={setFormValues}
            />
          </div>
        </div>
        <div className="flex justify-between items-center">
          {!!props.initialValues && (
            <Button
              type="button"
              variant="destructiveOutline"
              onClick={(e) => handleProductUpdate(e, "delete")}
            >
              Delete
            </Button>
          )}
          <div className="flex items-center gap-2 ml-auto">
            <Button type="button" variant="outline" onClick={dismissModal}>
              Cancel
            </Button>
            <Button
              type="submit"
              disabled={isLoading}
              className="flex gap-2 items-center justify-center"
            >
              {!!isLoading && <Loader2 size={18} className="animate-spin" />}
              {props.initialValues ? "Save" : "Create"}
            </Button>
          </div>
        </div>
      </form>
    </>
  );
};