"use client";

import Button from "../../../../ui/Button";
import Input from "../../../../ui/CustomInput";
import CustomPhoneInput from "../../../../ui/CustomPhoneInput";
import LogoUploader from "../../../../ui/LogoUploader";
import { useEffect, useState } from "react";
import Select from "../../../../ui/CustomSelect";
import { useAppForm } from "../../../../../hooks/useAppForm";
import {
  PlatformSettingsFormValues,
  platformSettingsSchema,
} from "../../../../../hooks/features/admin/settings/platform/schema";
import usePlatformSettingsUpdate from "../../../../../hooks/features/admin/settings/platform/usePlatformSettingsUpdate";
import useFetchPlatformSettings from "../../../../../hooks/features/admin/settings/platform/useFetchPlatformSettings";
import ClientWrapper from "../../../../ClientWrapper";
import useUpdatePlatformLogo from "../../../../../hooks/features/admin/settings/platform/useUpdatePlatformLogo";
import { getImagePath } from "../../../../../utils/helper";
import SomethingWentWrong from "../../../../SomethingWentWrong";

const currencyOptions = [{ label: "USD ($)", value: "USD" }];

export default function PlatformSettings() {
  const [logo, setLogo] = useState<string | null>(null);

  const {
    platformSettings,
    loading: fetchingPlatformSettings,
    error,
  } = useFetchPlatformSettings();
  const { updatePlatformSettings, loading: updateLoading } =
    usePlatformSettingsUpdate();

  const { updatePlatformLogo, isUpdatingPlatformLogo } =
    useUpdatePlatformLogo();

  const { register, control, reset, handleSubmit, errors, getValue } =
    useAppForm<PlatformSettingsFormValues>({
      defaultValues: {
        appName: "",
        mobileNumber: {
          dialCode: "",
          number: "",
        },
        email: "",
        currency: "USD",
      },
      schema: platformSettingsSchema,
      onSubmit: async (data) => {
        try {
          await updatePlatformSettings(data);
        } catch (error) {
          console.error("ERROR: ", error);
        }
      },
    });

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

    reset({
      appName: platformSettings.appName ?? "",
      email: platformSettings.email ?? "",
      currency: platformSettings.currency ?? "USD",
      mobileNumber: {
        dialCode: platformSettings.dialCode,
        number: platformSettings.phone,
      },
    });

    setLogo(getImagePath(platformSettings.logo) ?? null);
  }, [platformSettings]);

  const handleLogoUpload = async (file, preview) => {
    try {
      const formData = new FormData();
      formData.append("logo", file);
      setLogo(preview);
      await updatePlatformLogo(formData);
    } catch (error) {
      setLogo(null);
    }
  };

  if (fetchingPlatformSettings) {
    return <PlatformSettingsSkeleton />;
  }

  if (error) {
    return (
      <SomethingWentWrong
        variant="section"
        title="Unable to load platform settings"
        description="This settings section failed to load, but the rest of the admin settings area is still available."
        onRetry={() => window.location.reload()}
        buttonText=""
      />
    );
  }

  return (
    <ClientWrapper fallback={<PlatformSettingsSkeleton />}>
      <div className="w-full">
        <div className="glass-card-v2 rounded-xl p-4 xl:p-6">
          {/* Header */}
          <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">
              Platform Settings
            </h2>

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

          <div className="space-y-6">
            {/* Logo Upload */}
            <LogoUploader value={logo} onChange={handleLogoUpload} />

            {/* Form Fields */}
            <div className="grid gap-x-4 gap-y-3 2xl:gap-5 md:grid-cols-2">
              <Input
                label="Platform Name"
                placeholder="Enter Platform Name"
                register={register("appName")}
                error={errors?.appName?.message}
              />

              <CustomPhoneInput
                label="Phone Number"
                name="mobileNumber"
                control={control}
                placeholder="Enter Phone Number"
                error={errors?.mobileNumber?.number?.message}
              />

              <Input
                label="Email Address"
                type="email"
                placeholder="Enter Email Address"
                className="md:col-span-2"
                register={register("email")}
                error={errors?.email?.message}
              />
              <Select<PlatformSettingsFormValues>
                label="Currency"
                name="currency"
                control={control}
                placeholder="Select Currency"
                options={currencyOptions}
                error={errors?.currency?.message}
              />
            </div>
          </div>
        </div>
      </div>
    </ClientWrapper>
  );
}

function PlatformSettingsSkeleton() {
  return (
    <div className="animate-pulse w-full">
      <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>

        <div className="space-y-6">
          {/* Logo Upload */}
          <div className="flex flex-col gap-4 sm:flex-row sm:items-center">
            <div className="h-24 w-24 rounded-full border-2 border-gray-200 bg-gray-200" />

            <div className="flex-1">
              <div className="mb-3 h-5 w-36 rounded bg-gray-200" />
              <div className="mb-2 h-4 w-64 rounded bg-gray-200" />
              <div className="h-11 w-36 rounded-xl bg-gray-200" />
            </div>
          </div>

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

            {/* Phone Number */}
            <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>

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

            {/* Currency */}
            <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>
      </div>
    </div>
  );
}
