"use client";

import { useEffect, useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Input } from "@/components/ui/input";
import DividerWithText from "@/components/ui/FormInput/DividerWithText";
import { getMetals } from "@/Services/Metals/ApiMetal";
import axios from "axios";
import toast from "react-hot-toast";

export default function MetalSettings() {
  const queryClient = useQueryClient();
  const [metalRates, setMetalRates] = useState({});
  const [metalStatuses, setMetalStatuses] = useState({});

  // Fetch metals from database
  const { data: metals = [], isLoading } = useQuery({
    queryKey: ["metals"],
    queryFn: getMetals,
  });

  const metalData = metals?.rows;

  // Fetch existing metal rates
  const { data: existingRates = [] } = useQuery({
    queryKey: ["metal-rates"],
    queryFn: async () => {
      const response = await axios.get("/api/metal-rates");
      return response.data.rows || [];
    },
  });

  // Initialize rates and statuses from existing data
  useEffect(() => {
    if (existingRates.length > 0) {
      const ratesMap = {};
      const statusesMap = {};
      existingRates.forEach((rate) => {
        ratesMap[rate.metal_id] = rate.rate;
        statusesMap[rate.metal_id] = rate.status === 1;
      });
      setMetalRates(ratesMap);
      setMetalStatuses(statusesMap);
    }
  }, [existingRates]);

  const mutation = useMutation({
    mutationFn: async (ratesData) => {
      // Save each metal rate with status
      const promises = ratesData.map(({ metal_id, rate, status }) => {
        const formData = new FormData();
        formData.append("metal_id", metal_id);
        formData.append("rate", rate);
        formData.append("status", status ? "1" : "0");
        return axios.post("/api/metal-rates", formData);
      });
      return Promise.all(promises);
    },
    onSuccess: () => {
      queryClient.invalidateQueries(["metal-rates"]);
      toast.success("Metal rates saved successfully!");
    },
    onError: () => {
      toast.error("Failed to save metal rates");
    },
  });

  const handleRateChange = (metalId, value) => {
    setMetalRates((prev) => ({
      ...prev,
      [metalId]: value,
    }));
  };

  const handleStatusChange = (metalId, value) => {
    setMetalStatuses((prev) => ({
      ...prev,
      [metalId]: value,
    }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    // Filter only metals with rates assigned and include status
    const ratesData = Object.entries(metalRates)
      .filter(([_, rate]) => rate && rate > 0)
      .map(([metal_id, rate]) => ({
        metal_id: parseInt(metal_id),
        rate: parseFloat(rate),
        status:
          metalStatuses[metal_id] !== undefined
            ? metalStatuses[metal_id]
            : true,
      }));

    if (ratesData.length === 0) {
      toast.error("Please assign at least one metal rate");
      return;
    }

    mutation.mutate(ratesData);
  };

  // Filter only active metals
  const activeMetals = metalData?.filter((metal) => metal.status === 1);

  if (isLoading) {
    return (
      <div className="bg-white w-full border border-gray-200 rounded-md p-6">
        <p className="text-center text-gray-500">Loading metals...</p>
      </div>
    );
  }

  if (activeMetals.length === 0) {
    return (
      <div className="bg-white w-full border border-gray-200 rounded-md">
        <div className="border-b p-4 bg-brand-dark/5">
          <h2 className="text-xl font-semibold text-brand-dark">Metal Rates</h2>
        </div>
        <div className="p-6">
          <p className="text-center text-gray-500">
            No metals found. Please add metals first in Metal Management.
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-white w-full border border-gray-200 rounded-md">
      <div className="border-b p-4 bg-brand-dark/5">
        <h2 className="text-xl font-semibold text-brand-dark">Metal Rates</h2>
      </div>
      <form onSubmit={handleSubmit} className="p-6 space-y-6">
        <DividerWithText
          text="Assign Rates to Metals"
          showLines
          underline
          position="start"
          textClassName="text-brand-dark"
          lineColor="border-brand-dark"
        />

        <div className="space-y-4">
          {activeMetals.map((metal) => (
            <div
              key={metal.id}
              className="grid grid-cols-1 md:grid-cols-4 gap-4 p-4 border border-gray-200 rounded-lg bg-gray-50"
            >
              <div className="md:col-span-1">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Metal Name
                </label>
                <Input
                  type="text"
                  value={metal.metal_name}
                  disabled
                  className="bg-gray-100 text-gray-700"
                />
              </div>

              <div className="md:col-span-1">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Unit
                </label>
                <Input
                  type="text"
                  value={metal.unit}
                  disabled
                  className="bg-gray-100 text-gray-700 capitalize"
                />
              </div>

              <div className="md:col-span-1">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Purity/Carat
                </label>
                <Input
                  type="text"
                  value={metal.purity || "-"}
                  disabled
                  className="bg-gray-100 text-gray-700"
                />
              </div>

              <div className="md:col-span-1">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Rate (₹) per {metal.unit}
                </label>
                <Input
                  type="number"
                  min="0"
                  step="0.01"
                  value={metalRates[metal.id] || ""}
                  onChange={(e) => handleRateChange(metal.id, e.target.value)}
                  placeholder="Enter rate"
                />
              </div>

              {/* <div className="md:col-span-1">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Show in Navbar
                </label>
                <div className="flex items-center h-[42px]">
                  <Switch
                    checked={metalStatuses[metal.id] !== undefined ? metalStatuses[metal.id] : true}
                    onCheckedChange={(value) => handleStatusChange(metal.id, value)}
                  />
                  <span className="ml-2 text-sm text-gray-600">
                    {metalStatuses[metal.id] !== undefined && metalStatuses[metal.id] ? "Active" : "Inactive"}
                  </span>
                </div>
              </div> */}
            </div>
          ))}
        </div>

        <div className="flex justify-end pt-4">
          <Button type="submit" variant="dark" disabled={mutation.isPending}>
            {mutation.isPending ? "Saving..." : "Save Metal Rates"}
          </Button>
        </div>
      </form>
    </div>
  );
}
