import { defineWidgetConfig } from "@medusajs/admin-sdk"
import { Container, Heading, Input, Button, Text, toast } from "@medusajs/ui"
import { useState, useEffect } from "react"
import type { DetailWidgetProps, AdminProduct } from "@medusajs/framework/types"
import { sdk } from "../lib/sdk"
import { useTranslation } from "react-i18next"
import { normalizeValue, isContentEqual, deepClone } from "../lib/cms-utils"

const TechnicalSpecificationsWidget = ({
  data: product
}: DetailWidgetProps<AdminProduct>) => {
  const { t } = useTranslation()

  const [specs, setSpecs] = useState<{ key: string; value: string }[]>([])
  const [lastSaved, setLastSaved] = useState<{ key: string; value: string }[] | null>(null)
  const [isSaving, setIsSaving] = useState(false)

  useEffect(() => {
    const existingSpecs = product?.metadata?.technical_specifications

    if (existingSpecs && typeof existingSpecs === "object") {
      const formatted = Object.entries(existingSpecs).map(([key, value]) => ({
        key,
        value: String(value),
      }))
      setSpecs(formatted)
      setLastSaved(normalizeValue(formatted))
    } else {
      setSpecs([])
      setLastSaved([])
    }
  }, [product])

  const handleAddRow = () => {
    setSpecs([...specs, { key: "", value: "" }])
  }

  const handleRemoveRow = (index: number) => {
    setSpecs(specs.filter((_, i) => i !== index))
  }

  const handleChange = (index: number, field: "key" | "value", newValue: string) => {
    const updated = [...specs]
    updated[index][field] = newValue
    setSpecs(updated)
  }

  const handleSave = async () => {
    if (!product?.id) {
      toast.error(t("biomketProduct.technicalSpecs.productMissing"))
      return
    }

    setIsSaving(true)

    const cleanedSpecs = specs
      .filter(s => s.key.trim() !== "" && s.value.trim() !== "")
      .reduce((acc, curr) => {
        acc[curr.key] = curr.value
        return acc
      }, {} as Record<string, string>)

    const updatedMetadata = {
      ...(product.metadata || {}),
      technical_specifications: cleanedSpecs
    }

    try {
      const response = await sdk.fetch(
        `/admin/products/${product.id}`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            metadata: updatedMetadata,
          }),
        }
      )

      if (response.ok) {
        toast.success(t("biomketProduct.technicalSpecs.saveSuccess"))
        setLastSaved(normalizeValue(specs))
        return
      }

      const message = await response.text()
      throw new Error(message || t("biomketProduct.technicalSpecs.saveError"))
    } catch (err) {
      console.error(err)
      toast.error(
        err instanceof Error
          ? err.message
          : t("biomketProduct.technicalSpecs.saveError")
      )
    } finally {
      setIsSaving(false)
    }
  }

  return (
    <Container className="p-4">
      <div className="flex items-center justify-between mb-6">
        <Heading level="h2">{t("biomketProduct.technicalSpecs.title")}</Heading>
        <Button variant="secondary" size="small" onClick={handleAddRow}>
          {t("biomketProduct.technicalSpecs.addRow")}
        </Button>
      </div>

      <div className="flex flex-col gap-4">
        {specs.length === 0 ? (
          <Text className="text-gray-500">{t("biomketProduct.technicalSpecs.empty")}</Text>
        ) : (
          specs.map((spec, index) => (
            <div key={index} className="flex gap-4">
              <Input
                placeholder={t("biomketProduct.technicalSpecs.keyPlaceholder")}
                value={spec.key}
                onChange={(e) => handleChange(index, "key", e.target.value)}
              />
              <Input
                placeholder={t("biomketProduct.technicalSpecs.valuePlaceholder")}
                value={spec.value}
                onChange={(e) => handleChange(index, "value", e.target.value)}
              />
              <Button
                variant="danger"
                size="small"
                onClick={() => handleRemoveRow(index)}
              >
                {t("biomketProduct.common.delete")}
              </Button>
            </div>
          ))
        )}
      </div>

      <div className="mt-6 flex justify-end">
        <Button 
          variant="primary" 
          onClick={handleSave} 
          isLoading={isSaving}
          disabled={lastSaved !== null && isContentEqual(specs, lastSaved)}
        >
          {t("biomketProduct.technicalSpecs.save")}
        </Button>
      </div>
    </Container>
  )
}

export const config = defineWidgetConfig({
  zone: "product.details.after",
})

export default TechnicalSpecificationsWidget
