import { memo, useState } from 'react'
import { AnimatePresence, m, useReducedMotion } from 'framer-motion'
import { Link } from 'react-router-dom'
import {
  Building2,
  Lock,
  ShieldCheck,
  Signal,
  Smartphone,
  Trash2,
} from 'lucide-react'

import type { Device } from '../../types'
import { conditionText, connectionText, getStatusClass } from '../../types'
import { ConfirmDangerDialog } from '../../../../widgets/ConfirmDangerDialog/ConfirmDangerDialog'
import { useDeferredModalPayload } from '../../../../shared/lib/lazyMount'

type DeviceMainCardProps = {
  device: Device
  onOpenHistory: () => void
}

function getDeviceFullName(device: Device) {
  return [device.serialNumber].filter(Boolean).join(' ')
}

function areDeviceMainCardPropsEqual(
  prev: DeviceMainCardProps,
  next: DeviceMainCardProps,
) {
  return (
    prev.onOpenHistory === next.onOpenHistory &&
    prev.device.id === next.device.id &&
    prev.device.image === next.device.image &&
    prev.device.model === next.device.model &&
    prev.device.factoryNumber === next.device.factoryNumber &&
    prev.device.serialNumber === next.device.serialNumber &&
    prev.device.imei === next.device.imei &&
    prev.device.imei2 === next.device.imei2 &&
    prev.device.condition === next.device.condition &&
    prev.device.connection === next.device.connection &&
    prev.device.connectionText === next.device.connectionText &&
    prev.device.permissions?.locked === next.device.permissions?.locked &&
    prev.device.workTime === next.device.workTime &&
    prev.device.organisationId === next.device.organisationId &&
    prev.device.organisation === next.device.organisation &&
    prev.device.registeredAt === next.device.registeredAt
  )
}

export const DeviceMainCard = memo(function DeviceMainCard({
  device,
  onOpenHistory,
}: DeviceMainCardProps) {
  const [deletingDevice, setDeletingDevice] = useState<Device | null>(null)
  const renderDeletingDevice = useDeferredModalPayload(deletingDevice)
  const shouldReduceMotion = useReducedMotion()
  const statusTransition = shouldReduceMotion
    ? { duration: 0 }
    : {
      duration: 0.24,
      ease: [0.34, 1.42, 0.64, 1] as [number, number, number, number],
    }
  const statusItems = [
    {
      key: `condition-${device.condition}`,
      className: getStatusClass(device.condition),
      icon: <ShieldCheck size={17} />,
      content: conditionText[device.condition],
    },
    {
      key: `connection-${device.connection}-${device.connectionText ?? ''}`,
      className: getStatusClass(device.connection),
      icon: <Signal size={17} />,
      content: device.connectionText ?? connectionText[device.connection],
    },
  ]

  if (device.permissions?.locked) {
    statusItems.push({
      key: 'locked',
      className: 'is-danger',
      icon: <Lock size={17} />,
      content: 'Заблокирован',
    })
  }

  if (device.workTime) {
    statusItems.push({
      key: 'work-time',
      className: 'is-muted',
      icon: <Smartphone size={17} />,
      content: `В работе: ${device.workTime}`,
    })
  }

  function handleConfirmDeleteDevice() {
    if (!deletingDevice) return

    console.log('Удаление устройства пока без мутации', deletingDevice)
    setDeletingDevice(null)
  }

  function handleDeleteDevice(device: Device) {
    setDeletingDevice(device)
  }

  return (
    <div className="device-card device-card--main">
      <div className="device-main">
        <div className="device-main__image">
          {device.image ? (
            <img src={device.image} alt={device.model ?? 'Устройство'} />
          ) : (
            <img src="/devices/армафон3.3+.webp" alt="АРМАФОН" />
          )}
        </div>

        <div className="device-main__info">
          <h2>{device.model ?? '-'}</h2>

          <p>{device.factoryNumber}</p>
          <p>
            {device.imei}
            {device.imei2 ? ` · ${device.imei2}` : ''}
          </p>

          <div className="device-main__divider" />

          <div className="device-main__statuses">
            <AnimatePresence>
              {statusItems.map((status, index) => (
                <m.div
                  key={status.key}
                  layout={!shouldReduceMotion}
                  className={`device-status ${status.className}`}
                  initial={{ opacity: 0, x: shouldReduceMotion ? 0 : -8 }}
                  animate={{
                    opacity: 1,
                    x: 0,
                    transition: {
                      ...statusTransition,
                      delay: shouldReduceMotion ? 0 : index * 0.04,
                    },
                  }}
                  exit={{
                    opacity: 0,
                    x: shouldReduceMotion ? 0 : -8,
                    transition: statusTransition,
                  }}
                >
                  {status.icon}
                  {status.content}
                </m.div>
              ))}
            </AnimatePresence>
          </div>
        </div>
      </div>

      <div className="device-main__bottom">
        <div className="device-registered device-organisation">
          <Building2 size={17} />
          <div className="device-registered-info">
            <span>Организация</span>
            {device.organisationId ? (
              <Link to={`/employees/organisations/${device.organisationId}`}>
                {device.organisation ?? `Организация #${device.organisationId}`}
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                  <path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M18.607 11.035v7.929a2.27 2.27 0 0 1-2.3 2.286H5.05a2.27 2.27 0 0 1-2.299-2.3V7.693a2.273 2.273 0 0 1 2.3-2.3h7.928M21.25 2.75L10.679 13.321M15.964 2.75h5.286v5.286"></path>
                </svg>
              </Link>
            ) : (
              <b>{device.organisation ?? 'Не указана'}</b>
            )}
          </div>
        </div>

        <div className="device-registered">
          <Smartphone size={17} />
          <div className="device-registered-info">
            <span>Зарегистрирован</span>
            <b>{device.registeredAt ?? 'Нет данных'}</b>
          </div>
        </div>

        <div className="device-card__actions">
          <button
            className="device-history-btn"
            type="button"
            onClick={onOpenHistory}
          >
            Подробная история эксплуатации
          </button>

          <button
            className="device-delete-btn"
            type="button"
            aria-label="Удалить"
            onClick={() => handleDeleteDevice(device)}
          >
            <Trash2 size={18} />
          </button>
        </div>
      </div>

      <ConfirmDangerDialog
        open={Boolean(deletingDevice)}
        title="Удалить смартфон?"
        description={
          renderDeletingDevice
            ? `Устройство ${getDeviceFullName(renderDeletingDevice)} будет удалено. Это действие нельзя будет отменить.`
            : ''
        }
        confirmText="Удалить"
        onOpenChange={(open) => {
          if (!open) {
            setDeletingDevice(null)
          }
        }}
        onConfirm={handleConfirmDeleteDevice}
      />
    </div>
  )
}, areDeviceMainCardPropsEqual)
