"use client";

import {
  useFormContext,
  useFieldArray,
  Controller,
  useWatch,
} from "react-hook-form";
import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import CustomInput from "@/components/ui/FormInput/CustomInput";
import { CustomDropZone, CustomToggle } from "@/components/ui/FormInput/Inputs";
import MultiSelect from "@/components/ui/FormInput/MultiSelectNew";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { addMetaTag } from "@/Services/Meta/ApiMeta";

const MetaFields = ({ reference_type, reference_id, onClose }) => {
  const queryClient = useQueryClient();
  const {
    control,
    reset,
    setValue,
    formState: { errors },
    watch,
  } = useFormContext();

  const { fields, append, remove } = useFieldArray({
    control,
    name: "metas",
  });

  const [uploadedFiles, setUploadedFiles] = useState(
    fields.map(() => ({ image: [] }))
  );

  const metas = useWatch({ control, name: "metas" });

  // Sync image values to `content.image`
  useEffect(() => {
    fields.forEach((_, index) => {
      setValue(`metas.${index}.content`, uploadedFiles[index]);
    });
  }, [uploadedFiles, setValue, fields.length]);

  const metaMutation = useMutation({
    mutationFn: addMetaTag,
    onSuccess: () => {
      queryClient.invalidateQueries(["meta_tags"]);
      reset();
      setUploadedFiles([]);
      onClose?.();
    },
  });

  const handleSubmitMeta = () => {
    const values = watch();
    const formData = new FormData();

    formData.append("folder", "meta");
    formData.append("reference_type", reference_type);
    formData.append("reference_id", reference_id);

    const metasPayload = values.metas.map((meta, index) => {
      const baseMeta = {
        attribute_scope: meta.attribute_scope,
        attribute_type: meta.attribute_type,
        attribute_key: meta.attribute_key,
        is_content: meta.is_content,
      };

      if (meta.is_content) {
        return {
          ...baseMeta,
          content: meta.content,
        };
      } else {
        const file = meta.content?.image?.[0];
        if (file) {
          formData.append(`files[${index}]`, file);
        }
        return {
          ...baseMeta,
          content: "", // will be handled from files[]
        };
      }
    });

    formData.append("metas", JSON.stringify(metasPayload));
    // metaMutation.mutate(formData);
  };

  return (
    <div className="space-y-6 border-t pt-4">
      <div className="flex justify-end">
        <Button
          type="button"
          onClick={() => {
            append({
              attribute_scope: "general",
              attribute_type: "name",
              attribute_key: "",
              content: "",
              is_content: true,
            });
            setUploadedFiles((prev) => [...prev, { image: [] }]);
          }}
        >
          + Add Meta
        </Button>
      </div>

      {fields.map((field, index) => {
        const toggleName = `metas.${index}.is_content`;
        const contentName = `metas.${index}.content`;
        const isTextMode = metas?.[index]?.is_content ?? true;
        const contentValue = metas?.[index]?.content;

        return (
          <div
            key={field.id}
            className="grid grid-cols-1 md:grid-cols-4 gap-6 border-b pb-4"
          >
            {/* Scope */}
            <Controller
              name={`metas.${index}.attribute_scope`}
              control={control}
              render={({ field }) => (
                <MultiSelect
                  {...field}
                  label="Scope"
                  options={[
                    { label: "General", value: "general" },
                    { label: "Open Graph", value: "og" },
                    { label: "Twitter", value: "twitter" },
                  ]}
                  errors={errors}
                />
              )}
            />

            {/* Type */}
            <Controller
              name={`metas.${index}.attribute_type`}
              control={control}
              render={({ field }) => (
                <MultiSelect
                  {...field}
                  label="Type"
                  options={[
                    { label: "name", value: "name" },
                    { label: "property", value: "property" },
                    { label: "http-equiv", value: "http-equiv" },
                  ]}
                  isMulti={false}
                  disabled
                  errors={errors}
                />
              )}
            />

            {/* Key */}
            <Controller
              name={`metas.${index}.attribute_key`}
              control={control}
              render={({ field }) => (
                <CustomInput
                  {...field}
                  label="Meta Key"
                  placeholder="e.g. og:title"
                  errors={errors}
                  required
                />
              )}
            />

            {/* Content */}
            {isTextMode ? (
              <CustomInput
                name={contentName}
                value={contentValue}
                label="Meta Content"
                onChange={(e) => setValue(contentName, e.target.value)}
                placeholder="e.g. iPhone 15"
                errors={errors}
                required
                labelComponent={
                  <CustomToggle
                    options={[{ name: toggleName, label: "Text Mode" }]}
                    control={control}
                    errors={errors}
                    showTooltip
                    showLabel={false}
                  />
                }
              />
            ) : (
              <CustomDropZone
                name={contentName}
                label="Meta Content"
                number_of_images={1}
                fileType="image"
                image_size={1024 * 1024 * 2}
                uploadedFiles={uploadedFiles[index]}
                setUploadedFiles={(fileObj) => {
                  setUploadedFiles((prev) => {
                    const updated = [...prev];
                    updated[index] = fileObj;
                    return updated;
                  });
                }}
                showIcon={false}
                errors={errors}
                required
                labelComponent={
                  <CustomToggle
                    options={[{ name: toggleName, label: "File Mode" }]}
                    control={control}
                    errors={errors}
                    showTooltip
                    showLabel={false}
                  />
                }
              />
            )}

            {/* Remove */}
            <div className="md:col-span-4 flex justify-end">
              <Button
                type="button"
                onClick={() => {
                  remove(index);
                  setUploadedFiles((prev) =>
                    prev.filter((_, i) => i !== index)
                  );
                }}
                className="bg-red-600"
              >
                Remove
              </Button>
            </div>
          </div>
        );
      })}

      {/* Save + Reset */}
      <div className="flex justify-end gap-4 pt-4">
        <Button type="reset" onClick={() => reset()} className="bg-red-600">
          Reset
        </Button>
        <Button type="button" variant="dark" onClick={handleSubmitMeta}>
          Save Meta Tags
        </Button>
      </div>
    </div>
  );
};

export default MetaFields;
