import {
  useEffect,
  useState,
  type FormEvent,
} from 'react'
import * as Dialog from '@radix-ui/react-dialog'
import { X } from 'lucide-react'

import { machineDictionariesService } from '../../../../entities/machine/api/machineDictionariesService'
import type {
  Machine,
  MachineDictionaryOption,
} from '../../../../entities/machine/model/types'
import { machinesService } from '../../../../entities/machine/api/machinesService'
import { MotionDialogContent } from '../../../../shared/ui/MotionDialog/MotionDialog'
import { MachineSelect } from '../MachineSelect/MachineSelect'

import '../../../EmployeesPage/components/AddEmployeeModal/AddEmployeeModal.scss'
import './AddMachineModal.scss'

type AddMachineModalProps = {
  open: boolean
  mode?: 'create' | 'edit'
  machine?: Machine | null
  onOpenChange: (open: boolean) => void
  onSuccess?: () => void | Promise<void>
}

export function AddMachineModal({
  open,
  mode = 'create',
  machine = null,
  onOpenChange,
  onSuccess,
}: AddMachineModalProps) {
  const isEditMode = mode === 'edit'
  const [name, setName] = useState('')
  const [licensePlate, setLicensePlate] = useState('')
  const [type, setType] = useState('')
  const [department, setDepartment] = useState('')
  const [description, setDescription] = useState('')
  const [machineTypeOptions, setMachineTypeOptions] = useState<
    MachineDictionaryOption[]
  >([])
  const [departmentOptions, setDepartmentOptions] = useState<
    MachineDictionaryOption[]
  >([])
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [submitError, setSubmitError] = useState<string | null>(null)

  useEffect(() => {
    if (!open) return

    let isMounted = true

    async function loadDictionaries() {
      const [types, departments] = await Promise.all([
        machineDictionariesService.getMachineTypes(),
        machineDictionariesService.getMachineDepartments(),
      ])

      if (!isMounted) return

      setMachineTypeOptions(types)
      setDepartmentOptions(departments)
    }

    loadDictionaries()

    return () => {
      isMounted = false
    }
  }, [open])

  useEffect(() => {
    if (!open) return

    setSubmitError(null)

    if (isEditMode && machine) {
      setName(machine.name)
      setLicensePlate(machine.licensePlate)
      setType(machine.type)
      setDepartment(machine.department)
      setDescription(machine.description)
      return
    }

    setName('')
    setLicensePlate('')
    setType('')
    setDepartment('')
    setDescription('')
  }, [open, isEditMode, machine])

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()

    if (isSubmitting) return

    const payload = {
      name: name.trim(),
      licensePlate: licensePlate.trim(),
      type: type.trim(),
      department: department.trim(),
      description: description.trim(),
    }

    if (
      !payload.name ||
      !payload.licensePlate ||
      !payload.type ||
      !payload.department
    ) {
      return
    }

    try {
      setIsSubmitting(true)
      setSubmitError(null)

      if (isEditMode) {
        if (!machine) return

        await machinesService.updateMachine(machine.id, payload)
      } else {
        await machinesService.createMachine(payload)
      }

      await onSuccess?.()
      onOpenChange(false)
    } catch (error) {
      setSubmitError(
        error instanceof Error
          ? error.message
          : 'Не удалось сохранить АТТ',
      )
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <Dialog.Root open={open} onOpenChange={onOpenChange}>
      <MotionDialogContent
        open={open}
        overlayClassName="add-employee-modal__overlay"
        contentClassName="add-employee-modal add-machine-modal"
        motionPreset="fade"
      >
        <div className="add-employee-modal__header">
          <div>
            <Dialog.Title className="add-employee-modal__title">
              {isEditMode ? 'Редактировать АТТ' : 'Добавить АТТ'}
            </Dialog.Title>

            <Dialog.Description className="add-employee-modal__description">
              {isEditMode
                ? 'Изменение данных АТТ'
                : 'Создание АТТ в парке мониторинга'}
            </Dialog.Description>
          </div>

          <Dialog.Close
            className="add-employee-modal__close"
            type="button"
            disabled={isSubmitting}
          >
            <X size={20} />
          </Dialog.Close>
        </div>

        <form className="add-employee-form" onSubmit={handleSubmit}>
          <div className="add-employee-layout">
            <div className="add-employee-fields">
              <div className="add-employee-fields__section">
                <div className="add-employee-fields__title">
                  <span>Основные данные</span>
                  <p>Название, госномер, тип и подразделение АТТ.</p>
                </div>

                <label className="add-employee-field">
                  <span>Название АТТ</span>
                  <input
                    value={name}
                    onChange={(event) => setName(event.target.value)}
                    placeholder="Например: Самосвал БелАЗ 7555"
                    required
                    disabled={isSubmitting}
                  />
                </label>

                <div className="add-employee-form__grid">
                  <label className="add-employee-field">
                    <span>Госномер</span>
                    <input
                      value={licensePlate}
                      onChange={(event) => setLicensePlate(event.target.value)}
                      placeholder="А123ВС 154"
                      required
                      disabled={isSubmitting}
                    />
                  </label>

                  <div className="add-employee-field">
                    <span>Тип АТТ</span>
                    <MachineSelect
                      value={type}
                      options={machineTypeOptions}
                      placeholder="Самосвал"
                      emptyText="Типы АТТ не найдены"
                      disabled={isSubmitting}
                      onChange={setType}
                    />
                  </div>
                </div>

                <div className="add-employee-field">
                  <span>Подразделение / участок / объект</span>
                  <MachineSelect
                    value={department}
                    options={departmentOptions}
                    placeholder="Карьер Северный"
                    emptyText="Подразделения не найдены"
                    disabled={isSubmitting}
                    onChange={setDepartment}
                  />
                </div>
              </div>
            </div>

            <div className="add-employee-fields">
              <div className="add-employee-fields__section">
                <div className="add-employee-fields__title">
                  <span>Комментарий</span>
                  <p>Маяк привязывается отдельным действием после создания АТТ.</p>
                </div>

                <label className="add-employee-field add-machine-field--textarea">
                  <span>Описание / комментарий</span>
                  <textarea
                    value={description}
                    onChange={(event) => setDescription(event.target.value)}
                    placeholder="Короткий комментарий по АТТ"
                    disabled={isSubmitting}
                  />
                </label>
              </div>
            </div>
          </div>

          {submitError && (
            <div className="add-employee-error">
              {submitError}
            </div>
          )}

          <div className="add-employee-modal__footer">
            <Dialog.Close
              className="add-employee-cancel"
              type="button"
              disabled={isSubmitting}
            >
              Отмена
            </Dialog.Close>

            <button
              className="add-employee-submit"
              type="submit"
              disabled={isSubmitting}
            >
              {isSubmitting
                ? isEditMode
                  ? 'Сохранение...'
                  : 'Добавление...'
                : isEditMode
                  ? 'Сохранить'
                  : 'Добавить'}
            </button>
          </div>
        </form>
      </MotionDialogContent>
    </Dialog.Root>
  )
}
