"use client";

import SiteBreadcrumb from "@/components/site-breadcrumb";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useRouter } from "@/i18n/routing";
import {
  getFbTokenValid,
  getYtTokenValid,
  saveFbToken,
  saveYtToken,
} from "@/service/social-media/social-media";
import { Icon } from "@iconify/react/dist/iconify.js";
import { useEffect, useState } from "react";
import FacebookLogin, {
  ReactFacebookLoginInfo,
  ReactFacebookFailureResponse
} from "react-facebook-login";

const SocialMediaPage = () => {
  const router = useRouter();

  const [isFacebookLogin, setIsFacebookLogin] = useState<boolean>(false);
  const [isGoogleLogin, setIsGoogleLogin] = useState<boolean>(false);
  const [, setData] = useState<any>({});

const responseFacebook = (
  response: ReactFacebookLoginInfo | ReactFacebookFailureResponse
) => {
  if ('accessToken' in response && response.accessToken) {
    sendFbToken(response.accessToken);
    setIsFacebookLogin(true);
  } else {
    setIsFacebookLogin(false);
  }
};

  const clientId =
    "515231445138-5ius52rjsqucc6petfpv1d42v1lj778o.apps.googleusercontent.com";
  const feedbackUrl = "https://mediahub.polri.go.id/admin/settings/socmed";

  async function sendFbToken(token: string) {
    const res = await saveFbToken(token);
    if (!res?.error) {
      setIsFacebookLogin(true);
    }
  }

  async function sendYtToken(code: string | string[]) {
    const res = await saveYtToken(code);
    if (!res?.error) {
      setIsGoogleLogin(true);
    }
  }

  useEffect(() => {
    async function checkTokens() {
      try {
        const [fbRes, ytRes] = await Promise.all([
          getFbTokenValid(),
          getYtTokenValid(),
        ]);
        setIsFacebookLogin(!fbRes?.error && fbRes.data?.data?.isValid);
        setIsGoogleLogin(!ytRes?.error && ytRes.data?.data?.isValid);
      } catch (error) {
        console.error("Error checking tokens:", error);
      }
    }
    checkTokens();
  }, []);

  // Jika mau handle redirect code YouTube OAuth
  // useEffect(() => {
  //   const { code } = router.query;
  //   if (code !== undefined) {
  //     sendYtToken(code);
  //   }
  // }, [router.query]);

  return (
    <div className="space-y-4">
      <SiteBreadcrumb />
      <div className="bg-white rounded-md p-4 shadow-lg border">
        <h2 className="text-lg font-semibold">Social Media</h2>
      </div>

      <div className="w-full space-y-4">
        <Card>
          <CardHeader>
            <CardTitle>Koneksi Social Media</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {/* Facebook */}
              <div className="text-center space-y-2">
                {isFacebookLogin ? (
                  <>
                    <Button
                      variant="default"
                      className="w-full flex items-center justify-center gap-2 bg-[#1877F2] hover:bg-[#166fe0]"
                    >
                      <Icon icon="logos:facebook" className="text-xl" />
                      Facebook
                    </Button>
                    <p
                      className={`${
                        isFacebookLogin ? "text-green-600" : "text-gray-500"
                      }`}
                    >
                      {isFacebookLogin ? "Terhubung" : "Tidak Terhubung"}
                    </p>
                  </>
                ) : (
                  <>
                    <FacebookLogin
                      appId="1290603775136204"
                      autoLoad
                      fields="name,email,picture"
                      scope="public_profile,user_friends,pages_manage_posts,pages_manage_metadata,pages_event,pages_read_engagement,pages_manage_engagement,pages_read_user_content,instagram_basic,instagram_content_publish,instagram_manage_messages,instagram_manage_comments"
                      callback={responseFacebook}
                      icon="fa-facebook"
                      cssClass="w-full flex items-center justify-center gap-2 bg-[#1877F2] hover:bg-[#166fe0] text-white rounded-md py-2"
                      textButton=" Facebook"
                    />
                    <p className="text-gray-500">Tidak Terhubung</p>
                  </>
                )}
              </div>

              {/* Google / YouTube */}
              <div className="text-center space-y-2">
                <a
                  href={`https://accounts.google.com/o/oauth2/v2/auth?scope=https://www.googleapis.com/auth/youtube.force-ssl&access_type=offline&include_granted_scopes=true&response_type=code&state=state_parameter_passthrough_value&redirect_uri=${feedbackUrl}&client_id=${clientId}`}
                  className="w-full inline-flex items-center justify-center gap-2 bg-red-600 hover:bg-red-700 text-white rounded-md py-2"
                >
                  <Icon icon="bi:google" className="text-xl" />
                  Google
                </a>
                <p
                  className={`${
                    isGoogleLogin ? "text-green-600" : "text-gray-500"
                  }`}
                >
                  {isGoogleLogin ? "Terhubung" : "Tidak Terhubung"}
                </p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
};

export default SocialMediaPage;
