import { useEffect, useState } from 'react';
import { useLocalization } from '../hooks';
import { Button, Link } from '../components';
import { ROUTES } from 'routes';

export default function PzErrorPage({
  error,
  reset
}: {
  error: Error & { digest?: string; isServerError?: boolean };
  reset: () => void;
}) {
  const [isServerError, setIsServerError] = useState(false);

  useEffect(() => {
    if ('isServerError' in error) {
      setIsServerError(true);
      return;
    }

    setIsServerError(!!error.digest);
  }, [error]);

  return isServerError ? (
    <ServerErrorUI />
  ) : (
    <ClientErrorUI error={error} reset={reset} />
  );
}

function ClientErrorUI({
  error,
  reset
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  const { t } = useLocalization();

  const errorMessage = error?.message || 'Unknown error';

  return (
    <section className="text-center px-6 py-6 my-14 md:px-0 md:m-14">
      <div className="text-4xl font-bold md:text-6xl text-red-500">500</div>
      <h1 className="text-lg md:text-xl mt-4">
        {t('common.client_error.title')}
      </h1>
      <p className="text-lg md:text-xl mt-2">
        {t('common.client_error.description')}
      </p>

      <div className="mt-4 mx-auto max-w-lg">
        <p className="text-xs text-gray-600 font-mono bg-gray-100 p-3 rounded overflow-auto text-left">
          <span className="font-semibold">Error:</span> {errorMessage}
        </p>
      </div>

      <div className="mt-6 flex flex-col gap-4 items-center justify-center">
        <Link href={ROUTES.HOME} className="text-lg underline">
          {t('common.client_error.link_text')}
        </Link>
        <Button onClick={reset} className="text-lg">
          {t('common.try_again')}
        </Button>
      </div>
    </section>
  );
}

function ServerErrorUI() {
  const { t } = useLocalization();

  const reloadPage = () => {
    window.location.reload();
  };

  return (
    <section className="text-center px-6 my-14 md:px-0 md:m-14">
      <div className="text-7xl font-bold md:text-8xl">500</div>
      <h1 className="text-lg md:text-xl"> {t('common.page_500.title')} </h1>
      <p className="text-lg md:text-xl"> {t('common.page_500.description')} </p>

      <div className="mt-6 flex flex-col gap-4 items-center justify-center">
        <Link href={ROUTES.HOME} className="text-lg underline">
          {t('common.page_500.link_text')}
        </Link>
        <Button onClick={reloadPage} className="text-lg">
          {t('common.try_again')}
        </Button>
      </div>
    </section>
  );
}
