import React, { useEffect, useState } from 'react';
import { Box, Text, IconButton, Icon, Icons, Scroll, Button, config, toRem } from 'folds';
import { Page, PageContent, PageHeader } from '../../../components/page';
import { SequenceCard } from '../../../components/sequence-card';
import { SequenceCardStyle } from '../styles.css';
import { SettingTile } from '../../../components/setting-tile';
import LotusLogo from '../../../../../public/res/Lotus.png';
import pkg from '../../../../../package.json';
import { clearCacheAndReload } from '../../../../client/initMatrix';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { lotusTerminalBodyClass } from '../../../../lotus-terminal.css';

type MSC1929Contact = {
  matrix_id?: string;
  email_address?: string;
  role?: string;
};

type MSC1929Support = {
  contacts?: MSC1929Contact[];
  support_page?: string;
};

function useServerSupport(): MSC1929Support | null {
  const mx = useMatrixClient();
  const [support, setSupport] = useState<MSC1929Support | null>(null);

  useEffect(() => {
    const baseUrl = (mx as unknown as { baseUrl: string }).baseUrl;
    fetch(`${baseUrl}/.well-known/matrix/support`)
      .then((res) => {
        if (!res.ok) return null;
        return res.json() as Promise<MSC1929Support>;
      })
      .then((data) => {
        if (data && (data.contacts?.length || data.support_page)) {
          setSupport(data);
        }
      })
      .catch(() => {
        // Graceful degradation — server may not have this configured
      });
  }, [mx]);

  return support;
}

