/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable no-constant-binary-expression */
"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { X } from "lucide-react";
import { useEffect, useState, type ReactNode } from "react";
import { useForm } from "react-hook-form";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";

import { productApi } from "@/api/product-api.service";
import Loader from "@/components/loader";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { delay } from "@/features/app";
import useActionPostMutation from "@/hooks/use-action-post-mutation";
import usePost from "@/hooks/use-post-hook";
import { mapToIPost, type IPost } from "@/lib/utils";
import { useMutation } from "@tanstack/react-query";
import { toast } from "sonner";
import z from "zod/v3";

// eslint-disable-next-line react-refresh/only-export-components
export const productSchema = z.object({
  images: z.array(z.string()).min(1, "At least 1 image is required"),
  title: z
    .string()
    .min(1, "Product title is required")
    .min(5, "Product title must be at least 5 characters"),
  price: z.preprocess(
    (val) => (typeof val === "string" ? Number(val) : val),
    z
      .number({
        invalid_type_error: "Price must be a number",
        required_error: "Price is required",
      })
      .min(1, "Price must be greater than 0")
  ),
  category: z.string().min(1, "Category is required"),
  condition: z.string().min(1, "Condition is required"),
  brand: z.string().optional(),
  description: z
    .string()
    .min(1, "Description is required")
    .min(20, "Description must be at least 20 characters"),
  tags: z.array(z.string()).optional(),
  sku: z.string().min(1, "Sku must be required"),
  location: z.string().optional(),
  publist: z.boolean().optional(),
});

export type ProductFormData = z.infer<typeof productSchema>;

