import { CellsBadge } from '@/entity/element/ui/cellsBadge'
import {
  AlertCircle,
  Building2,
  Calendar as CalendarIcon,
  CheckCircle,
  Droplets,
  Gauge,
  Settings,
  Thermometer,
} from 'lucide-react'
import { useEffect, useState } from 'react'
import { Button } from 'shared/ui/button'
import { Card, CardContent } from 'shared/ui/card'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from 'shared/ui/dialog'
import { Input } from 'shared/ui/input'
import { Label } from 'shared/ui/label'
import {
  useDailyConditions,
  useLaboratories,
  useLaboratoryConditions,
} from './hooks'
import isEqual from 'lodash.isequal'
import {
  VerificationConditionsConfig,
  VerificationConditionsValue,
} from './types'

// Утилиты для работы с localStorage
const getLocalStorageKey = (type: string, id: string) => `${type}_${id}`

const saveToLocalStorage = (key: string, value: string) => {
  try {
    localStorage.setItem(key, value)
  } catch (error) {
    console.warn('Failed to save to localStorage:', error)
  }
}

const getFromLocalStorage = (key: string): string => {
  try {
    return localStorage.getItem(key) || ''
  } catch (error) {
    console.warn('Failed to get from localStorage:', error)
    return ''
  }
}

// Иконки для разных типов условий
const getConditionIcon = (name: string) => {
  const lowerName = name.toLowerCase()
  if (lowerName.includes('температур')) return Thermometer
  if (lowerName.includes('влажн')) return Droplets
  if (lowerName.includes('давлен')) return Gauge
  return AlertCircle
}

const ConditionItem = ({
  name,
  value,
  unit,
}: {
  name: string
  value?: string
  unit?: string
}) => {
  const Icon = getConditionIcon(name)

  return (
    <div className="flex items-center gap-2 rounded-md bg-muted/30 p-1.5 text-sm">
      <div className="flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-primary/10">
        <Icon className="h-2.5 w-2.5 text-primary" />
      </div>
      <div className="min-w-0 flex-1">
        <div className="font-medium text-foreground">{name}</div>
      </div>
      <div className="h-5 shrink-0 rounded bg-muted px-2 py-0.5 text-xs text-muted-foreground">
        {value || '—'} {unit || ''}
      </div>
    </div>
  )
}

interface VerificationConditionsRenderProps {
  config: VerificationConditionsConfig & { id?: string }
  value?: VerificationConditionsValue
  onChange?: (value: VerificationConditionsValue) => void
  onSave?: (value: VerificationConditionsValue) => Promise<void>
}

