"use client";
import postData from "@/api/post-data";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { TableBody, TableCell, TableRow } from "@/components/ui/table";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { Loader2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { RefreshCw } from "lucide-react";

export default function ProductLabelsBody({ labels, locale }) {
   const [isSubmitPending, setIsSubmitPending] = useState(false);
   const [isSyncPendingIndex, setIsSyncPendingIndex] = useState(null);
   const t = useTranslations('vendor');

  async function onSubmit() {
    const succeed = [];
    const failed = [];
    setIsSubmitPending(true);

    // Use Promise.all to wait for all async operations to complete
    const updatePromises = labels.map(async (label) => {
      // Find input for word using a specific naming convention
      const title =
        document.querySelector(`input[name="word_${label.item_id}"]`)?.value ||
        "";
      // Find input for value using a specific naming convention
      const value =
        document.querySelector(`input[name="value_${label.item_id}"]`)?.value ||
        "";

      // Only proceed if there's a change
      if (title !== label.trans_title || value !== label.trans_val) {
        const formData = new FormData();
        formData.append(`word[${label.item_id}][]`, title);
        formData.append(`value[${label.item_id}][]`, value);

            const { error } = await postData({
               endPoint: '/user/products/addtional-details/translation',
               locale,
               body: formData
            });


        if (error) {
          failed.push(label.item_id);
        } else {
          succeed.push(label.item_id);
        }
      }
    });

    // Wait for all updates to complete
    await Promise.all(updatePromises);

    setIsSubmitPending(false);

    if (failed.length === 0 && succeed.length === 0) {
      toastSuccess("no value changes");
    }

    if (failed.length > 0) {
      toastError(
        locale === "en"
          ? `Failed to update ${failed.length} labels`
          : `حقل ${failed.length} فشل في تحديث`
      );
    }

    if (succeed.length > 0) {
      toastSuccess(
        locale === "en"
          ? `Updated ${succeed.length} labels`
          : `تم تحديث ${succeed.length} حقل`
      );
    }
  }


   async function handleSyncLabel(ori, value, i) {
      setIsSyncPendingIndex(i);
      const formData = new FormData();
      formData.append('original', ori);
      formData.append('value', value);
      const { error, message } = await postData({
         endPoint: '/user/products/addtional-details/translation/sync',
         token,
         locale,
         body: formData
      });
      setIsSyncPendingIndex(null);
      if (error) {
         toastError(message);
         return;
      }
      toastSuccess(message);
   }
   return (
      <TableBody>
         {labels.map((label, i) => (
            <TableRow key={i}>
               <TableCell className="font-medium">{i + 1}</TableCell>
               <TableCell>{label.title}</TableCell>
               <TableCell>
                  <Input
                     name={`word_${label.item_id}`}
                     defaultValue={label.trans_title}
                  />
               </TableCell>
               <TableCell>{label.value}</TableCell>
               <TableCell>
                  <Input
                     name={`value_${label.item_id}`}
                     defaultValue={label.trans_val}
                  />
               </TableCell>
               {
                  label?.trans_val &&
                  <TableCell>
                     <Button onClick={() => handleSyncLabel(label.value, label.trans_val, i)} className="bg-amber-500 hover:bg-amber-500/90">
                        {
                           isSyncPendingIndex === i ? <RefreshCw className='animate-spin text-center' />
                              :
                              <RefreshCw />
                        }
                     </Button>
                  </TableCell>
               }
            </TableRow>
         ))}
         <TableRow>
            <TableCell colSpan={2} className='bg-transparent'>
               {
                  <Button disabled={isSubmitPending} onClick={onSubmit} className="w-full">{
                     isSubmitPending ? <Loader2 className='animate-spin text-center' />
                        :
                        t('save')
                  }
                  </Button>
               }
            </TableCell>
         </TableRow>
      </TableBody>
   );
}