export default function ProductModal({
  children,
  data,
  ...props
}: {
  children: ReactNode;
  onSubmit?: () => void;
  data?: IPost;
}) {
  const [open, setOpen] = useState(false);
  const [tagInput, setTagInput] = useState("");

  const actionMutation = useActionPostMutation();

  const form = useForm<ProductFormData>({
    resolver: zodResolver(productSchema) as any,
    defaultValues: {
      images: [],
      title: "",
      price: 0,
      category: "",
      condition: "",
      brand: "",
      description: "",
      tags: [],
      sku: "",
      location: "",
      publist: false,
    },
  });

  const watchedImages = form.watch("images");
  const watchedTags = form.watch("tags");

  const conditions = ["New", "Used – like new", "Used – good", "Used – fair"];
  const categories = ["Tools", "Electronics & computers"];

  const { refetch, ...query } = usePost(data);

  const addTag = () => {
    if (tagInput.trim() && !watchedTags?.includes(tagInput.trim())) {
      const currentTags = form.getValues("tags") || [];
      form.setValue("tags", [...currentTags, tagInput.trim()]);
      setTagInput("");
    }
  };

  const removeTag = (tagToRemove: string) => {
    const currentTags = form.getValues("tags") || [];
    form.setValue(
      "tags",
      currentTags.filter((tag) => tag !== tagToRemove)
    );
  };

  const onSubmit = async (values: ProductFormData) => {
    try {
      console.log({ values });

      // saveMutation.mutate(values);

      const { images, ...newValue } = values;

      actionMutation.mutate({ ...data, ...newValue } as IPost);
      setOpen(false);
    } catch (error) {
      console.error("Error submitting form:", error);
    }
  };

  const handleClose = () => {
    setOpen(false);
    form.reset();
    setTagInput("");
  };

  const mutation = useMutation({
    mutationKey: ["createBlobUrl", data?.sku],
    mutationFn: (images: string[]) => {
      return productApi.apiRequest("createBlobUrl", images);
    },
  });

  useEffect(() => {
    (async () => {
      if ((query.data as any)?.mapped) {
        form.reset(query.data as any);
        return;
      }

      if (!(query.data as any)?.data || !data) return;
      const images = mapToIPost({ ...(query.data as any)?.data }).images;

      const urls = await mutation.mutateAsync(images);
      const values = {
        ...data,
        images: urls as string[],
      };
      form.reset(values);
    })();
  }, [query.data, data]);

  const saveMutation = useMutation({
    mutationKey: ["save_product"],
    mutationFn: async (values: any) => {
      await delay(300);
      return productApi.apiRequest("saveProductLocalServer", {
        id: data?.id,
        mapped: true,
        ...values,
      });
    },
    onSuccess() {
      toast.success("Saved", {
        description: (
          <span className="!text-black font-medium">{"Product was saved"}</span>
        ),
      });
      refetch();
    },
  });

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>{children}</DialogTrigger>
      <DialogContent
        aria-describedby={undefined}
        className="md:max-w-4xl h-[95vh] flex flex-col p-0"
      >
        {/* Header */}
        <DialogHeader className="p-6 border-b">
          <DialogTitle className="text-2xl font-bold">
            {data ? "Edit product" : "Create new product"}
          </DialogTitle>
        </DialogHeader>

        {/* Body */}
        {!query.isLoading && !mutation.isPending && (
          <div className="flex-1 overflow-y-auto p-6">
            <Form {...form}>
              <form
                onSubmit={form.handleSubmit(onSubmit)}
                className="space-y-8"
              >
                {/* Images */}
                <Card>
                  <CardContent className="p-6">
                    <FormField
                      control={form.control}
                      name="images"
                      render={() => (
                        <FormItem>
                          <FormLabel className="text-lg font-semibold">
                            Images *
                          </FormLabel>
                          <FormMessage />

                          {/* Image preview */}
                          {watchedImages.length > 0 && (
                            <div className="mt-6 overflow-x-auto">
                              <div className="flex gap-3">
                                {watchedImages.map((image, index) => (
                                  <div
                                    key={index}
                                    className="relative flex-shrink-0 w-32 h-32 group rounded-lg border overflow-hidden"
                                  >
                                    <img
                                      src={image || "/placeholder.svg"}
                                      alt={`Preview ${index + 1}`}
                                      className="w-full h-full object-cover"
                                    />
                                  </div>
                                ))}
                              </div>
                            </div>
                          )}
                        </FormItem>
                      )}
                    />
                  </CardContent>
                </Card>

                {/* Product info */}
                <Card>
                  <CardContent className="p-6 space-y-6">
                    <h3 className="text-lg font-semibold border-b pb-2">
                      Product information
                    </h3>

                    <FormField
                      control={form.control}
                      name="title"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Title *</FormLabel>
                          <FormControl>
                            <Input
                              placeholder="VD: MacBook Pro 14-inch 2023"
                              {...field}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="price"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Price ($) *</FormLabel>
                          <FormControl>
                            <Input type="number" placeholder="10" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                      <FormField
                        control={form.control}
                        name="category"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>Category *</FormLabel>
                            <FormControl>
                              {/* <Input placeholder="Tools" {...field} /> */}

                              <Select
                                onValueChange={field.onChange}
                                value={field.value}
                              >
                                <SelectTrigger className="w-full">
                                  <SelectValue placeholder="Select category" />
                                </SelectTrigger>
                                <SelectContent>
                                  {categories.map((c) => (
                                    <SelectItem key={c} value={c.toLowerCase()}>
                                      {c}
                                    </SelectItem>
                                  ))}
                                </SelectContent>
                              </Select>
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />

                      <FormField
                        control={form.control}
                        name="condition"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>Condition *</FormLabel>
                            <FormControl>
                              <Select
                                onValueChange={field.onChange}
                                value={field.value}
                              >
                                <SelectTrigger className="w-full">
                                  <SelectValue placeholder="Select condition" />
                                </SelectTrigger>
                                <SelectContent>
                                  {conditions.map((c) => (
                                    <SelectItem key={c} value={c.toLowerCase()}>
                                      {c}
                                    </SelectItem>
                                  ))}
                                </SelectContent>
                              </Select>
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />

                      <FormField
                        control={form.control}
                        name="brand"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>Brand</FormLabel>
                            <FormControl>
                              <Input
                                readOnly={data?.status}
                                placeholder="VD: Cisco"
                                {...field}
                              />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                    </div>

                    <FormField
                      control={form.control}
                      name="description"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Description *</FormLabel>
                          <FormControl>
                            <Textarea rows={4} {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </CardContent>
                </Card>

                {/* Additional info */}
                <Card>
                  <CardContent className="p-6 space-y-6">
                    <h3 className="text-lg font-semibold border-b pb-2">
                      Additional information
                    </h3>

                    {/* Tags */}
                    <div className="space-y-3">
                      <FormLabel>Tags</FormLabel>
                      <div className="flex gap-2">
                        <Input
                          value={tagInput}
                          onChange={(e) => setTagInput(e.target.value)}
                          placeholder="Tag and press Enter"
                          onKeyDown={(e) => {
                            if (e.key === "Enter") {
                              e.preventDefault();
                              addTag();
                            }
                          }}
                        />
                      </div>
                      {watchedTags && watchedTags?.length > 0 && (
                        <div className="flex flex-wrap gap-2">
                          {watchedTags.map((tag) => (
                            <Badge
                              onClick={() => removeTag(tag)}
                              key={tag}
                              variant="secondary"
                              className="flex items-center gap-1 px-3 py-1"
                            >
                              {tag}
                              <X className="w-3 h-3 cursor-pointer hover:text-red-500" />
                            </Badge>
                          ))}
                        </div>
                      )}
                    </div>

                    <FormField
                      control={form.control}
                      name="sku"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Sku *</FormLabel>
                          <FormControl>
                            <Input
                              readOnly={!!data}
                              placeholder="VD: MBP14-2023-512GB"
                              {...field}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="location"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Location</FormLabel>
                          <FormControl>
                            <Input
                              placeholder="VD: Hà Nội, Việt Nam"
                              {...field}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    {/* <FormField
                    control={form.control}
                    name="publist"
                    render={({ field }) => {
                      const isUpdate = !!data?.id; // đang update nếu có id
                      const canRepublish = isUpdate && data?.status === true;

                      return (
                        <FormItem>
                          <FormControl>
                            <div className="flex items-start gap-3">
                              <Checkbox
                                id="publish"
                                checked={field.value}
                                onCheckedChange={field.onChange}
                              />
                              <div className="grid gap-1 leading-none">
                                <Label htmlFor="publish">
                                  {canRepublish
                                    ? "Re-publish this product"
                                    : "Publish after saving"}
                                </Label>
                                <p className="text-sm text-muted-foreground">
                                  {canRepublish
                                    ? "Make this product visible again after updating"
                                    : "Automatically publish this product when saving"}
                                </p>
                              </div>
                            </div>
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      );
                    }}
                  /> */}
                  </CardContent>
                </Card>
              </form>
            </Form>
          </div>
        )}

        {(query.isLoading || mutation.isPending) && (
          <div className="flex items-center justify-center w-full h-full">
            <Loader />
          </div>
        )}

        {/* Footer */}
        <div className="p-6 border-t bg-white flex justify-end gap-3">
          <Button type="button" variant="outline" onClick={handleClose}>
            Close
          </Button>

          {data && (
            <Button type="button" onClick={form.handleSubmit(onSubmit)}>
              {data?.status ? <>Unlist</> : <>Publist</>}
            </Button>
          )}

          {/* <Button
            disabled={saveMutation.isPending}
            type="submit"
            onClick={form.handleSubmit(onSubmit)}
          >
            {saveMutation.isPending ? <Loader color="white" /> : "Save"}
          </Button> */}
        </div>
      </DialogContent>
    </Dialog>
  );
}
