import clsx from 'clsx'
import Link from 'next/link'
import {useEffect, useMemo, useState} from 'react'
import toast from 'react-hot-toast'
import {Button} from 'web/components/buttons/button'
import {Col} from 'web/components/layout/col'
import {Modal, MODAL_CLASS, SCROLLABLE_MODAL_CLASS} from 'web/components/layout/modal'
import {Row} from 'web/components/layout/row'
import {Avatar} from 'web/components/widgets/avatar'
import {Title} from 'web/components/widgets/title'
import {useHiddenProfiles} from 'web/hooks/use-hidden-profiles'
import {api} from 'web/lib/api'
import {useT} from 'web/lib/locale'

export function HiddenProfilesModal(props: {open: boolean; setOpen: (open: boolean) => void}) {
  const {open, setOpen} = props
  const t = useT()
  const [busyIds, setBusyIds] = useState<Record<string, boolean>>({})
  const {hiddenProfiles, refreshHiddenProfiles} = useHiddenProfiles()

  const empty = useMemo(
    () => (hiddenProfiles ? hiddenProfiles.length === 0 : false),
    [hiddenProfiles],
  )

  useEffect(() => {
    if (!open) return
    refreshHiddenProfiles()
  }, [open])

  const unhide = async (userId: string) => {
    if (busyIds[userId]) return
    setBusyIds((b) => ({...b, [userId]: true}))
    try {
      await api('unhide-profile', {hiddenUserId: userId})
      refreshHiddenProfiles()
    } catch (e) {
      console.error('Failed to unhide profile', e)
      toast.error(t('settings.hidden_profiles.unhide_failed', 'Failed to unhide'))
    } finally {
      // setBusyIds((b) => ({...b, [userId]: false}))
    }
  }

  return (
    <Modal open={open} setOpen={setOpen} size="lg">
      <Col className={clsx(MODAL_CLASS, 'mx-0 sm:mx-24')}>
        <Title className="mb-2">
          {t('settings.hidden_profiles.title', "Profiles you've hidden")}
        </Title>
        {hiddenProfiles && hiddenProfiles.length > 0 && (
          <Col
            className={clsx('divide-y divide-canvas-300 w-full pr-4', SCROLLABLE_MODAL_CLASS)}
            data-testid="hidden-profiles"
          >
            {hiddenProfiles.map((u) => (
              <Row key={u.id} className="items-center justify-between py-2 gap-2">
                <Link className="w-full rounded-md hover:bg-canvas-25 p-2" href={'/' + u.username}>
                  <Row className="items-center gap-3">
                    <Avatar size="md" username={u.username} avatarUrl={u.avatarUrl ?? undefined} />
                    <Col>
                      <div className="font-medium">{u.name}</div>
                      <div className="text-ink-500 text-sm">@{u.username}</div>
                    </Col>
                  </Row>
                </Link>
                <Button
                  size="sm"
                  color="gray-outline"
                  onClick={() => unhide(u.id)}
                  disabled={busyIds[u.id]}
                >
                  {busyIds[u.id]
                    ? t('settings.hidden_profiles.unhiding', 'Unhiding...')
                    : t('settings.hidden_profiles.unhide', 'Unhide')}
                </Button>
              </Row>
            ))}
          </Col>
        )}
        {empty && (
          <div className="text-ink-500 py-6 text-center">
            {t('settings.hidden_profiles.empty', "You haven't hidden any profiles.")}
          </div>
        )}
      </Col>
    </Modal>
  )
}

export default HiddenProfilesModal
