"use client";

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

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

import {
  Form,
  FormField,
  FormItem,
  FormLabel,
  FormControl,
  FormMessage,
} from "~/components/ui/form";
import z from "zod/v3";
import { urlToBase64 } from "~/features/base64";
import { productApi } from "~/api/products-api.service";

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(),
});

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

export default function ProductModal({
  children,
  ...props
}: {
  children: ReactNode;
  onSubmit?: () => void;
}) {
  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: "",
    },
  });

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

  const conditions = ["New", "Used - like new", "Used - good", "Used - fair"];
  const categories = ["Tools"];

  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) => {
    const currentImages = form.getValues("images");
    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 (data: ProductFormData) => {
    try {
      const images = data.images;
      const convertedImages = await Promise.all(
        images.map(async (img) => {
          if (img.startsWith("blob:")) {
            // convert blob url to base64
            return await urlToBase64(img);
          }
          return img; // giữ nguyên nếu ko phải blob url
        })
      );

      const dataToSubmit = {
        ...data,
        images: convertedImages,
      };

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

      const response = await productApi.create(dataToSubmit);

      if (!response) return;

      setOpen(false);
      form.reset();
      setUrlInput("");
      setTagInput("");

      props.onSubmit?.();
    } catch (error) {
      console.error("Error submitting form:", error);
    }
  };

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

  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">
            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"
                                />
                                <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)}
                                >
                                  <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 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
                            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"
                              onClick={() => removeTag(tag)}
                            />
                          </Badge>
                        ))}
                      </div>
                    )}
                  </div>

                  <FormField
                    control={form.control}
                    name="sku"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Sku *</FormLabel>
                        <FormControl>
                          <Input
                            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>
                    )}
                  />
                </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 ? "Đang thêm..." : "Create"}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
