"use client";

import { useEffect, useState } from "react";

import Button from "../../../../ui/Button";
import Input from "../../../../ui/CustomInput";
import { useAppForm } from "../../../../../hooks/useAppForm";
import {
  SocialMediaSettingsFormValues,
  socialMediaSettingsSchema,
} from "../../../../../hooks/features/admin/settings/social/schema";
import useFetchSocialMediaSettings from "../../../../../hooks/features/admin/settings/social/useFetchSocialMediaSettings";
import useUpdateSocialMediaSettings from "../../../../../hooks/features/admin/settings/social/useUpdateSocialMediaSettings";
import SomethingWentWrong from "../../../../SomethingWentWrong";

interface SocialPlatform {
  id: keyof SocialMediaSettingsFormValues;
  label: string;
  placeholder: string;
  enabled: boolean;
}

export default function SocialMediaSettings() {
  const {
    socialMediaSettings,
    loading: fetchingSocialMediaSettings,
    isError,
  } = useFetchSocialMediaSettings();
  const { updateSocialMediaSettings, updatingSocialMediaSettings } =
    useUpdateSocialMediaSettings();

  const [platforms, setPlatforms] = useState<SocialPlatform[]>([
    {
      id: "facebook",
      label: "Facebook",
      placeholder: "https://facebook.com/...",
      enabled: true,
    },
    {
      id: "instagram",
      label: "Instagram",
      placeholder: "https://instagram.com/...",
      enabled: true,
    },
    {
      id: "twitter",
      label: "Twitter (X)",
      placeholder: "https://x.com/...",
      enabled: true,
    },
    {
      id: "linkedIn",
      label: "LinkedIn",
      placeholder: "https://linkedin.com/in/...",
      enabled: true,
    },
    {
      id: "youtube",
      label: "YouTube",
      placeholder: "https://youtube.com/...",
      enabled: true,
    },
    {
      id: "customLink",
      label: "Custom Link",
      placeholder: "https://...",
      enabled: true,
    },
  ]);

  const { register, errors, handleSubmit, setValue, clearErrors } =
    useAppForm<SocialMediaSettingsFormValues>({
      defaultValues: {
        facebook: "",
        instagram: "",
        twitter: "",
        linkedIn: "",
        youtube: "",
        customLink: "",
      },
      schema: socialMediaSettingsSchema,
      onSubmit: async (data) => {
        try {
          await updateSocialMediaSettings(data);
        } catch (error) {}
      },
    });

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

    setValue("facebook", socialMediaSettings.facebook);
    setValue("instagram", socialMediaSettings.instagram);
    setValue("twitter", socialMediaSettings.twitter);
    setValue("linkedIn", socialMediaSettings.linkedIn);
    setValue("youtube", socialMediaSettings.youtube);
    setValue("customLink", socialMediaSettings.customLink);
  }, [socialMediaSettings, setValue]);

  const handleToggle = (id: keyof SocialMediaSettingsFormValues) => {
    setPlatforms((prev) =>
      prev.map((item) => {
        if (item.id === id) {
          const nextEnabled = !item.enabled;
          if (!nextEnabled) {
            setValue(id, "");
            clearErrors(id);
          }
          return { ...item, enabled: nextEnabled };
        }
        return item;
      }),
    );
  };

  if (fetchingSocialMediaSettings) {
    return <SocialMediaSettingsSkeleton />;
  }

  if (isError) {
    return (
      <SomethingWentWrong
        variant="section"
        title="Unable to load social media 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">
        {/* 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">
            Social Media Management
          </h2>

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

        {/* Social Links */}
        <div className="space-y-3 2xl:space-y-5">
          {platforms.map((platform) => (
            <div key={platform.id} className="flex items-end gap-4">
              <div className="flex-1">
                <Input
                  label={platform.label}
                  placeholder={platform.placeholder}
                  register={register(platform.id)}
                  error={errors[platform.id]?.message}
                  disabled={!platform.enabled}
                  className="disabled:bg-gray-50 disabled:text-gray-400 disabled:cursor-not-allowed"
                />
              </div>

              {/* <div className="pb-3">
                <Toggle
                  checked={platform.enabled}
                  onChange={() => handleToggle(platform.id)}
                  size="md"
                />
              </div> */}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function SocialMediaSettingsSkeleton() {
  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-56 rounded bg-gray-200" />
          <div className="h-12 w-28 rounded-xl bg-gray-200" />
        </div>

        <div className="space-y-3 2xl:space-y-5">
          {[...Array(3)].map((_, index) => (
            <div key={index} className="h-14 w-full rounded-xl bg-gray-200" />
          ))}
        </div>
      </div>
    </div>
  );
}
