import React, { useRef, useState } from 'react';
import { styled, CircularProgress, IconButton } from '@mui/material';
import { CameraAlt, AddCircleOutline } from '@mui/icons-material';

import { ScreenshotDropzone } from './ScreenshotDropzone';
import { ScreenshotThumbnail } from './ScreenshotThumbnail';
import { MAX_FILE_COUNT } from './utils';
import { useDialogContext, useDialogActions } from '../dialogContext';
import { ScreenshotDetail } from './ScreenshotDetail';
import { ScFieldTitle } from '../../common/FieldTitle';
import { ExtensionPrompt } from './ExtensionPrompt';
import { Tooltip } from '../../common/Tooltip';

const ScPlaceholder = styled('div')`
  display: flex;
  flex-direction: column;
  height: 100px;
  width: 100%;
  align-items: center;
  justify-content: center;
  text-align: center;
  flex-grow: 1;
  border: 1px solid #b5b5b5;
  border-radius: 24px;
`;

const ScScreenshotDummy = styled('div')`
  display: flex;
  width: 100px;
  height: 100px;
  align-items: center;
  justify-content: center;
  margin: 1px;
`;

const ScHeading = styled('div')`
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
`;

const ScControls = styled('div')`
  display: flex;
`;

const ScText = styled('div')`
  color: ${({ theme }) => theme.palette.text.secondary};
`;

const ALLOWED_UPLOAD_TYPES = ['image/png', 'image/jpeg', 'image/gif'];

