import React, { useEffect, useState } from 'react';
import { buildStyles, CircularProgressbar } from 'react-circular-progressbar';
import { FiLoader } from 'react-icons/fi';
import { Link } from 'react-router-dom';
import {
  FaCheckCircle,
  FaChevronRight,
  FaPlay,
  FaRegCircle,
} from 'react-icons/fa';

import { useAppStateContext } from '../context/user.data.context';
import RecomazeLogo from '../components/svg/RecomazeLogo';
import Button from '../components/widgets/Button';
import { getLocalStorageValue, setLocalStorageValue } from '../utils';
import { recomaze_ai_personalization_env } from '../env';

const Onboarding = (): JSX.Element => {
  const { user, fetchUser } = useAppStateContext();
  const [selectedTab, setSelectedtab] = useState<number>(0);
  const [isError, setIsError] = useState<string | null>(null);
  const [isSuccess, setIsSuccess] = useState<string | null>(null);

  const [showSuccessPage, setShowSuccessPage] = useState<boolean>(false);

  useEffect(() => {
    const rating = getLocalStorageValue('rating-popup');
    if (!rating) setLocalStorageValue('rating-popup', 'init');

    if (!user) fetchUser();
  }, [user]);

  useEffect(() => {
    if (isError || isSuccess) {
      const timer: NodeJS.Timeout = setTimeout(() => {
        setIsError(null);
        setIsSuccess(null);
      }, 4000);

      return () => clearTimeout(timer);
    }
  }, [isError, isSuccess]);

  return (
    <div className="relative w-full md:w-3/4 mx-auto py-8 space-y-4 p-4">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
        <div className="space-y-2">
          <div className="flex items-center space-x-2">
            <RecomazeLogo className="w-5 h-6" />
            <p className="font-bold text-lg">Get started with Recomaze AI</p>
          </div>
          <p className="text-xs font-normal text-gray-400">
            Recomaze helps you convert more by showing the right product
            suggestions and answers automatically.
          </p>
        </div>
        <div className="w-full flex justify-end">
          <Link
            target="_blank"
            to="https://www.youtube.com/watch?v=Oa96HzWB89k"
            className="flex md:justify-end w-full bg-white"
          >
            <div className="w-36 relative">
              <div className="absolute h-full top-[20%] left-[30%] z-[999]">
                <div className="border border-white p-2 rounded-full flex justify-center items-center">
                  <FaPlay className="text-white text-base" />
                </div>
              </div>
              <div className="bg-black/40 absolute w-full h-full rounded-md"></div>
              <div className="w-full">
                <img
                  src={
                    recomaze_ai_personalization_env?.recomaze_cdn +
                    'public/theme.png'
                  }
                  alt="theme"
                  className="w-full h-full rounded-lg object-contain"
                />
              </div>
            </div>
          </Link>
        </div>
      </div>
      <div className="space-y-4">
        <div className="bg-white p-4 rounded-md">
          {/* Common Header */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="flex flex-col space-y-2">
              <p className="font-semibold text-base">
                {showSuccessPage
                  ? 'Onboarding Process has been completed'
                  : 'Complete these basic important steps'}
              </p>

              <p className="text-gray-300 text-xs font-normal">
                Basic yet important steps to start using Recomaze and raise your
                conversion rate
              </p>

              {showSuccessPage ? (
                <div className="pt-4">
                  <Link to="/agent-analytics">
                    <Button
                      variant="primary"
                      onClick={() => {
                        const rating = getLocalStorageValue('rating-popup');
                        if (!rating || rating === 'init') {
                          setLocalStorageValue('rating-popup', 'pending');
                        }
                      }}
                    >
                      Go to Agent Analytics
                    </Button>
                  </Link>
                </div>
              ) : null}
            </div>
            {showSuccessPage ? (
              <div className="flex space-x-2 justify-end items-center w-full">
                <span className="text-success font-bold text-xs">
                  Onboarding Complete
                </span>
                <div className="border-4 border-success rounded-full p-[2px] text-xl text-success">
                  <FaCheckCircle />
                </div>
              </div>
            ) : (
              <div className="flex space-x-2 justify-end items-center w-full">
                <span className="text-danger font-bold text-xs">
                  {user?.step && user?.step >= 2 ? 2 : user?.step} of 2 steps
                  completed
                </span>
                <div className="max-w-10">
                  <CircularProgressbar
                    value={(user?.step || 1) * 50}
                    minValue={1}
                    maxValue={100}
                    strokeWidth={15}
                    styles={buildStyles({ pathColor: '#ff1d64' })}
                    className="h-8 w-8"
                  />
                </div>
              </div>
            )}
          </div>

          {/* Steps */}
          {!showSuccessPage ? (
            <div className="pt-5 space-y-4">
              {OnboardingSteps({
                domainName: recomaze_ai_personalization_env?.domain || '',
              })?.map((onboarding, key) => {
                return (
                  <div
                    onClick={() =>
                      setSelectedtab(tab => {
                        if (tab === key) return -1;

                        return key;
                      })
                    }
                    key={key}
                    className={`space-y-2 cursor-pointer p-2 rounded-md ${
                      selectedTab === key ? 'bg-[#f7f7f7]' : ''
                    }`}
                  >
                    <div className="flex items-center space-x-2">
                      {!user ? (
                        <FiLoader className="text-sm animate-spin" />
                      ) : (user?.step || 0) >= onboarding.step ? (
                        <FaCheckCircle className="text-danger text-sm" />
                      ) : (
                        <FaRegCircle className="text-zinc-300" />
                      )}
                      <p className="font-semibold text-base">
                        {onboarding.title}
                      </p>
                    </div>
                    {selectedTab === key ? (
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full">
                        <div className="flex flex-col justify-between">
                          <div className="space-y-4">
                            <p className="text-gray-400 font-normal text-xs">
                              {onboarding.sub_title}
                            </p>
                            {onboarding.cta_label ? (
                              <p className="text-gray-400 font-semibold text-xs">
                                {onboarding.cta_label}
                              </p>
                            ) : null}
                          </div>

                          <div
                            onClick={() => {
                              if (
                                onboarding.step === 3 &&
                                user?.step &&
                                user?.step >= 2
                              ) {
                                setShowSuccessPage(true);
                              }
                            }}
                            className=""
                          >
                            {onboarding.action}
                          </div>
                        </div>
                        {onboarding.video_link ? (
                          <div className="flex md:justify-end relative">
                            {onboarding.video_link}
                          </div>
                        ) : null}
                      </div>
                    ) : null}
                  </div>
                );
              })}
            </div>
          ) : null}
        </div>
      </div>
    </div>
  );
};

export default Onboarding;

const OnboardingSteps = ({ domainName }: { domainName: string }) => [
  {
    title: 'Customize Recomaze on YourStore',
    step: 2,
    sub_title:
      'Match the look of your brand in 2 minutes. Add your logo, colors, and CTA styles.',
    video_link: (
      <div className="max-w-40 max-h-24 relative">
        <Link
          to="https://www.youtube.com/watch?v=4LJEj6AqV7k"
          className="relative"
        >
          <a
            href="https://www.youtube.com/watch?v=4LJEj6AqV7k"
            target="_blank"
            rel="noopener noreferrer"
          >
            <div className="absolute h-full top-[30%] left-[40%] z-[999]">
              <div className="border border-white p-2 rounded-full flex justify-center items-center">
                <FaPlay className="text-white text-2xl" />
              </div>
            </div>
            <div className="bg-black/40 absolute w-full h-full rounded-md"></div>
            <div className="w-40">
              <img
                src={
                  recomaze_ai_personalization_env?.recomaze_cdn +
                  'public/customization.png'
                }
                alt="customization"
                className="w-full h-full rounded-lg object-contain"
              />
            </div>
          </a>
        </Link>
      </div>
    ),
    cta_label: 'Stores that customize see 12% higher AOV.',
    action: (
      <div className="max-w-20 pt-10">
        <Link to="/home">
          <Button className="bg-black px-4 py-2 rounded-md text-white">
            Customize
          </Button>
        </Link>
      </div>
    ),
  },
  {
    title: 'Preview Recomaze in Action',
    sub_title: 'See it live like your shoppers do',
    video_link: null,
    step: 3,
    action: (
      <Link
        to={`https://${domainName}`}
        className=" flex items-center space-x-2"
      >
        <a
          href={`https://${domainName}`}
          target="_blank"
          rel="noopener noreferrer"
          className="pt-10 flex items-center space-x-2"
        >
          <span className="text-danger font-bold text-xs">
            View My Store with Recomaze
          </span>
          <FaChevronRight className="text-[#B0B0B0]" />
        </a>
      </Link>
    ),
  },
];
