"use client";

import { useEffect, useState } from "react";
import { FiEye, FiEyeOff } from "react-icons/fi";

import Button from "../../../../ui/Button";
import Input from "../../../../ui/CustomInput";
import Toggle from "../../../../ui/Toggle";
import { useAppForm } from "../../../../../hooks/useAppForm";
import {
  SightEngineSettingsFormValues,
  sightEngineSettingsSchema,
} from "../../../../../hooks/features/admin/settings/sightEngine/schema";
import useFetchSightEngineSettings from "../../../../../hooks/features/admin/settings/sightEngine/useFetchSightEngineSettings";
import useUpdateSightEngineSettings from "../../../../../hooks/features/admin/settings/sightEngine/useUpdateSightEngineSettings";
import SomethingWentWrong from "../../../../SomethingWentWrong";

export default function SightEngineSettings() {
  const [showSecret, setShowSecret] = useState(false);

  const {
    sightEngineSettings,
    loading: fetchingSightEngineSettings,
    isError,
  } = useFetchSightEngineSettings();
  const { updateSightEngineSettings, updatingSightEngineSettings } =
    useUpdateSightEngineSettings();

  const { register, errors, handleSubmit, control, setValue } =
    useAppForm<SightEngineSettingsFormValues>({
      defaultValues: {
        apiSecret: "",
        apiUser: "",
        imageDetection: false,
      },
      schema: sightEngineSettingsSchema,
      onSubmit: async (data) => {
        try {
          await updateSightEngineSettings(data);
        } catch (error) {}
      },
    });

  useEffect(() => {
    if (!sightEngineSettings) return;

    setValue("apiUser", sightEngineSettings.apiUser);
    setValue("apiSecret", sightEngineSettings.apiSecret);
    setValue("imageDetection", sightEngineSettings.imageDetection);
  }, [sightEngineSettings, setValue]);

  if (fetchingSightEngineSettings) {
    return <SightEngineSettingsSkeleton />;
  }

  if (isError) {
    return (
      <SomethingWentWrong
        variant="section"
        title="Unable to load Sight Engine settings"
        description="This settings section failed to load, but other settings remain available."
        onRetry={() => window.location.reload()}
        buttonText=""
      />
    );
  }

  return (
    <div>
      <div className="glass-card-v2 rounded-xl p-4 xl:p-6">
        <div className="mb-6 flex items-center gap-4 justify-between">
          <h2 className="font-body text-base xl:text-lg 2xl:text-xl font-semibold text-table-text">
            Sight Engine Settings
          </h2>

          <Button
            variant="white"
            onClick={handleSubmit}
            BtnInnerclassName="text-link! px-4.5!"
            buttonClassName="shadow-none!"
            loading={updatingSightEngineSettings}
          >
            Save
          </Button>
        </div>

        <div className="grid gap-x-4 gap-y-3 2xl:gap-5 md:grid-cols-2">
          <Input
            label="API User"
            placeholder="Enter API User"
            register={register("apiUser")}
            error={errors?.apiUser?.message}
          />

          <Input
            label="API Secret"
            type={showSecret ? "text" : "password"}
            placeholder="Enter API Secret"
            register={register("apiSecret")}
            error={errors?.apiSecret?.message}
            rightIcon={
              showSecret ? (
                <FiEyeOff
                  onClick={() => setShowSecret(false)}
                  className="cursor-pointer text-lg text-gray-500"
                />
              ) : (
                <FiEye
                  onClick={() => setShowSecret(true)}
                  className="cursor-pointer text-lg text-gray-500"
                />
              )
            }
          />
        </div>

        <div className="mt-8 flex items-center justify-between rounded-xl border border-[#E5DFFF] p-4">
          <div>
            <h3 className="font-medium text-heading">AI Image Detection</h3>
            <p className="mt-1 text-sm text-gray-500">
              Enable AI-generated image detection using Sight Engine.
            </p>
          </div>

          <Toggle
            name="imageDetection"
            control={control}
            error={errors?.imageDetection?.message}
          />
        </div>
      </div>
    </div>
  );
}

function SightEngineSettingsSkeleton() {
  return (
    <div className="animate-pulse">
      <div className="glass-card-v2 rounded-xl p-4 xl:p-6">
        <div className="mb-6 flex items-center justify-between gap-4">
          <div className="h-7 w-48 rounded bg-gray-200" />
          <div className="h-12 w-28 rounded-xl bg-gray-200" />
        </div>

        <div className="grid gap-x-4 gap-y-3 2xl:gap-5 md:grid-cols-2">
          <div>
            <div className="mb-2 h-5 w-32 rounded bg-gray-200" />
            <div className="h-12 w-full rounded-xl bg-gray-200" />
          </div>

          <div>
            <div className="mb-2 h-5 w-24 rounded bg-gray-200" />
            <div className="h-12 w-full rounded-xl bg-gray-200" />
          </div>
        </div>

        <div className="mt-8 h-20 rounded-xl border border-[#E5DFFF] bg-gray-100" />
      </div>
    </div>
  );
}
