import React, { useState } from 'react';
import styled, { keyframes } from 'styled-components';
import { HiDocument, HiX } from 'react-icons/hi';
import {
  getObjectUrl,
  isPreviewableImage,
  useObjectUrls,
} from '@/shared/hooks/useObjectUrls';
import { formatFileSize, fileExtension } from '@/shared/utils/filePreview';
import { ImageLightbox } from './ImageLightbox';

const previewEnter = keyframes`
  from {
    opacity: 0;
    transform: scale(0.96) translateY(4px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
`;

const PreviewGrid = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(132px, 1fr));
  gap: ${({ theme }) => theme.spacing[4]};
  margin-top: ${({ theme }) => theme.spacing[5]};
  width: 100%;
`;

const PreviewCard = styled.div`
  position: relative;
  display: flex;
  flex-direction: column;
  border: 1px solid ${({ theme }) => theme.colors.borderSoft};
  border-radius: ${({ theme }) => theme.borderRadius.xl};
  background-color: ${({ theme }) => theme.colors.surfaceElevated};
  box-shadow: ${({ theme }) => theme.shadows.sm};
  overflow: hidden;
  min-width: 0;
  animation: ${previewEnter} 0.22s ease-out;
  transition:
    box-shadow ${({ theme }) => theme.transitions.fast},
    transform ${({ theme }) => theme.transitions.fast};

  @media (prefers-reduced-motion: reduce) {
    animation: none;
  }

  &:hover {
    box-shadow: ${({ theme }) => theme.shadows.md};
    transform: ${({ theme }) => theme.motion.hoverLift};
  }
`;

const ImageThumbButton = styled.button`
  width: 100%;
  min-height: 80px;
  max-height: 280px;
  border: none;
  padding: ${({ theme }) => theme.spacing[2]};
  margin: 0;
  background: ${({ theme }) => theme.colors.surfaceMuted};
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;

  &:focus-visible {
    outline: 2px solid ${({ theme }) => theme.colors.primary};
    outline-offset: -2px;
  }
`;

const ThumbImage = styled.img`
  display: block;
  width: 100%;
  height: auto;
  max-height: 260px;
  object-fit: contain;
`;

const FileIconArea = styled.div`
  width: 100%;
  aspect-ratio: 4 / 3;
  min-height: 100px;
  max-height: 140px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: ${({ theme }) => theme.colors.surfaceMuted};
  color: ${({ theme }) => theme.colors.primary};
  font-size: 1.25rem;
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};

  svg {
    width: 28px;
    height: 28px;
    opacity: 0.85;
  }
`;

const PreviewMeta = styled.div`
  padding: ${({ theme }) => `${theme.spacing[3]} ${theme.spacing[3]}`};
  min-width: 0;
`;

const PreviewName = styled.div`
  font-size: ${({ theme }) => theme.typography.fontSize.xs};
  font-weight: ${({ theme }) => theme.typography.fontWeight.medium};
  color: ${({ theme }) => theme.colors.text.primary};
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
`;

const PreviewSize = styled.div`
  font-size: 0.6875rem;
  color: ${({ theme }) => theme.colors.text.tertiary};
  margin-top: 2px;
`;

const RemoveBtn = styled.button`
  position: absolute;
  top: 8px;
  inset-inline-end: 8px;
  width: 28px;
  height: 28px;
  border-radius: ${({ theme }) => theme.borderRadius.full};
  border: none;
  background: ${({ theme }) => theme.colors.surface};
  color: ${({ theme }) => theme.colors.text.secondary};
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: ${({ theme }) => theme.shadows.sm};
  z-index: 1;

  &:hover {
    color: ${({ theme }) => theme.colors.error};
    background: ${({ theme }) => theme.colors.errorLight};
  }

  &:focus-visible {
    outline: 2px solid ${({ theme }) => theme.colors.primary};
  }
`;

export interface FilePreviewListProps {
  files: File[];
  onRemove: (index: number) => void;
  onPreviewImage?: (file: File, url: string) => void;
}

export const FilePreviewList: React.FC<FilePreviewListProps> = ({
  files,
  onRemove,
  onPreviewImage,
}) => {
  const urls = useObjectUrls(files);
  const [lightbox, setLightbox] = useState<{ src: string; alt: string } | null>(null);

  if (files.length === 0) {
    return null;
  }

  const openPreview = (file: File, url: string) => {
    if (onPreviewImage) {
      onPreviewImage(file, url);
    } else {
      setLightbox({ src: url, alt: file.name });
    }
  };

  return (
    <>
      <PreviewGrid>
        {files.map((file, index) => {
          const url = getObjectUrl(urls, file);
          const isImage = isPreviewableImage(file);

          return (
            <PreviewCard key={`${file.name}-${file.size}-${file.lastModified}`}>
              <RemoveBtn
                type="button"
                onClick={() => onRemove(index)}
                aria-label={`Remove ${file.name}`}
              >
                <HiX aria-hidden />
              </RemoveBtn>
              {isImage && url ? (
                <ImageThumbButton
                  type="button"
                  onClick={() => openPreview(file, url)}
                  aria-label={file.name}
                >
                  <ThumbImage src={url} alt={file.name} />
                </ImageThumbButton>
              ) : (
                <FileIconArea aria-hidden>
                  <HiDocument />
                  {fileExtension(file.name).slice(0, 4)}
                </FileIconArea>
              )}
              <PreviewMeta>
                <PreviewName title={file.name}>{file.name}</PreviewName>
                <PreviewSize>{formatFileSize(file.size)}</PreviewSize>
              </PreviewMeta>
            </PreviewCard>
          );
        })}
      </PreviewGrid>
      {lightbox && (
        <ImageLightbox
          src={lightbox.src}
          alt={lightbox.alt}
          onClose={() => setLightbox(null)}
        />
      )}
    </>
  );
};
