"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 { useAppForm } from "../../../../../hooks/useAppForm";
import {
  PaymentSettingsFormValues,
  paymentSettingsSchema,
} from "../../../../../hooks/features/admin/settings/payment/schema";
import useFetchPaymentSettings from "../../../../../hooks/features/admin/settings/payment/useFetchPaymentSettings";
import useUpdatePaymentSettings from "../../../../../hooks/features/admin/settings/payment/useUpdatePaymentSettings";
import SomethingWentWrong from "../../../../SomethingWentWrong";

export default function PaymentSettings() {
  const [showPublishableKey, setShowPublishableKey] = useState(false);
  const [showSecretKey, setShowSecretKey] = useState(false);
  const [showWebhookSecret, setShowWebhookSecret] = useState(false);
  const {
    paymentSettings,
    loading: fetchingPaymentSettings,
    isError,
    error,
  } = useFetchPaymentSettings();

  const { updatePaymentSettings, updatingPaymentSettings } =
    useUpdatePaymentSettings();

  const { register, errors, reset, handleSubmit, setValue } =
    useAppForm<PaymentSettingsFormValues>({
      defaultValues: {
        stripePublishableKey: "",
        stripeSecretKey: "",
        stripeWebhookSecret: "",
      },
      schema: paymentSettingsSchema,
      onSubmit: async (data) => {
        try {
          await updatePaymentSettings(data);
        } catch (error) {}
      },
    });

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

    setValue("stripePublishableKey", paymentSettings.stripePublishableKey);
    setValue("stripeSecretKey", paymentSettings.stripeSecretKey);
    setValue("stripeWebhookSecret", paymentSettings.stripeWebhookSecret);
  }, [paymentSettings]);

  if (fetchingPaymentSettings) {
    return <PaymentSettingsSkeleton />;
  }

  if (isError) {
    return (
      <SomethingWentWrong
        variant="section"
        title="Unable to load payment 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">
            Payment Settings
          </h2>

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

        <div className="grid gap-x-4 gap-y-3 2xl:gap-5 md:grid-cols-2">
          <Input
            label="Publishable Key"
            type={showPublishableKey ? "text" : "password"}
            placeholder="pk_test_51Nxxxxxxxxxxxxxxxx"
            rightIcon={
              showPublishableKey ? (
                <FiEyeOff
                  onClick={() => setShowPublishableKey(!showPublishableKey)}
                  className="text-lg text-gray-500"
                />
              ) : (
                <FiEye
                  onClick={() => setShowPublishableKey(!showPublishableKey)}
                  className="text-lg text-gray-500"
                />
              )
            }
            register={register("stripePublishableKey")}
            error={errors.stripePublishableKey?.message}
          />

          <Input
            label="Secret Key"
            type={showSecretKey ? "text" : "password"}
            register={register("stripeSecretKey")}
            error={errors?.stripeSecretKey?.message}
            placeholder="sk_test_51Nxxxxxxxxxxxxxxxx"
            rightIcon={
              showSecretKey ? (
                <FiEyeOff
                  onClick={() => setShowSecretKey(!showSecretKey)}
                  className="text-lg text-gray-500"
                />
              ) : (
                <FiEye
                  onClick={() => setShowSecretKey(!showSecretKey)}
                  className="text-lg text-gray-500"
                />
              )
            }
          />

          <Input
            label="Webhook Secret"
            type={showWebhookSecret ? "text" : "password"}
            register={register("stripeWebhookSecret")}
            error={errors?.stripeWebhookSecret?.message}
            placeholder="whsec_51Nxxxxxxxxxxxxxxxx"
            rightIcon={
              showWebhookSecret ? (
                <FiEyeOff
                  onClick={() => setShowWebhookSecret(!showWebhookSecret)}
                  className="text-lg text-gray-500"
                />
              ) : (
                <FiEye
                  onClick={() => setShowWebhookSecret(!showWebhookSecret)}
                  className="text-lg text-gray-500"
                />
              )
            }
          />
        </div>
      </div>
    </div>
  );
}

function PaymentSettingsSkeleton() {
  return (
    <div className="animate-pulse">
      <div className="glass-card-v2 rounded-xl p-4 xl:p-6">
        {/* Header */}
        <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>

        {/* Form Fields */}
        <div className="grid gap-x-4 gap-y-3 2xl:gap-5 md:grid-cols-2">
          {/* Publishable Key */}
          <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>

          {/* Secret Key */}
          <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>

          {/* Webhook Secret */}
          <div className="md:col-span-2">
            <div className="mb-2 h-5 w-36 rounded bg-gray-200" />
            <div className="h-12 w-full rounded-xl bg-gray-200" />
          </div>
        </div>
      </div>
    </div>
  );
}
