import { useState } from 'react';

import songwhipApi from '~/lib/songwhipApi/songwhipApi';
import Box from '~/src/components/Box';
import Button from '~/src/components/Button';
import Card from '~/src/components/Card';
import { useAppConfirm } from '~/src/components/NextApp/lib/CoreUi';
import TextInput from '~/src/components/TextInput';

export const AdminCacheTool = () => {
  const [path, setPath] = useState<string>('');
  const [data, setData] = useState<object>();
  const [error, setError] = useState<Error>();

  const [isInspecting, setIsInspecting] = useState(false);
  const [isPurging, setIsPurging] = useState(false);
  const [isPurgingEverything, setIsPurgingEverything] = useState(false);
  const confirm = useAppConfirm();

  const fetchItemFromPath = async (path: string) => {
    const resolveResponse = await songwhipApi(`resolve/${path}`, {
      method: 'GET',
    });

    const { type, id } = resolveResponse.json.data;

    let endpoint = 'artists';
    if (type === 'album') endpoint = 'albums';
    if (type === 'track') endpoint = 'tracks';
    if (type === 'customPage') endpoint = 'custom-pages';

    return { endpoint, id };
  };

  const handleInspectPage = async () => {
    setError(undefined);
    setData(undefined);

    if (!path.trim()) return undefined;

    setIsInspecting(true);

    try {
      const { endpoint, id } = await fetchItemFromPath(path);

      const { json } = await songwhipApi(`${endpoint}/${id}/cache`, {
        method: 'GET',
      });

      setData(json.data);
    } catch (error) {
      setError(error);
    } finally {
      setIsInspecting(false);
    }
  };

  const handlePurgePage = async () => {
    setError(undefined);
    setData(undefined);

    if (!path.trim()) return undefined;

    setIsPurging(true);

    try {
      const { endpoint, id } = await fetchItemFromPath(path);

      const { json } = await songwhipApi(`${endpoint}/${id}/cache`, {
        method: 'DELETE',
      });

      setData(json.data);
    } catch (error) {
      setError(error);
    } finally {
      setIsPurging(false);
    }
  };

  const handlePurgeEverything = async () => {
    if (
      !(await confirm({
        content: 'This will purge all caches for all pages.',
      }))
    ) {
      return undefined;
    }

    setError(undefined);
    setData(undefined);
    setIsPurgingEverything(true);

    try {
      const { json } = await songwhipApi(`cache/purge`, {
        method: 'POST',
      });

      setData(json.data);
    } catch (error) {
      setError(error);
    } finally {
      setIsPurgingEverything(false);
    }
  };

  return (
    <Box flexBox flexColumn gap="2rem" flexGrow padding="2rem">
      <Box flexBox flexRow spaceBetween flexWrap gap="1rem">
        <Box flexBox flexRow flexWrap gap="1rem">
          <TextInput
            width={300}
            defaultValue={path}
            onChange={({ value }) => setPath(value)}
            placeholder="Page path"
          />
          <Button
            flexBox
            width={150}
            onClick={() => handleInspectPage()}
            text="Inspect"
            isLoading={isInspecting}
            isDisabled={isPurging || isPurgingEverything}
          />
          <Button
            flexBox
            width={150}
            onClick={() => handlePurgePage()}
            text="Purge"
            isLoading={isPurging}
            isDisabled={isInspecting || isPurgingEverything}
          />
        </Box>

        <Button
          width={300}
          onClick={() => handlePurgeEverything()}
          text="Purge everything"
          isLoading={isPurgingEverything}
          isDisabled={isInspecting || isPurging}
        />
      </Box>

      <Box flexBox flexColumn gap="2rem" flexGrow>
        <Card padding="2rem" flexBox flexColumn flexGrow>
          <pre>
            {error ? error.message : ''}{' '}
            {data ? JSON.stringify(data, null, 2) : ''}
          </pre>
        </Card>
      </Box>
    </Box>
  );
};
