"use client";

import * as z from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useState } from "react";
import axios from "axios";
import { toast } from "react-hot-toast";

import { useStoreModal } from "@/hooks/use-store-modal";
import { Modal } from "@/components/ui/modal";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import ImageUpload from "@/components/image-upload";

const formSchema = z.object({
  name: z.string().min(1),
  logo: z.string().min(1),
  shopMail: z.string().min(1),
  shopUrl: z.string().min(1),

});

export const StoreModal = () => {
  const storeModal = useStoreModal();

  const [loading, setLoading] = useState(false);

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: '',
      logo: '',
      shopMail: '',
      shopUrl: ''
    },
  });

  const onSubmit = async (values: z.infer<typeof formSchema>) => {

    try {
      setLoading(true);

      const response = await axios.post('/api/stores', values);

      window.location.assign(`/${response.data.id}`);
    } catch (error) {
      toast.error("Une erreur s'est produite.")
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      title="Créez une boutique"
      description="Ajouter une nouvelle boutique pour gérer vos produits"
      isOpen={storeModal.isOpen}
      onClose={storeModal.onClose}
    >
      <div>
        <div className="space-y-4 py-2 pb-4">
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)}>
              <FormField
                control={form.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Nom de la boutique</FormLabel>
                    <FormControl>
                      <Input disabled={loading}
                        placeholder="E-Commerce"
                        {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="logo"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Logo de la boutique</FormLabel>
                    <FormControl>
                      <ImageUpload
                        disabled={loading}
                        value={(field.value != '') ? [{ url: field.value, order: 0 }] : []}
                        onChange={(base64Array) => {
                          if (base64Array.length > 0) {
                            const updatedValue = base64Array[0];
                            field.onChange(updatedValue.url);
                          }
                        }}
                        onRemove={() => {
                          field.onChange('');
                        }}
                        field={{
                          value: [{ url: field.value, order: 0 }],
                          onChange: (updatedValue) => {
                            if (updatedValue.length > 0) {
                              field.onChange(updatedValue[0].url);
                            } else {
                              field.onChange('');
                            }
                          }
                        }}
                        label="Glissez ou cliquez pour ajouter une image"
                        maxFiles={1}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="shopMail"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Adresse mail représentant la boutique</FormLabel>
                    <FormControl>
                      <Input disabled={loading}
                        placeholder="contact@projoctopus.com"
                        {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="shopUrl"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>URL de la boutique</FormLabel>
                    <FormControl>
                      <Input disabled={loading}
                        placeholder="www.projoctopus.com"
                        {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <div className="pt-6 space-x-2 flex items-center justify-end w-full">
                <Button disabled={loading} variant="outline" onClick={storeModal.onClose}>Cancel</Button>
                <Button disabled={loading} type="submit">Continue</Button>
              </div>
            </form>
          </Form>
        </div>
      </div>
    </Modal>
  );
};