import React, { useState, useEffect } from 'react'
import { useAuth } from './auth/AuthContext'
import Toast from './Toast'
import SubmitButton from './SubmitButton'
import DeleteButton from './DeleteButton'
import './ShoppingItemForm.css'

function ShoppingItemForm({ onNavigate, itemId, boardId, previousTab, onSaved }) {
  const { authFetch } = useAuth()
  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [groupName, setGroupName] = useState('')
  const [groupSuggestions, setGroupSuggestions] = useState([])
  const [volumeBase, setVolumeBase] = useState('')
  const [repetitionPeriodValue, setRepetitionPeriodValue] = useState('')
  const [repetitionPeriodType, setRepetitionPeriodType] = useState('day')
  const [loading, setLoading] = useState(false)
  const [loadingItem, setLoadingItem] = useState(false)
  const [isDeleting, setIsDeleting] = useState(false)
  const [toastMessage, setToastMessage] = useState(null)

  const isEdit = !!itemId

  useEffect(() => {
    loadGroupSuggestions()
  }, [])

  useEffect(() => {
    if (itemId) {
      fetchItem()
    }
  }, [itemId])

  const loadGroupSuggestions = async () => {
    try {
      const res = await authFetch('/api/shopping/groups')
      if (res.ok) {
        const data = await res.json()
        setGroupSuggestions(Array.isArray(data) ? data : [])
      }
    } catch (err) {
      console.error('Error loading group suggestions:', err)
    }
  }

  const fetchItem = async () => {
    setLoadingItem(true)
    try {
      const res = await authFetch(`/api/shopping/items/${itemId}`)
      if (res.ok) {
        const data = await res.json()
        setName(data.name)
        setDescription(data.description || '')
        setGroupName(data.group_name || '')
        if (data.volume_base && data.volume_base !== 1) {
          setVolumeBase(data.volume_base.toString())
        }
        if (data.repetition_period) {
          const parts = data.repetition_period.trim().split(/\s+/)
          if (parts.length >= 2) {
            const value = parseInt(parts[0], 10)
            const unit = parts[1].toLowerCase()
            setRepetitionPeriodValue(value.toString())
            // Map PostgreSQL units to our types
            if (unit.startsWith('day')) setRepetitionPeriodType('day')
            else if (unit.startsWith('week') || unit === 'wks' || unit === 'wk') setRepetitionPeriodType('week')
            else if (unit.startsWith('mon')) setRepetitionPeriodType('month')
            else if (unit.startsWith('year') || unit === 'yrs' || unit === 'yr') setRepetitionPeriodType('year')
            else if (unit.startsWith('hour') || unit === 'hrs' || unit === 'hr') setRepetitionPeriodType('hour')
            else if (unit.startsWith('min')) setRepetitionPeriodType('minute')
            // Handle PostgreSQL weeks-as-days: "7 days" -> 1 week
            if (unit.startsWith('day') && value % 7 === 0 && value >= 7) {
              setRepetitionPeriodValue((value / 7).toString())
              setRepetitionPeriodType('week')
            }
          }
        }
      } else {
        setToastMessage({ text: 'Ошибка загрузки товара', type: 'error' })
      }
    } catch (err) {
      setToastMessage({ text: 'Ошибка загрузки', type: 'error' })
    } finally {
      setLoadingItem(false)
    }
  }

  const handleSave = async () => {
    if (!name.trim()) {
      setToastMessage({ text: 'Введите название товара', type: 'error' })
      return
    }

    if (!hasValidPeriod) {
      setToastMessage({ text: 'Укажите период повторения', type: 'error' })
      return
    }

    setLoading(true)
    try {
      let repetitionPeriod = null
      if (repetitionPeriodValue && repetitionPeriodValue.trim() !== '') {
        const val = parseInt(repetitionPeriodValue.trim(), 10)
        if (!isNaN(val) && val > 0) {
          repetitionPeriod = `${val} ${repetitionPeriodType}`
        }
      }

      const vb = volumeBase.trim() ? parseFloat(volumeBase.trim()) : null
      const payload = {
        name: name.trim(),
        description: description.trim() || null,
        group_name: groupName.trim() || null,
        volume_base: vb && vb > 0 ? vb : null,
        repetition_period: repetitionPeriod,
      }

      let url, method
      if (isEdit) {
        url = `/api/shopping/items/${itemId}`
        method = 'PUT'
      } else {
        url = `/api/shopping/boards/${boardId}/items`
        method = 'POST'
      }

      const res = await authFetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      })

      if (res.ok) {
        onSaved?.()
        window.history.back()
      } else {
        const err = await res.json()
        setToastMessage({ text: err.error || 'Ошибка сохранения', type: 'error' })
      }
    } catch (err) {
      setToastMessage({ text: 'Ошибка сохранения', type: 'error' })
    } finally {
      setLoading(false)
    }
  }

  const handleDelete = async () => {
    if (!window.confirm('Удалить товар?')) return

    setIsDeleting(true)
    try {
      const res = await authFetch(`/api/shopping/items/${itemId}`, { method: 'DELETE' })
      if (res.ok) {
        onSaved?.()
        window.history.back()
      } else {
        setToastMessage({ text: 'Ошибка удаления', type: 'error' })
        setIsDeleting(false)
      }
    } catch (err) {
      setToastMessage({ text: 'Ошибка удаления', type: 'error' })
      setIsDeleting(false)
    }
  }

  const handleClose = () => {
    window.history.back()
  }

  const hasValidPeriod = repetitionPeriodValue && repetitionPeriodValue.trim() !== '' && parseInt(repetitionPeriodValue.trim(), 10) > 0

  if (loadingItem) {
    return (
      <div className="shopping-item-form">
        <div className="fixed inset-0 bottom-20 flex justify-center items-center">
          <div className="flex flex-col items-center">
            <div className="w-12 h-12 border-4 border-indigo-200 border-t-indigo-600 rounded-full animate-spin mb-4"></div>
            <div className="text-gray-600 font-medium">Загрузка...</div>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="shopping-item-form">
      <button className="close-x-button" onClick={handleClose}>
        ✕
      </button>

      <h2>{isEdit ? 'Редактировать товар' : 'Новый товар'}</h2>

      <div className="form-card">
        <div className="form-group">
          <label htmlFor="item-name">Название</label>
          <input
            id="item-name"
            type="text"
            className="form-input"
            value={name}
            onChange={e => setName(e.target.value)}
            placeholder="Название товара"
          />
        </div>

        <div className="form-group">
          <label htmlFor="item-description">Описание</label>
          <textarea
            id="item-description"
            className="form-input"
            value={description}
            onChange={e => setDescription(e.target.value)}
            placeholder="Описание товара"
            rows={3}
          />
        </div>

        <div className="form-group">
          <label htmlFor="item-group">Группа</label>
          <input
            id="item-group"
            type="text"
            className="form-input"
            value={groupName}
            onChange={e => setGroupName(e.target.value)}
            placeholder="Группа товара"
            list="shopping-group-suggestions"
          />
          <datalist id="shopping-group-suggestions">
            {groupSuggestions.map((g, i) => (
              <option key={i} value={g} />
            ))}
          </datalist>
        </div>

        <div className="form-group">
          <label htmlFor="item-volume">Объём</label>
          <input
            id="item-volume"
            type="number"
            step="any"
            min="0"
            className="form-input"
            value={volumeBase}
            onChange={e => setVolumeBase(e.target.value)}
            placeholder="1"
          />
        </div>

        <div className="form-group">
          <label htmlFor="item-repetition">Повторения</label>
          <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
            <span className="repetition-label">Хватает на</span>
            <input
              id="item-repetition"
              type="number"
              min="0"
              className="form-input"
              value={repetitionPeriodValue}
              onChange={e => setRepetitionPeriodValue(e.target.value)}
              placeholder="Число"
              style={{ flex: '1' }}
            />
            <select
              value={repetitionPeriodType}
              onChange={e => setRepetitionPeriodType(e.target.value)}
              className="form-input"
              style={{ width: '120px' }}
            >
              <option value="minute">Минута</option>
              <option value="hour">Час</option>
              <option value="day">День</option>
              <option value="week">Неделя</option>
              <option value="month">Месяц</option>
              <option value="year">Год</option>
            </select>
          </div>
        </div>

        <div className="form-actions">
          <SubmitButton
            onClick={handleSave}
            loading={loading}
            disabled={!name.trim() || !hasValidPeriod}
          >
            Сохранить
          </SubmitButton>
          {isEdit && (
            <DeleteButton
              onClick={handleDelete}
              loading={isDeleting}
              disabled={loading}
              title="Удалить товар"
            />
          )}
        </div>
      </div>

      {toastMessage && (
        <Toast
          message={toastMessage.text}
          type={toastMessage.type}
          onClose={() => setToastMessage(null)}
        />
      )}
    </div>
  )
}

export default ShoppingItemForm
