"use client";

import { useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";
import api from "@/lib/api";
import toast from "react-hot-toast";
export default function VariationsPage() {
  const searchParams = useSearchParams();
  const id = searchParams.get("id");

  const [product, setProduct] = useState<any>(null);
  const [variations, setVariations] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!id) {
      setLoading(false);
      return;
    }

    loadData();
  }, [id]);

  const loadData = async () => {
    try {
      setLoading(true);

      const token = localStorage.getItem("auth_token");

      const res = await api.get(`/vendor/products/${id}`, {
        headers: { Authorization: `Bearer ${token}` },
      });

      setProduct(res.data.data);

      const vres = await api.get(
        `/vendor/products/${id}/variations`,
        {
          headers: { Authorization: `Bearer ${token}` },
        }
      );

      setVariations(vres.data.data || []);
    } catch (err) {
      console.log("Load error:", err);
    } finally {
      setLoading(false);
    }
  };

  const updateField = (index: number, field: string, value: any) => {
    const copy = [...variations];
    copy[index] = {
      ...copy[index],
      [field]: value,
    };
    setVariations(copy);
  };

  const updateVariation = async (variation: any) => {
    try {
      const token = localStorage.getItem("auth_token");

      await api.post(
        `/vendor/variations/${variation.id}`,
        {
          price: variation.price,
          sale_price: variation.sale_price,
          stock_quantity: variation.stock_quantity,
          sku: variation.sku,
        },
        {
          headers: { Authorization: `Bearer ${token}` },
        }
      );

      toast.success("Updated successfully");
    } catch (err) {
      console.log(err);
      toast.error("Update failed");
    }
  };

  const deleteVariation = async (variationId: number) => {
    try {
      const token = localStorage.getItem("auth_token");

      await api.delete(`/vendor/variations/${variationId}`, {
        headers: { Authorization: `Bearer ${token}` },
      });

      setVariations((prev) =>
        prev.filter((v) => v.id !== variationId)
      );
    } catch (err) {
      console.log(err);
    }
  };

  // ❗ no id case
  if (!id) {
    return (
      <div className="p-6 text-red-500">
        Invalid product ID
      </div>
    );
  }

  // ⏳ loading
  if (loading) {
    return (
      <div className="p-6 text-gray-500">
        Loading variations...
      </div>
    );
  }

  return (
    <div className="p-6 bg-gray-50 min-h-screen">

      <div className="mb-6">
        <h1 className="text-2xl font-black">
          Variations
        </h1>

        <p className="text-gray-500">
          {product?.name}
        </p>
      </div>

      <div className="bg-white rounded-2xl shadow overflow-x-auto">

        <table className="w-full min-w-[900px]">

          <thead className="bg-gray-100 text-left">
            <tr>
              <th className="p-4">Variation</th>
              <th>SKU</th>
              <th>Price</th>
              <th>Sale Price</th>
              <th>Stock</th>
              <th>Status</th>
              <th className="text-right p-4">Actions</th>
            </tr>
          </thead>

          <tbody>
            {variations.map((v, index) => (
              <tr key={v.id} className="border-t">

                <td className="p-4 font-semibold">
                  {v.attribute_values
                    ?.map((a: any) => a.attribute_value?.value)
                    .join(" / ")}
                </td>

                <td>
                  <input
                    value={v.sku || ""}
                    onChange={(e) =>
                      updateField(index, "sku", e.target.value)
                    }
                    className="border p-2 rounded w-[120px]"
                  />
                </td>

                <td>
                  <input
                    value={v.price || ""}
                    onChange={(e) =>
                      updateField(index, "price", e.target.value)
                    }
                    className="border p-2 rounded w-[100px]"
                  />
                </td>

                <td>
                  <input
                    value={v.sale_price || ""}
                    onChange={(e) =>
                      updateField(index, "sale_price", e.target.value)
                    }
                    className="border p-2 rounded w-[100px]"
                  />
                </td>

                <td>
                  <input
                    value={v.stock_quantity || ""}
                    onChange={(e) =>
                      updateField(index, "stock_quantity", e.target.value)
                    }
                    className="border p-2 rounded w-[80px]"
                  />
                </td>

                <td>
                  <span
                    className={`px-3 py-1 rounded-full text-sm ${
                      v.status
                        ? "bg-green-100 text-green-700"
                        : "bg-red-100 text-red-700"
                    }`}
                  >
                    {v.status ? "Active" : "Inactive"}
                  </span>
                </td>

                <td className="text-right p-4 flex gap-2 justify-end">
                  <button
                    onClick={() => updateVariation(v)}
                    className="bg-blue-600 text-white px-3 py-1 rounded"
                  >
                    Save
                  </button>

                  <button
                    onClick={() => deleteVariation(v.id)}
                    className="bg-red-600 text-white px-3 py-1 rounded"
                  >
                    Delete
                  </button>
                </td>

              </tr>
            ))}
          </tbody>

        </table>
      </div>
    </div>
  );
}