import { Flex, Image, Text } from '@chakra-ui/react'
import { Upload } from 'lucide-react'
import { useRef } from 'react'

export interface CalledItLogoUploadProps {
  currentLogoUrl?: string
  label?: string
  onFileSelect: (file: File) => void
}

export function CalledItLogoUpload({ currentLogoUrl, label = 'Logo', onFileSelect }: CalledItLogoUploadProps) {
  const inputRef = useRef<HTMLInputElement>(null)

  function handleClick() {
    inputRef.current?.click()
  }

  function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0]
    if (file) onFileSelect(file)
    e.target.value = ''
  }

  return (
    <Flex direction="column" gap="1">
      <Text fontSize="sm" fontWeight="500" color="heading">{label}</Text>
      <Flex
        align="center"
        gap="3"
        p="3"
        borderWidth="1px"
        borderColor="border"
        rounded="lg"
        cursor="pointer"
        _hover={{ borderColor: 'brand.500', bg: 'subtle' }}
        onClick={handleClick}
        role="button"
        aria-label="Upload logo"
      >
        {currentLogoUrl ? (
          <Image
            src={currentLogoUrl}
            alt="Logo preview"
            boxSize="10"
            rounded="md"
            objectFit="cover"
            flexShrink={0}
          />
        ) : (
          <Flex
            boxSize="10"
            rounded="md"
            bg="subtle"
            align="center"
            justify="center"
            flexShrink={0}
            borderWidth="1px"
            borderColor="border"
          >
            <Upload size={16} color="var(--chakra-colors-gray-400)" />
          </Flex>
        )}
        <Text fontSize="sm" color="muted">
          {currentLogoUrl ? 'Click to replace logo' : 'Click to upload logo'}
        </Text>
      </Flex>
      <input
        ref={inputRef}
        type="file"
        accept="image/jpeg,image/png,image/webp"
        style={{ display: 'none' }}
        onChange={handleChange}
      />
    </Flex>
  )
}
