import { useState } from 'react';
import { Head, usePage } from '@inertiajs/react';
import type { ReactElement } from 'react';
import axios from 'axios';
import TeacherLayoutWithProviders from '@/Layouts/TeacherLayout';
import FadePresence from '@/Components/Transition/FadePresence';
import CloseIconButton from '@/Components/CloseIconButton';
import DotLoader from '@/Components/ui/dotloader';
import BackArrowIcon from '@/assets/icons/BackArrowIcon';
import { useNavigationContext } from '@/Contexts/NavigationContext';
import type { PageProps } from '@/types';

// Keeps the deleting state on screen long enough to read, even though a roster
// delete is a handful of set-based queries and usually returns in milliseconds.
const MINIMUM_DELETING_MS = 3000;

const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

export default function DeleteAll() {
  const { props } = usePage<PageProps<{ total_students?: number; [key: string]: unknown }>>();
  const totalStudents = props.total_students ?? 0;

  const { navigate } = useNavigationContext();

  // Only the footer swaps between steps, so this key drives the footer's
  // FadePresence wrappers and nothing above them.
  const [footerStep, setFooterStep] = useState<'default' | 'confirm' | 'deleting' | 'retry'>(
    'default'
  );

  const handleBack = () => {
    setFooterStep('default');
  };

  const handleClose = () => {
    navigate('/students', {
      scope: ['subContent'],
      duration: 400,
    });
  };

  const handleConfirmDelete = async () => {
    if (footerStep === 'deleting') return;

    setFooterStep('deleting');

    // The request and the minimum on-screen time run together, so a fast
    // delete still shows the deleting state for MINIMUM_DELETING_MS while a
    // slow one holds it until the server is actually finished.
    const [succeeded] = await Promise.all([
      axios
        .delete(route('owner.students.roster.destroy'), { data: { confirm: true } })
        .then(() => true)
        .catch(() => false),
      delay(MINIMUM_DELETING_MS),
    ]);

    if (!succeeded) {
      setFooterStep('retry');

      return;
    }

    navigate('/students/splash', {
      scope: ['subContent'],
      duration: 400,
    });
  };

  return (
    <>
      <Head title="Teacher - Student Roster" />

      <FadePresence
        transitionKey="default"
        duration={400}
        className="relative flex h-full w-full flex-col"
      >
        <div className="flex h-full flex-col">
          <div className="flex flex-1 flex-col">
            <div className="mb-[8px] flex items-center justify-between p-0">
              <h1 className="flex translate-y-[-1px] items-center font-readingful text-[2.4rem] font-bold leading-none text-[#6F8AE2]">
                Student Roster
              </h1>
              <CloseIconButton onClick={handleClose} />
            </div>
            <p className="mb-[11px] font-readingful text-[2.0rem] font-bold text-[#B7C7F7]">
              Delete all user accounts.
            </p>
            <p className="mb-auto max-w-[600px] font-readmore text-[1.6rem] leading-tight text-[#576082]">
              There are currently a total of{' '}
              <span className="font-readingful">{totalStudents}</span> student account
              {totalStudents === 1 ? '' : 's'} associated with your use <br />
              of Readingful. They may be deleted singularly from within their individual <br />
              student account profiles. However, if you have no additional use for this <br />
              student roster, as a whole, you can delete it in its entirety, along with all <br />
              correlated user data, by clicking the “delete” button below.
            </p>
          </div>

          <div className="mt-auto flex items-end justify-between">
            <FadePresence transitionKey={footerStep} duration={400}>
              {footerStep === 'deleting' ? (
                <p className="h-[22px] translate-y-[7px] content-end font-readmore text-[16px] leading-none text-[#BFC6DD]">
                  Deleting student roster...
                </p>
              ) : footerStep === 'retry' ? (
                <p className="h-[22px] translate-y-[7px] content-end font-readmore text-[16px] leading-none text-[#BFC6DD]">
                  Failed to delete student roster. Try again?
                </p>
              ) : footerStep === 'confirm' ? (
                <p className="h-[22px] translate-y-[7px] content-end font-readmore text-[16px] leading-none text-[#BFC6DD]">
                  Please confirm the deletion of your entire student account roster.
                </p>
              ) : (
                <p className="h-[22px] translate-y-[7px] content-end font-readmore text-[16px] leading-none text-[#BFC6DD]">
                  Student roster deletion is permanent. It cannot be undone.
                </p>
              )}
            </FadePresence>

            <FadePresence transitionKey={footerStep} duration={400}>
              {footerStep === 'deleting' ? (
                <DotLoader dotColor="#85A8FF" size="xl" />
              ) : footerStep === 'confirm' || footerStep === 'retry' ? (
                <div className="flex flex-row items-center gap-[18px]">
                  <button
                    type="button"
                    onClick={handleBack}
                    className="flex h-[30px] w-[20px] cursor-pointer items-center justify-center"
                  >
                    <BackArrowIcon className="h-[30px] w-[20px] [&_path]:fill-[#E2E8F7] [&_path]:hover:fill-[#E2E8F7BF] [&_path]:active:fill-[#E2E8F780]" />
                  </button>
                  <button
                    type="button"
                    onClick={handleConfirmDelete}
                    className="h-[50px] w-[122px] cursor-pointer rounded-full bg-[#6c96ff] py-3 font-readingful text-[2.2rem] leading-none text-white transition duration-150 hover:opacity-75 active:opacity-50"
                  >
                    Confirm
                  </button>
                </div>
              ) : (
                <button
                  type="button"
                  onClick={() => setFooterStep('confirm')}
                  className="h-[50px] w-[106px] cursor-pointer rounded-full bg-[#6c96ff] py-3 font-readingful text-[2.2rem] leading-none text-white transition duration-150 hover:opacity-75 active:opacity-50"
                >
                  Delete
                </button>
              )}
            </FadePresence>
          </div>
        </div>
      </FadePresence>
    </>
  );
}

DeleteAll.layout = (page: ReactElement) => (
  <TeacherLayoutWithProviders>{page}</TeacherLayoutWithProviders>
);
