"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { ImageIcon, Link, Plus, Upload, 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 { Tabs, TabsContent, TabsList, TabsTrigger } from "~/components/ui/tabs";
import { Textarea } from "~/components/ui/textarea";

import { useMutation, useQuery } from "@tanstack/react-query";
import axios from "axios";
import z from "zod/v3";
import { productApi } from "~/api/products-api.service";
import { ConfirmAlert } from "~/components/btn/confirm-alert";
import Loader from "~/components/loader";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "~/components/ui/form";
import { urlToBase64 } from "~/features/base64";
import { delay } from "~/features/delay";
import { cn } from "~/lib/utils";
import { Checkbox } from "~/components/ui/checkbox";
import { Label } from "~/components/ui/label";

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?: IProduct;
}) {
  const [open, setOpen] = useState(false);
  const [tagInput, setTagInput] = useState("");
  const [urlInput, setUrlInput] = useState("");

  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"];

  const { isLoading, refetch, ...query } = useQuery({
    queryKey: ["product", data?.id],
    queryFn: async () => {
      if (!data) return null;

      await delay(300); // Giả lập delay để thấy loading
      const res = await productApi.get(data.id);
      return res;
    },
    enabled: false,
  });

  const delImageMutation = useMutation({
    mutationFn: async (imageUrl: string) => {
      await delay(300);

      return await axios.delete(imageUrl);
    },
    onSuccess: (data) => {
      refetch();
    },
  });

  const actionMutation = useMutation({
    mutationFn: async (formData: ProductFormData & { id?: number }) => {
      const { id, brand, publist, ...rest } = formData;
      let response;

      if (id) {
        // Update
        response = await productApi.update(id, { ...rest, id });

        if (publist && response?.data) {
          const action = data?.status ? "re-publist" : "publist";
          await productApi.customAction(
            response.data.id,
            action,
            response.data,
            "POST",
            { toast_success: false }
          );
        }
      } else {
        // Create
        response = await productApi.create({ ...rest, brand });

        if (publist && response?.data) {
          await productApi.customAction(
            response.data.id,
            "publist",
            response.data
          );
        }
      }

      return response;
    },
    onSuccess: () => {
      refetch(); // làm mới danh sách
      setOpen(false);
      setUrlInput("");
      setTagInput("");
      props.onSubmit?.();
      form.reset();
    },
    onError: (error) => {
      console.error("Mutation failed:", error);
    },
  });

  const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (files) {
      const newImages: string[] = [];
      const currentImages = form.getValues("images");

      Array.from(files).forEach((file) => {
        const url = URL.createObjectURL(file);
        newImages.push(url);
      });

      form.setValue("images", [...currentImages, ...newImages]);
    }
  };

  const addImageFromUrl = () => {
    if (urlInput.trim() && !watchedImages.includes(urlInput.trim())) {
      const currentImages = form.getValues("images");
      form.setValue("images", [...currentImages, urlInput.trim()]);
      setUrlInput("");
    }
  };

  const removeImage = (index: number, image: string) => {
    const currentImages = form.getValues("images");

    if (data && isHttpUrl(image)) {
      delImageMutation.mutate(image);
    } else {
      form.setValue(
        "images",
        currentImages.filter((_, i) => i !== index)
      );
    }
  };

  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 ({ images, ...values }: ProductFormData) => {
    try {
      let imagesToConvert: string[] = [];

      if (data) {
        // Có data => đang update
        const oldImages = data.images || [];
        const newImages = images || [];

        // Lấy ra hình khác so với data.images
        imagesToConvert = newImages.filter((img) => !oldImages.includes(img));
      } else {
        // Không có data => đang create
        imagesToConvert = images || [];
      }

      // Convert blob url sang base64 nếu cần
      const convertedImages = await Promise.all(
        imagesToConvert.map(async (img) =>
          img.startsWith("blob:") ? await urlToBase64(img) : img
        )
      );

      const dataToSubmit: ProductFormData = {
        ...values,
        images: convertedImages,
      };

      console.log("Product data to submit:", dataToSubmit);

      // const response = data
      //   ? await (async () => {
      //       const { brand, ...d } = dataToSubmit;
      //       return await productApi.update(data.id, { ...d, id: data.id });
      //     })()
      //   : await productApi.create(dataToSubmit);

      // if (!response) return;

      actionMutation.mutate({ ...dataToSubmit, id: data?.id });

      console.log("Hình mới cần xử lý:", convertedImages);
    } catch (error) {
      console.error("Error submitting form:", error);
    }
  };

  const isHttpUrl = (url: string) => {
    try {
      const u = new URL(url);
      return u.protocol === "http:" || u.protocol === "https:";
    } catch {
      return false;
    }
  };

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

  useEffect(() => {
    if (data) {
      form.reset(data);
    }
  }, [data]);

  useEffect(() => {
    if (query.isSuccess && query.isFetched && query.data?.data) {
      form.reset(query.data?.data);
    }
  }, [delImageMutation.isSuccess, query.isFetched, query.isSuccess]);

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>{children}</DialogTrigger>
      <DialogContent 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 */}
        <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 />
                        <Tabs defaultValue="upload" className="w-full">
                          <TabsList className="grid w-full grid-cols-2 mb-4">
                            <TabsTrigger
                              value="upload"
                              className="flex items-center gap-2"
                            >
                              <Upload className="w-4 h-4" />
                              Local
                            </TabsTrigger>
                            <TabsTrigger
                              value="url"
                              className="flex items-center gap-2"
                            >
                              <Link className="w-4 h-4" />
                              Link image
                            </TabsTrigger>
                          </TabsList>

                          <TabsContent value="upload">
                            <div className="border-2 border-dashed border-gray-300 rounded-xl p-8 text-center hover:border-blue-400 transition-colors">
                              <input
                                type="file"
                                multiple
                                accept="image/*"
                                onChange={handleImageUpload}
                                className="hidden"
                                id="image-upload"
                              />
                              <label
                                htmlFor="image-upload"
                                className="cursor-pointer"
                              >
                                <div className="flex flex-col items-center">
                                  <div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4">
                                    <ImageIcon className="w-8 h-8 text-gray-600" />
                                  </div>
                                  <h3 className="text-lg font-semibold text-gray-700 mb-2">
                                    Upload
                                  </h3>
                                  <p className="text-sm text-gray-500">
                                    Drag or click to select image
                                  </p>
                                </div>
                              </label>
                            </div>
                          </TabsContent>

                          <TabsContent value="url">
                            <div className="flex gap-2">
                              <Input
                                value={urlInput}
                                onChange={(e) => setUrlInput(e.target.value)}
                                placeholder="https://example.com/image.jpg"
                                className="flex-1"
                              />
                              <Button
                                type="button"
                                onClick={addImageFromUrl}
                                variant="outline"
                              >
                                <Plus className="w-4 h-4" />
                              </Button>
                            </div>
                          </TabsContent>
                        </Tabs>

                        {/* Image preview */}
                        {watchedImages.length > 0 && (
                          <div className="mt-6 grid grid-cols-2 md:grid-cols-4 gap-4">
                            {watchedImages.map((image, index) => (
                              <div key={index} className="relative group">
                                <img
                                  src={image || "/placeholder.svg"}
                                  alt={`Preview ${index + 1}`}
                                  className="w-full h-32 object-cover rounded-lg border"
                                />
                                {data && isHttpUrl(image) ? (
                                  <ConfirmAlert
                                    onConfirm={() => removeImage(index, image)}
                                  >
                                    <Button
                                      type="button"
                                      variant="destructive"
                                      size="sm"
                                      className={cn(
                                        "absolute top-2 right-2 h-8 w-8 p-0 opacity-0 ",
                                        {
                                          ["group-hover:opacity-100"]:
                                            !delImageMutation.isPending,
                                        }
                                      )}
                                    >
                                      {delImageMutation.isPending ? (
                                        <Loader color="white" />
                                      ) : (
                                        <X className="w-4 h-4" />
                                      )}
                                    </Button>
                                  </ConfirmAlert>
                                ) : (
                                  <Button
                                    type="button"
                                    variant="destructive"
                                    size="sm"
                                    className="absolute top-2 right-2 h-8 w-8 p-0 opacity-0 group-hover:opacity-100"
                                    onClick={() => removeImage(index, image)}
                                  >
                                    <X className="w-4 h-4" />
                                  </Button>
                                )}
                              </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}
                              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();
                          }
                        }}
                      />
                      <Button type="button" onClick={addTag} variant="outline">
                        <Plus className="w-4 h-4" />
                      </Button>
                    </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>

        {/* Footer */}
        <div className="p-6 border-t bg-white flex justify-end gap-3">
          <Button type="button" variant="outline" onClick={handleClose}>
            Cancel
          </Button>
          <Button
            type="submit"
            onClick={form.handleSubmit(onSubmit)}
            disabled={form.formState.isSubmitting}
          >
            {form.formState.isSubmitting || actionMutation.isPending ? (
              <Loader color="white" />
            ) : data ? (
              "Save"
            ) : (
              "Create"
            )}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