type AboutProps = {
  requestClose: () => void;
};
export function About({ requestClose }: AboutProps) {
  const mx = useMatrixClient();
  const serverSupport = useServerSupport();

  return (
    <Page>
      <PageHeader outlined={false}>
        <Box grow="Yes" gap="200">
          <Box grow="Yes" alignItems="Center" gap="200">
            <Text size="H3" truncate>
              About
            </Text>
          </Box>
          <Box shrink="No">
            <IconButton onClick={requestClose} variant="Surface" aria-label="Close">
              <Icon src={Icons.Cross} />
            </IconButton>
          </Box>
        </Box>
      </PageHeader>
      <Box grow="Yes">
        <Scroll hideTrack visibility="Hover">
          <PageContent>
            <Box direction="Column" gap="700">
              <Box gap="400">
                <Box shrink="No">
                  <img
                    style={{ width: toRem(60), height: toRem(60) }}
                    src={LotusLogo}
                    alt="Lotus Chat logo"
                  />
                </Box>
                <Box direction="Column" gap="300">
                  <Box direction="Column" gap="100">
                    <Box gap="100" alignItems="End">
                      <Text size="H3">Lotus Chat</Text>
                      <Text size="T200">v{pkg.version}</Text>
                    </Box>
                    <Text>A Matrix client for Lotus Guild.</Text>
                  </Box>

                  <Box gap="200" wrap="Wrap">
                    <Button
                      as="a"
                      href="https://code.lotusguild.org/LotusGuild/cinny"
                      rel="noreferrer noopener"
                      target="_blank"
                      variant="Secondary"
                      fill="Soft"
                      size="300"
                      radii="300"
                      before={<Icon src={Icons.Code} size="100" filled />}
                    >
                      <Text size="B300">Source Code</Text>
                    </Button>
                    <Button
                      as="a"
                      href="https://matrix.lotusguild.org"
                      rel="noreferrer noopener"
                      target="_blank"
                      variant="Critical"
                      fill="Soft"
                      size="300"
                      radii="300"
                      before={<Icon src={Icons.Heart} size="100" filled />}
                    >
                      <Text size="B300">Support</Text>
                    </Button>
                  </Box>
                </Box>
              </Box>
              <Box direction="Column" gap="100">
                <Text size="L400">Options</Text>
                <SequenceCard
                  className={SequenceCardStyle}
                  variant="SurfaceVariant"
                  direction="Column"
                  gap="400"
                >
                  <SettingTile
                    title="Clear Cache & Reload"
                    description="Clear all your locally stored data and reload from server."
                    after={
                      <Button
                        onClick={() => clearCacheAndReload(mx)}
                        variant="Secondary"
                        fill="Soft"
                        size="300"
                        radii="300"
                        outlined
                      >
                        <Text size="B300">Clear Cache</Text>
                      </Button>
                    }
                  />
                </SequenceCard>
              </Box>
              {serverSupport && (
                <Box direction="Column" gap="100">
                  <Text size="L400">Homeserver Support</Text>
                  <SequenceCard
                    className={SequenceCardStyle}
                    variant="SurfaceVariant"
                    direction="Column"
                    gap="400"
                  >
                    <Box direction="Column" gap="200" style={{ padding: config.space.S200 }}>
                      {serverSupport.contacts && serverSupport.contacts.length > 0 && (
                        <Box direction="Column" gap="100">
                          {serverSupport.contacts.map((contact, i) => (
                            <Box key={i} alignItems="Center" gap="200">
                              <Text size="T300" priority="300">
                                {contact.role === 'm.role.admin'
                                  ? 'Admin'
                                  : contact.role === 'm.role.security'
                                    ? 'Security'
                                    : 'Contact'}
                                :
                              </Text>
                              <Text
                                size="T300"
                                style={{
                                  color: document.body.classList.contains(lotusTerminalBodyClass)
                                    ? 'var(--lt-accent-cyan)'
                                    : undefined,
                                }}
                              >
                                {contact.matrix_id ?? contact.email_address ?? ''}
                              </Text>
                            </Box>
                          ))}
                        </Box>
                      )}
                      {serverSupport.support_page && (
                        <Box alignItems="Center" gap="200">
                          <Text size="T300" priority="300">
                            Support Page:
                          </Text>
                          <Text size="T300">
                            <a
                              href={serverSupport.support_page}
                              target="_blank"
                              rel="noreferrer noopener"
                              style={{
                                color: document.body.classList.contains(lotusTerminalBodyClass)
                                  ? 'var(--lt-accent-cyan)'
                                  : undefined,
                              }}
                            >
                              {serverSupport.support_page}
                            </a>
                          </Text>
                        </Box>
                      )}
                    </Box>
                  </SequenceCard>
                </Box>
              )}
              <Box direction="Column" gap="100">
                <Text size="L400">Credits</Text>
                <SequenceCard
                  className={SequenceCardStyle}
                  variant="SurfaceVariant"
                  direction="Column"
                  gap="400"
                >
                  <Box
                    as="ul"
                    direction="Column"
                    gap="200"
                    style={{
                      margin: 0,
                      paddingLeft: config.space.S400,
                    }}
                  >
                    <li>
                      <Text size="T300">
                        The{' '}
                        <a
                          href="https://github.com/matrix-org/matrix-js-sdk"
                          rel="noreferrer noopener"
                          target="_blank"
                        >
                          matrix-js-sdk
                        </a>{' '}
                        is ©{' '}
                        <a
                          href="https://matrix.org/foundation"
                          rel="noreferrer noopener"
                          target="_blank"
                        >
                          The Matrix.org Foundation C.I.C
                        </a>{' '}
                        used under the terms of{' '}
                        <a
                          href="http://www.apache.org/licenses/LICENSE-2.0"
                          rel="noreferrer noopener"
                          target="_blank"
                        >
                          Apache 2.0
                        </a>
                        .
                      </Text>
                    </li>
                    <li>
                      <Text size="T300">
                        The{' '}
                        <a
                          href="https://github.com/mozilla/twemoji-colr"
                          target="_blank"
                          rel="noreferrer noopener"
                        >
                          twemoji-colr
                        </a>{' '}
                        font is ©{' '}
                        <a href="https://mozilla.org/" target="_blank" rel="noreferrer noopener">
                          Mozilla Foundation
                        </a>{' '}
                        used under the terms of{' '}
                        <a
                          href="http://www.apache.org/licenses/LICENSE-2.0"
                          target="_blank"
                          rel="noreferrer noopener"
                        >
                          Apache 2.0
                        </a>
                        .
                      </Text>
                    </li>
                    <li>
                      <Text size="T300">
                        The{' '}
                        <a
                          href="https://twemoji.twitter.com"
                          target="_blank"
                          rel="noreferrer noopener"
                        >
                          Twemoji
                        </a>{' '}
                        emoji art is ©{' '}
                        <a
                          href="https://twemoji.twitter.com"
                          target="_blank"
                          rel="noreferrer noopener"
                        >
                          Twitter, Inc and other contributors
                        </a>{' '}
                        used under the terms of{' '}
                        <a
                          href="https://creativecommons.org/licenses/by/4.0/"
                          target="_blank"
                          rel="noreferrer noopener"
                        >
                          CC-BY 4.0
                        </a>
                        .
                      </Text>
                    </li>
                    <li>
                      <Text size="T300">
                        The{' '}
                        <a
                          href="https://material.io/design/sound/sound-resources.html"
                          target="_blank"
                          rel="noreferrer noopener"
                        >
                          Material sound resources
                        </a>{' '}
                        are ©{' '}
                        <a href="https://google.com" target="_blank" rel="noreferrer noopener">
                          Google
                        </a>{' '}
                        used under the terms of{' '}
                        <a
                          href="https://creativecommons.org/licenses/by/4.0/"
                          target="_blank"
                          rel="noreferrer noopener"
                        >
                          CC-BY 4.0
                        </a>
                        .
                      </Text>
                    </li>
                  </Box>
                </SequenceCard>
              </Box>
            </Box>
          </PageContent>
        </Scroll>
      </Box>
    </Page>
  );
}
