"use client";

import React, { useCallback, useEffect, useState, useMemo, memo } from "react";
import {
  getProductAttributes,
  getAttributes,
  getAttributeValueOptions,
  linkAttributeToProduct,
  unlinkAttributeFromProduct,
} from "@/actions/catalog";
import { Button } from "@/components/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { UniversalCombobox } from "@/components/dashboard/UniversalCombobox";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { Trash, Plus, Loader2 } from "lucide-react";
import { toast } from "sonner";

interface ProductAttributesManagerProps {
  productId: string;
}

export const ProductAttributesManager = memo(({ productId }: ProductAttributesManagerProps) => {
  const [productAttributes, setProductAttributes] = useState<any[]>([]);
  const [attributes, setAttributes] = useState<any[]>([]);
  const [selectedAttr, setSelectedAttr] = useState<string>("");
  const [values, setValues] = useState<any[]>([]);
  const [selectedValue, setSelectedValue] = useState<string>("");
  const [isVariant, setIsVariant] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [removingId, setRemovingId] = useState<string | null>(null);

  /**
   * ⚡ Optimization: Memoized options for UniversalCombobox
   * Prevents re-rendering of the memoized UniversalCombobox by providing stable array references.
   */
  const attributeOptions = useMemo(() =>
    attributes.map(a => ({ value: a.id, label: a.name })),
    [attributes]
  );

  const valueOptions = useMemo(() =>
    values.map(v => ({ value: v.id, label: v.name })),
    [values]
  );

  const loadProductAttributes = useCallback(async () => {
    const response = await getProductAttributes(productId);
    if (response.success) {
      setProductAttributes(response.data);
    }
  }, [productId]);

  const loadAttributes = useCallback(async () => {
    const response = await getAttributes({ limit: 100, page: 1 });
    if (response.success) {
      setAttributes(response.data.documents);
    }
  }, []);

  const loadAttributeValues = useCallback(async (attrId: string) => {
    const response = await getAttributeValueOptions(attrId);
    if (response.success) {
      setValues(response.data);
    }
  }, []);

  useEffect(() => {
    loadProductAttributes();
    loadAttributes();
  }, [loadProductAttributes, loadAttributes]);

  useEffect(() => {
    if (selectedAttr) {
      loadAttributeValues(selectedAttr);
    } else {
      setValues([]);
      setSelectedValue("");
    }
  }, [selectedAttr, loadAttributeValues]);

  const onAdd = async () => {
    if (!selectedAttr || !selectedValue) {
      toast.error("Bitte Attribut und Wert auswählen.");
      return;
    }

    setLoading(true);
    try {
      const response = await linkAttributeToProduct({
        product_id: productId,
        attribute_id: selectedAttr,
        value_id: selectedValue,
      });
      if (response.success) {
        toast.success("Attribut verknüpft.");
        loadProductAttributes();
        setSelectedAttr("");
        setSelectedValue("");
        setIsVariant(false);
      } else {
        toast.error(response.error || "Fehler beim Verknüpfen.");
      }
    } catch (error) {
      toast.error("Fehler beim Verknüpfen.");
    } finally {
      setLoading(false);
    }
  };

  const onRemove = async (id: string) => {
    setRemovingId(id);
    try {
      const response = await unlinkAttributeFromProduct({
        product_id: productId,
        attribute_id: id,
      });
      if (response.success) {
        toast.success("Attribut entfernt.");
        await loadProductAttributes();
      } else {
        toast.error(response.error || "Fehler beim Entfernen.");
      }
    } catch (error) {
      toast.error("Fehler beim Entfernen.");
    } finally {
      setRemovingId(null);
    }
  };

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4 items-end bg-muted/30 p-4 rounded-lg border border-dashed border-border">
        <div className="flex flex-col gap-2">
          <Label className="text-xs font-semibold uppercase text-muted-foreground">Attribut</Label>
          <UniversalCombobox
            label="Attribut wählen"
            name="attr"
            options={attributeOptions}
            value={selectedAttr}
            onChange={setSelectedAttr}
          />
        </div>
        <div className="flex flex-col gap-2">
          <Label className="text-xs font-semibold uppercase text-muted-foreground">Wert</Label>
          <UniversalCombobox
            label="Wert wählen"
            name="val"
            options={valueOptions}
            value={selectedValue}
            onChange={setSelectedValue}
          />
        </div>
        <div className="flex items-center gap-2 pb-2">
          <Checkbox
            id="isVariant"
            checked={isVariant}
            onCheckedChange={(checked) => setIsVariant(!!checked)}
          />
          <Label htmlFor="isVariant" className="text-xs font-medium cursor-pointer">Varianten-Dimension</Label>
        </div>
        <Button onClick={onAdd} disabled={loading || !selectedAttr || !selectedValue}>
          {loading ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Plus className="h-4 w-4 mr-2" />}
          Hinzufügen
        </Button>
      </div>

      <div className="rounded-md border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Attribut</TableHead>
              <TableHead>Wert</TableHead>
              <TableHead className="text-center">Variante?</TableHead>
              <TableHead className="text-right w-[100px]"></TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {productAttributes.length === 0 ? (
              <TableRow>
                <TableCell colSpan={4} className="h-24 text-center text-muted-foreground">
                  Keine Attribute verknüpft.
                </TableCell>
              </TableRow>
            ) : (
              productAttributes.map((pa) => (
                <TableRow key={pa.attribute_id}>
                  <TableCell className="font-medium">{pa.attribute_name}</TableCell>
                  <TableCell>{pa.value_name}</TableCell>
                  <TableCell className="text-center">
                    {pa.is_variant ? (
                      <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-primary/10 text-primary border border-primary/20">Ja</span>
                    ) : (
                      <span className="text-muted-foreground text-xs font-medium">Nein</span>
                    )}
                  </TableCell>
                  <TableCell className="text-right">
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => onRemove(pa.attribute_id)}
                      className="text-destructive hover:text-destructive hover:bg-destructive/10"
                      aria-label="Attribut entfernen"
                      disabled={removingId === pa.attribute_id}
                    >
                      {removingId === pa.attribute_id ? (
                        <Loader2 className="h-4 w-4 animate-spin" />
                      ) : (
                        <Trash className="h-4 w-4" />
                      )}
                    </Button>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>
    </div>
  );
});

ProductAttributesManager.displayName = "ProductAttributesManager";
