"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 React

export const ProductModal: React.FC<ProductModalProps> = ({
  open,
  onClose,
  onSave,
  productData,
  categories,
  editing,
  handleChange,
  handleTieredPricingChange,
  handleAddTier,
  handleRemoveTier,
  setProductData,
}) => {
  const [imagePreview, setImagePreview] = useState<string | null>(null)
  const [imageDimensions, setImageDimensions] = useState({ width: 300, height: 200 })

  useEffect(() => {
    if (productData.image && typeof productData.image === "string") {
      setImagePreview(productData.image)
    }
  }, [productData.image])

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) {
      setProductData({ ...productData, image: null })
      setImagePreview(null)
      return
    }

    const image = new Image()
    const objectUrl = URL.createObjectURL(file)

    image.onload = () => {
      const aspectRatio = image.naturalWidth / image.naturalHeight
      const width = aspectRatio > 1 ? 300 : 200 * aspectRatio
      const height = aspectRatio > 1 ? 300 / aspectRatio : 200

      setProductData({ ...productData, image: file })
      setImagePreview(objectUrl)
      setImageDimensions({ width, height })
    }

    image.src = objectUrl
  }

  const handleSave = () => {
    onSave(productData)
    toast.success(editing ? "Product updated!" : "Product added!")
    onClose()
  }

  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={categories}
            setProductData={setProductData}
          />
          <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>>
}> = ({ productData, handleChange, categories, setProductData }) => (
  <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} />

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

const CategorySelect: React.FC<{
  categories: { _id: string; name: string }[]
  value: string
  setProductData: React.Dispatch<React.SetStateAction<ProductData>>
}> = ({ categories, value, setProductData }) => (
  <div>
    <label className="text-sm font-medium">Category</label>
    <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>
  </div>
)

const UnitTypeSelect: React.FC<{
  value: string
  setProductData: React.Dispatch<React.SetStateAction<ProductData>>
}> = ({ value, setProductData }) => (
  <div>
    <label className="text-sm font-medium">Unit Type</label>
    <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>
  </div>
)