export function VerificationConditionsRender({
  config,
  value,
  onChange,
  onSave,
}: VerificationConditionsRenderProps) {
  // Инициализация даты с учетом localStorage
  const getInitialDate = () => {
    if (value?.date) return value.date
    if (config.selectedDate) return config.selectedDate

    // Попытка загрузить из localStorage
    if (config.id) {
      const key = getLocalStorageKey('verification_conditions_date', config.id)
      const savedDate = getFromLocalStorage(key)
      if (savedDate) return savedDate
    }

    return new Date().toISOString().split('T')[0]
  }

  const [selectedDate, setSelectedDate] = useState(getInitialDate)
  const [editDialogOpen, setEditDialogOpen] = useState(false)
  const [editingConditions, setEditingConditions] = useState<
    Record<string, string>
  >({})

  const { data: laboratories = [] } = useLaboratories()
  const { data: labData } = useLaboratoryConditions(config.selectedLaboratoryId)
  const {
    data: dailyCondition,
    saveConditions,
    isSaving,
  } = useDailyConditions(config.selectedLaboratoryId, selectedDate)

  const selectedLab = laboratories.find(
    lab => lab.id === config.selectedLaboratoryId
  )

  const hasConditions =
    dailyCondition && Object.keys(dailyCondition.conditions).length > 0

  // Автоматически обновляем форму при смене даты или загрузке новых условий из БД
  useEffect(() => {
    if (!onChange) return

    const nextConditions = dailyCondition?.conditions || {}
    const currentConditions = value?.conditions || {}
    const shouldUpdateConditions = !isEqual(currentConditions, nextConditions)
    const shouldUpdateDate = value?.date !== selectedDate

    if (shouldUpdateConditions || shouldUpdateDate) {
      onChange({
        date: selectedDate,
        conditions: nextConditions,
      })
    }
  }, [dailyCondition, onChange, selectedDate, value?.conditions, value?.date])

  // Синхронизация selectedDate с внешним value.date
  useEffect(() => {
    if (value?.date && value.date !== selectedDate) {
      setSelectedDate(value.date)
    }
  }, [value?.date, selectedDate])

  // Инициализация значения если оно не установлено
  useEffect(() => {
    if (!value && onChange) {
      onChange({
        date: selectedDate,
        conditions: {},
      })
    }
  }, [value, onChange, selectedDate])

  const handleDateChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const newDate = event.target.value
    setSelectedDate(newDate)

    // Сохранение в localStorage
    if (config.id) {
      const key = getLocalStorageKey('verification_conditions_date', config.id)
      saveToLocalStorage(key, newDate)
    }

    // Обновляем значение даты в value
    if (onChange) {
      onChange({
        date: newDate,
        conditions: value?.conditions || {},
      })
    }
  }

  const handleOpenEditDialog = (isCreating = false) => {
    if (isCreating) {
      const emptyConditions: Record<string, string> = {}
      labData?.conditionTypes.forEach(conditionType => {
        emptyConditions[conditionType.id] = ''
      })
      setEditingConditions(emptyConditions)
    } else {
      setEditingConditions(dailyCondition?.conditions || {})
    }
    setEditDialogOpen(true)
  }

  const handleSaveConditions = async () => {
    if (!config.selectedLaboratoryId || !selectedDate || !labData) return

    try {
      await saveConditions(editingConditions)

      if (onChange) {
        onChange({
          date: selectedDate,
          conditions: editingConditions,
        })
      }

      setEditDialogOpen(false)
    } catch (error) {
      console.error('Ошибка сохранения:', error)
    }
  }

  const handleConditionChange = (conditionId: string, value: string) => {
    setEditingConditions(prev => ({
      ...prev,
      [conditionId]: value,
    }))
  }

  if (!config.selectedLaboratoryId) {
    return (
      <div className="relative">
        <CellsBadge targetCells={config.targetCells || []} />

        <Card className="border-dashed">
          <CardContent className="p-3">
            <div className="text-center text-muted-foreground">
              <Building2 className="mx-auto mb-1 h-4 w-4 opacity-50" />
              <p className="text-xs">Лаборатория не выбрана</p>
            </div>
          </CardContent>
        </Card>
      </div>
    )
  }

  if (!labData) {
    return (
      <div className="relative">
        <CellsBadge targetCells={config.targetCells || []} />

        <Card>
          <CardContent className="p-3">
            <div className="text-center text-muted-foreground">
              <div className="mx-auto mb-1 h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent" />
              <p className="text-xs">Загрузка...</p>
            </div>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="relative">
      {/* Бейдж ячеек */}
      <CellsBadge targetCells={config.targetCells || []} />

      <div className="space-y-2">
        <div className="space-y-2">
          {/* Информация о лаборатории и дате */}
          <div className="flex items-center gap-2 rounded-md bg-muted/20 p-2 text-sm">
            <Building2 className="h-3.5 w-3.5 text-muted-foreground" />
            <span className="font-medium text-muted-foreground">
              {selectedLab?.name || 'Лаборатория'}
            </span>
            <div className="ml-auto flex items-center gap-1 text-xs text-muted-foreground">
              <CalendarIcon className="h-3 w-3" />
              <Input
                type="date"
                value={selectedDate}
                onChange={handleDateChange}
                lang="ru"
                className="h-5 w-auto border-none bg-transparent p-0 text-xs font-normal focus:bg-background"
              />
            </div>
          </div>

          {/* Общий статус с кнопкой настроить */}
          <div className="flex items-center justify-between px-2 text-xs">
            <div className="flex items-center gap-1.5">
              {hasConditions ? (
                <>
                  <CheckCircle className="h-3.5 w-3.5 text-green-600" />
                  <span className="font-medium text-green-600">
                    Данные внесены
                  </span>
                </>
              ) : (
                <>
                  <AlertCircle className="h-3.5 w-3.5 text-orange-600" />
                  <span className="font-medium text-orange-600">
                    Данные не внесены
                  </span>
                </>
              )}
            </div>

            <Dialog open={editDialogOpen} onOpenChange={setEditDialogOpen}>
              <DialogTrigger asChild>
                <Button
                  variant="outline"
                  size="sm"
                  className="h-6 px-2 text-xs"
                  onClick={() => handleOpenEditDialog(!hasConditions)}
                >
                  <Settings className="mr-1 h-3 w-3" />
                  Настроить
                </Button>
              </DialogTrigger>
              <DialogContent className="max-w-sm">
                <DialogHeader>
                  <DialogTitle className="text-base">
                    Условия поверки
                  </DialogTitle>
                </DialogHeader>
                <div className="space-y-3">
                  <div className="space-y-1 text-xs text-muted-foreground">
                    <div>{selectedLab?.name}</div>
                    <div>
                      {new Date(selectedDate).toLocaleDateString('ru-RU')}
                    </div>
                  </div>

                  <div className="space-y-2">
                    {labData.conditionTypes.map(conditionType => (
                      <div key={conditionType.id} className="space-y-1">
                        <Label className="text-xs font-medium">
                          {conditionType.name}
                          {conditionType.unit && (
                            <span className="ml-1 font-normal text-muted-foreground">
                              ({conditionType.unit})
                            </span>
                          )}
                        </Label>
                        <Input
                          value={editingConditions[conditionType.id] || ''}
                          onChange={e =>
                            handleConditionChange(
                              conditionType.id,
                              e.target.value
                            )
                          }
                          placeholder="Значение"
                          className="h-7 text-xs"
                        />
                      </div>
                    ))}
                  </div>

                  <div className="flex gap-2">
                    <Button
                      onClick={handleSaveConditions}
                      disabled={isSaving}
                      size="sm"
                      className="h-7 flex-1 text-xs"
                    >
                      {isSaving ? 'Сохранение...' : 'Сохранить'}
                    </Button>
                    <Button
                      variant="outline"
                      onClick={() => setEditDialogOpen(false)}
                      size="sm"
                      className="h-7 flex-1 text-xs"
                    >
                      Отмена
                    </Button>
                  </div>
                </div>
              </DialogContent>
            </Dialog>
          </div>

          {/* Условия */}
          <div className="space-y-1">
            {labData.conditionTypes.map(conditionType => {
              const conditionValue =
                dailyCondition?.conditions[conditionType.id]

              return (
                <ConditionItem
                  key={conditionType.id}
                  name={conditionType.name}
                  value={conditionValue}
                  unit={conditionType.unit}
                />
              )
            })}
          </div>
        </div>
      </div>
    </div>
  )
}
