'use client'

import { useState } from 'react'
import { Card, CardHeader, CardContent, Typography, Stack, CircularProgress } from '@mui/material'
import Button from '@/@core/components/mui/Button'
import { useTranslations } from 'next-intl'
import { useGetEntityProfile } from '@/@core/hooks/data/profile'
import { useUpdateLogo } from '@/@core/hooks/data/profile/useUpdateLogo'
import { useUpdateCoverImage } from '@/@core/hooks/data/profile/useUpdateCoverImage'
import { useSnackbar } from 'notistack'
import { promptAndProcessImage } from '@/utils/imageCompression'

export default function ImagesCard() {
  const t = useTranslations('PROFILE')
  const { enqueueSnackbar } = useSnackbar()
  const { data, refetch } = useGetEntityProfile()
  const profile = data?.data

  const [editMode, setEditMode] = useState(false)
  const [logoFile, setLogoFile] = useState<File | null>(null)
  const [coverFile, setCoverFile] = useState<File | null>(null)
  const [logoPreview, setLogoPreview] = useState<string | null>(null)
  const [coverPreview, setCoverPreview] = useState<string | null>(null)

  const { mutateAsync: updateLogo, isPending: isLogoPending } = useUpdateLogo()
  const { mutateAsync: updateCover, isPending: isCoverPending } = useUpdateCoverImage()

  const handlePickLogo: React.ChangeEventHandler<HTMLInputElement> = async e => {
    const rawFile = e.target.files?.[0] || null
    if (!rawFile) {
      setLogoFile(null)
      setLogoPreview(null)
      return
    }

    const processed = await promptAndProcessImage(rawFile)
    if (!processed) {
      setLogoFile(null)
      setLogoPreview(null)
      return
    }

    setLogoFile(processed)
    const url = URL.createObjectURL(processed)
    setLogoPreview(url)
  }

  const handlePickCover: React.ChangeEventHandler<HTMLInputElement> = async e => {
    const rawFile = e.target.files?.[0] || null
    if (!rawFile) {
      setCoverFile(null)
      setCoverPreview(null)
      return
    }

    const processed = await promptAndProcessImage(rawFile)
    if (!processed) {
      setCoverFile(null)
      setCoverPreview(null)
      return
    }

    setCoverFile(processed)
    const url = URL.createObjectURL(processed)
    setCoverPreview(url)
  }

  const handleCancel = () => {
    setEditMode(false)
    setLogoFile(null)
    setCoverFile(null)
    setLogoPreview(null)
    setCoverPreview(null)
  }

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    try {
      if (!logoFile && !coverFile) {
        setEditMode(false)
        return
      }

      if (logoFile) {
        const fd = new FormData()
        fd.append('logo', logoFile)
        await updateLogo(fd)
      }

      if (coverFile) {
        const fd = new FormData()
        fd.append('cover_image', coverFile)
        await updateCover(fd)
      }

      enqueueSnackbar(t('images.successMessage'), { variant: 'success' })
      await refetch()
      handleCancel()
    } catch (error: any) {
      enqueueSnackbar(error?.message || t('images.errorMessage'), { variant: 'error' })
    }
  }

  if (!profile) return <Typography>{t('loading')}</Typography>

  const isPending = isLogoPending || isCoverPending

  const currentLogo = logoPreview || profile.logo_url
  const currentCover = coverPreview || profile.cover_image_url

  return (
    <Card className='rounded-xl shadow-sm border border-gray-200 h-full'>
      <CardHeader
        title={t('images.title')}
        action={
          editMode ? (
            <Stack direction='row' spacing={1}>
              <Button size='small' variant='outlined' onClick={handleCancel} disabled={isPending}>
                {t('cancel')}
              </Button>
              <Button
                size='small'
                variant='contained'
                type='submit'
                form='images-form'
                disabled={isPending || (!logoFile && !coverFile)}
                startIcon={isPending ? <CircularProgress size={16} color='inherit' /> : null}
              >
                {isPending ? t('saving') : t('save')}
              </Button>
            </Stack>
          ) : (
            <Button size='small' onClick={() => setEditMode(true)}>
              {t('edit')}
            </Button>
          )
        }
      />

      <CardContent className='flex flex-col gap-4'>
        {editMode ? (
          <form id='images-form' onSubmit={handleSubmit} className='flex flex-col gap-4'>
            <div>
              <Typography variant='subtitle2' gutterBottom>
                {t('images.logo')}
              </Typography>
              {currentLogo && (
                <img
                  src={currentLogo}
                  alt='Logo'
                  className='rounded-md border object-contain w-full h-40 bg-gray-50 mb-2'
                />
              )}
              <input type='file' accept='image/*' onChange={handlePickLogo} />
            </div>

            <div>
              <Typography variant='subtitle2' gutterBottom>
                {t('images.cover')}
              </Typography>
              {currentCover && (
                <img
                  src={currentCover}
                  alt='Cover'
                  className='rounded-md border object-cover w-full h-40 bg-gray-50 mb-2'
                />
              )}
              <input type='file' accept='image/*' onChange={handlePickCover} />
            </div>
          </form>
        ) : (
          <>
            <div>
              <Typography variant='subtitle2' gutterBottom>
                {t('images.logo')}
              </Typography>
              <img
                src={profile.logo_url}
                alt='Logo'
                className='rounded-md border object-contain w-full h-40 bg-gray-50'
              />
            </div>
            <div>
              <Typography variant='subtitle2' gutterBottom>
                {t('images.cover')}
              </Typography>
              <img
                src={profile.cover_image_url}
                alt='Cover'
                className='rounded-md border object-cover w-full h-40 bg-gray-50'
              />
            </div>
          </>
        )}
      </CardContent>
    </Card>
  )
}
