"use client";

import { useState, useEffect } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { ImageUpload } from "@/components/forms/image-upload";
import { PricingTiers } from "@/components/forms/pricing-tiers";
import type { ProductModalProps, ProductData } from "@/lib/types";
import { toast } from "sonner";
import type React from "react";
import { Plus } from "lucide-react";
import { apiRequest } from "@/lib/storeHelper";

type CategorySelectProps = {
  categories: { _id: string; name: string }[];
  value: string;
  setProductData: React.Dispatch<React.SetStateAction<ProductData>>;
  onAddCategory: (newCategory: { _id: string; name: string }) => void;
};

export const ProductModal: React.FC<ProductModalProps> = ({
  open,
  onClose,
  onSave,
  productData,
  categories,
  editing,
  handleChange,
  handleTieredPricingChange,
  handleAddTier,
  handleRemoveTier,
  setProductData,
}) => {
  /**
   * 1) Store the selected file *separately* from productData.image
   */
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const [imageDimensions, setImageDimensions] = useState({ width: 300, height: 200 });
  const [localCategories, setLocalCategories] = useState(categories);

  // If productData.image is a *URL* (string), show it as a default preview
  useEffect(() => {
    if (productData.image && typeof productData.image === "string") {
      setImagePreview(productData.image);
    }
  }, [productData.image]);

  useEffect(() => {
    setLocalCategories(categories);
  }, [categories]);

  /**
   * 2) When user selects a file, store it and create an objectURL for preview
   */
  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) {
      // no file selected
      setSelectedFile(null);
      setImagePreview(null);
      return;
    }

    // For preview
    const objectUrl = URL.createObjectURL(file);
    setSelectedFile(file);
    setImagePreview(objectUrl);

    // Optionally, load the image to calculate dimensions
    const image = new Image();
    image.onload = () => {
      const aspectRatio = image.naturalWidth / image.naturalHeight;
      const width = aspectRatio > 1 ? 300 : 200 * aspectRatio;
      const height = aspectRatio > 1 ? 300 / aspectRatio : 200;
      setImageDimensions({ width, height });
    };
    image.src = objectUrl;
  };

  /**
   * 3) On 'Save', call the parent onSave(productData, selectedFile)
   */
  const handleSave = async () => {
    if (!productData.category) {
      toast.error("Please select or add a category");
      return;
    }

    onSave(productData, selectedFile);
    toast.success(editing ? "Product updated!" : "Product added!");
    onClose();
  };

  const handleAddCategory = (newCategory: { _id: string; name: string }) => {
    setLocalCategories((prev) => [...prev, newCategory]);
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-6xl">
        <DialogHeader>
          <DialogTitle className="text-base">
            {editing ? "Edit Product" : "Add Product"}
          </DialogTitle>
        </DialogHeader>

        <div className="grid grid-cols-1 lg:grid-cols-[2fr_1fr] gap-8 py-4">
          <ProductBasicInfo
            productData={productData}
            handleChange={handleChange}
            categories={localCategories}
            setProductData={setProductData}
            onAddCategory={handleAddCategory}
          />

          <div className="space-y-6">
            <ImageUpload
              imagePreview={imagePreview}
              handleImageChange={handleImageChange}
              imageDimensions={imageDimensions}
            />
            <PricingTiers
              pricing={productData.pricing}
              handleTierChange={handleTieredPricingChange}
              handleRemoveTier={handleRemoveTier}
              handleAddTier={handleAddTier}
            />
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={onClose}>
            Cancel
          </Button>
          <Button onClick={handleSave}>
            {editing ? "Update" : "Create"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

const ProductBasicInfo: React.FC<{
  productData: ProductData;
  handleChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void;
  categories: { _id: string; name: string }[];
  setProductData: React.Dispatch<React.SetStateAction<ProductData>>;
  onAddCategory: (newCategory: { _id: string; name: string }) => void;
}> = ({ productData, handleChange, categories, setProductData, onAddCategory }) => (
  <div className="space-y-4">
    <div>
      <label className="text-sm font-medium">Product Name</label>
      <Input
        name="name"
        placeholder="Product Name"
        value={productData.name}
        onChange={handleChange}
        className="text-sm h-9"
      />
    </div>

    <div>
      <label className="text-sm font-medium">Description</label>
      <Textarea
        name="description"
        placeholder="Product Description"
        value={productData.description}
        onChange={handleChange}
        rows={4}
        className="text-sm h-24"
      />
    </div>

    <CategorySelect
      categories={categories}
      value={productData.category}
      setProductData={setProductData}
      onAddCategory={onAddCategory}
    />

    <UnitTypeSelect
      value={productData.unitType}
      setProductData={setProductData}
    />
  </div>
);

const CategorySelect: React.FC<CategorySelectProps> = ({
  categories,
  value,
  setProductData,
  onAddCategory,
}) => {
  const [isAddingCategory, setIsAddingCategory] = useState(false);
  const [newCategoryName, setNewCategoryName] = useState("");

  const handleAddCategory = async () => {
    if (!newCategoryName.trim()) {
      toast.error("Category name cannot be empty");
      return;
    }

    try {
      const response = await apiRequest("/categories", "POST", { name: newCategoryName });
      const newCategory = response.data;
      setProductData((prev) => ({ ...prev, category: newCategory._id }));
      onAddCategory(newCategory);
      setIsAddingCategory(false);
      setNewCategoryName("");
      toast.success("New category added successfully");
    } catch (error) {
      console.error("Failed to add new category:", error);
      toast.error("Failed to add new category");
    }
  };

  return (
    <div className="space-y-2">
      <label className="text-sm font-medium">Category</label>
      <div className="flex items-center space-x-2">
        {isAddingCategory ? (
          <Input
            value={newCategoryName}
            onChange={(e) => setNewCategoryName(e.target.value)}
            placeholder="New category name"
            className="flex-grow h-9 text-sm"
          />
        ) : (
          <Select
            value={value || "placeholder"}
            onValueChange={(val) =>
              setProductData((prev) => ({
                ...prev,
                category: val === "placeholder" ? "" : val,
              }))
            }
          >
            <SelectTrigger className={"h-9 text-sm"}>
              <SelectValue placeholder="Select category..." />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="placeholder">Select category...</SelectItem>
              {categories.map((cat) => (
                <SelectItem key={cat._id} value={cat._id}>
                  {cat.name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        )}
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={() => {
            if (isAddingCategory) {
              handleAddCategory();
            } else {
              setIsAddingCategory(true);
            }
          }}
        >
          <Plus className="w-4 h-4 mr-1" />
          {isAddingCategory ? "Save" : "Add"}
        </Button>
      </div>
    </div>
  );
};

const UnitTypeSelect: React.FC<{
  value: string;
  setProductData: React.Dispatch<React.SetStateAction<ProductData>>;
}> = ({ value, setProductData }) => (
  <div className="space-y-2">
    <label className="text-sm font-medium">Unit Type</label>
    <div className="flex items-center space-x-2">
      <Select
        value={value || "placeholder"}
        onValueChange={(val) =>
          setProductData((prev) => ({
            ...prev,
            unitType: val === "placeholder" ? "" : val,
          }))
        }
      >
        <SelectTrigger className="h-9 text-sm">
          <SelectValue placeholder="Select unit type" />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="placeholder" disabled>
            Select unit type
          </SelectItem>
          <SelectItem value="pcs">Pieces (pcs)</SelectItem>
          <SelectItem value="gr">Grams (gr)</SelectItem>
          <SelectItem value="kg">Kilograms (kg)</SelectItem>
        </SelectContent>
      </Select>
      <Button type="button" variant="outline" size="sm" disabled>
        <Plus className="w-4 h-4 mr-1" />
        Add
      </Button>
    </div>
  </div>
);