export const ScreenshotGallery: React.FC = () => {
  const fileRef = useRef<HTMLInputElement>(null);
  const {
    handleUploadImages,
    handleRemoveScreenshot,
    handleTakeScreenshot,
    setScreenshotDetail,
  } = useDialogActions();

  const keyId = useDialogContext((c) => c.keyData?.keyId);
  const screenshots = useDialogContext((c) => c.screenshots);
  const screenshotDetails = useDialogContext((c) => c.screenshotDetail);
  const canTakeScreenshots = useDialogContext((c) => c.canTakeScreenshots);
  const screenshotsUploading = useDialogContext((c) => c.screenshotsUploading);
  const permissions = useDialogContext((c) => c.permissions);

  const [extensionPrompt, setExtensionPrompt] = useState(false);

  const uploadEnabled = permissions.canUploadScreenshots;
  const deleteEnabled = permissions.canDeleteScreenshots;

  function onFileSelected(e: React.SyntheticEvent) {
    const files = (e.target as HTMLInputElement).files;
    if (!files) {
      return;
    }
    const toUpload: File[] = [];
    for (let i = 0; i < files.length; i++) {
      const item = files.item(i);
      if (item) {
        toUpload.push(item);
      }
    }
    validateAndUpload(toUpload);
  }
  const validate = (files: File[]) => {
    const errors: string[] = [];

    if (files.length > MAX_FILE_COUNT) {
      errors.push('Too many files');
    }

    files.forEach((file) => {
      if (ALLOWED_UPLOAD_TYPES.indexOf(file.type) < 0) {
        errors.push(`${file.name}: unsupported format`);
      }
    });

    const valid = errors.length === 0;

    return { errors, valid };
  };

  const validateAndUpload = (files: File[]) => {
    const { valid } = validate(files);
    if (valid) {
      handleUploadImages(files);
    }
  };

  const onFileSelect = () => {
    fileRef.current?.dispatchEvent(new MouseEvent('click'));
  };

  const ableToTakeScreenshot = canTakeScreenshots;

  // @ts-ignore
  const isChrome = Boolean(window.chrome);

  return (
    <>
      <input
        type="file"
        style={{ display: 'none' }}
        ref={fileRef}
        onChange={(e) => onFileSelected(e)}
        multiple
        accept={ALLOWED_UPLOAD_TYPES.join(',')}
      />

      <ScHeading>
        <ScFieldTitle>Screenshots</ScFieldTitle>
        {/* <ScControls>
          {uploadEnabled && (
            <>
              {(isChrome || ableToTakeScreenshot) && (
                <Tooltip title="Take screenshot">
                  <IconButton
                    sx={{ fontSize: 24 }}
                    onClick={
                      ableToTakeScreenshot
                        ? handleTakeScreenshot
                        : () => setExtensionPrompt(true)
                    }
                  >
                    <CameraAlt />
                  </IconButton>
                </Tooltip>
              )}

              <Tooltip title="Add image">
                <IconButton sx={{ fontSize: 24 }} onClick={onFileSelect}>
                  <AddCircleOutline />
                </IconButton>
              </Tooltip>
            </>
          )}
        </ScControls> */}
      </ScHeading>

      <ScreenshotDropzone
        validateAndUpload={validateAndUpload}
        enabled={uploadEnabled}
      >
        {screenshots.length
          ? screenshots.map((ss) => (
              <ScreenshotThumbnail
                key={ss.id}
                keyId={keyId}
                data={ss}
                onClick={() => setScreenshotDetail(ss)}
                onDelete={
                  deleteEnabled || ss.justUploaded
                    ? handleRemoveScreenshot
                    : undefined
                }
              />
            ))
          : null}
        {screenshotsUploading && (
          <ScScreenshotDummy>
            <CircularProgress />
          </ScScreenshotDummy>
        )}
        {!screenshots.length && !screenshotsUploading && (
          <ScPlaceholder
            style={{
              cursor: uploadEnabled ? 'pointer' : 'default',
              paddingTop: '24px',
            }}
            onClick={uploadEnabled ? onFileSelect : undefined}
          >
            <ScText>
              <span style={{ opacity: '0.25' }}>
                <svg
                  width="55"
                  height="39"
                  viewBox="0 0 55 39"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    d="M37.8933 22.7262C37.6454 22.9762 37.3505 23.1745 37.0255 23.3099C36.7006 23.4453 36.352 23.515 36 23.515C35.648 23.515 35.2994 23.4453 34.9744 23.3099C34.6495 23.1745 34.3546 22.9762 34.1067 22.7262L33.3333 21.9262V28.8329C33.3333 29.5401 33.0524 30.2184 32.5523 30.7185C32.0522 31.2186 31.3739 31.4995 30.6667 31.4995C29.9594 31.4995 29.2811 31.2186 28.781 30.7185C28.2809 30.2184 28 29.5401 28 28.8329V21.9262L27.2267 22.7262C26.7245 23.2284 26.0435 23.5105 25.3333 23.5105C24.6232 23.5105 23.9421 23.2284 23.44 22.7262C22.9378 22.2241 22.6557 21.543 22.6557 20.8329C22.6557 20.1227 22.9378 19.4417 23.44 18.9395L28.7733 13.6062C29.0212 13.3563 29.3162 13.1579 29.6411 13.0225C29.9661 12.8871 30.3146 12.8174 30.6667 12.8174C31.0187 12.8174 31.3672 12.8871 31.6922 13.0225C32.0171 13.1579 32.3121 13.3563 32.56 13.6062L37.8933 18.9395C38.1433 19.1875 38.3416 19.4824 38.477 19.8073C38.6124 20.1323 38.6821 20.4809 38.6821 20.8329C38.6821 21.1849 38.6124 21.5335 38.477 21.8584C38.3416 22.1834 38.1433 22.4783 37.8933 22.7262ZM49.3333 18.2729C49.3598 17.7932 49.3598 17.3125 49.3333 16.8329C49.3372 13.3075 48.1767 9.87942 46.032 7.08141C43.8873 4.28339 40.8785 2.27206 37.4731 1.3599C34.0677 0.447744 30.4564 0.68584 27.2003 2.0372C23.9441 3.38855 21.2254 5.77751 19.4667 8.83288C17.6385 8.93037 15.8662 9.49675 14.3203 10.4775C12.7744 11.4583 11.507 12.8204 10.64 14.4329C7.71633 14.8986 5.06972 16.4332 3.21324 18.7393C1.35676 21.0454 0.422659 23.9586 0.592028 26.9143C0.761397 29.87 2.02217 32.6574 4.12993 34.7364C6.23769 36.8153 9.04228 38.0376 12 38.1662H44C46.3446 38.1621 48.6225 37.3855 50.4815 35.9567C52.3404 34.5279 53.6768 32.5264 54.2839 30.2617C54.8911 27.9971 54.7352 25.5955 53.8403 23.4284C52.9454 21.2612 51.3614 19.4493 49.3333 18.2729Z"
                    fill="#8F005D"
                  />
                </svg>
              </span>

              {ableToTakeScreenshot &&
                uploadEnabled &&
                ' Take screenshot by camera icon.'}
            </ScText>
            {uploadEnabled && (
              <ScText
                sx={{
                  paddingTop: '18px',
                  fontWeight: '900',
                  color: '#000000A6',
                }}
              >
                Drag and drop your files here
              </ScText>
            )}
          </ScPlaceholder>
        )}
      </ScreenshotDropzone>
      {screenshotDetails && (
        <ScreenshotDetail
          keyId={keyId}
          screenshot={screenshotDetails}
          onClose={() => setScreenshotDetail(null)}
        />
      )}
      {extensionPrompt && (
        <ExtensionPrompt onClose={() => setExtensionPrompt(false)} />
      )}
    </>
  );
};
