import React, { useState, useEffect, useCallback } from 'react'
import { useAuth } from './auth/AuthContext'
import LoadingError from './LoadingError'
import Toast from './Toast'
import './Integrations.css'

function ShoppingItemHistory({ itemId, onNavigate }) {
  const { authFetch } = useAuth()
  const [history, setHistory] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  const [toastMessage, setToastMessage] = useState(null)
  const [deletingId, setDeletingId] = useState(null)

  const fetchHistory = useCallback(async () => {
    if (!itemId) return
    try {
      setLoading(true)
      setError(null)
      const response = await authFetch(`/api/shopping/items/${itemId}/history`)
      if (!response.ok) {
        throw new Error('Ошибка загрузки истории')
      }
      const data = await response.json()
      setHistory(Array.isArray(data) ? data : [])
    } catch (err) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }, [itemId, authFetch])

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

  const handleDelete = async (historyId) => {
    setDeletingId(historyId)
    try {
      const response = await authFetch(`/api/shopping/history/${historyId}`, {
        method: 'DELETE',
      })
      if (!response.ok) {
        throw new Error('Ошибка удаления')
      }
      setHistory(prev => prev.filter(entry => entry.id !== historyId))
      setToastMessage({ text: 'Запись удалена', type: 'success' })
    } catch (err) {
      setToastMessage({ text: err.message || 'Ошибка', type: 'error' })
    } finally {
      setDeletingId(null)
    }
  }

  const formatDate = (dateStr) => {
    const date = new Date(dateStr)
    const day = date.getDate()
    const months = ['янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек']
    const month = months[date.getMonth()]
    const year = date.getFullYear()
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${day} ${month} ${year}, ${hours}:${minutes}`
  }

  const formatVolume = (volume) => {
    if (volume === 1) return '1'
    const rounded = Math.round(volume * 10000) / 10000
    return rounded.toString()
  }

  return (
    <div className="max-w-2xl mx-auto">
      {onNavigate && (
        <button
          onClick={() => window.history.back()}
          className="close-x-button"
          title="Закрыть"
        >
          ✕
        </button>
      )}

      {loading ? (
        <div className="fixed inset-0 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>
      ) : error ? (
        <LoadingError onRetry={fetchHistory} />
      ) : history.length === 0 ? (
        <>
          <h2 className="text-2xl font-semibold text-gray-800 mb-6" style={{ marginTop: '1.25rem' }}>История покупок</h2>
          <div className="flex justify-center items-center py-16">
            <div className="text-gray-500 text-lg">История пуста</div>
          </div>
        </>
      ) : (
        <div>
          <h2 className="text-2xl font-semibold text-gray-800 mb-6" style={{ marginTop: '1.25rem' }}>История покупок</h2>
          <div className="space-y-3">
            {history.map((entry) => (
              <div
                key={entry.id}
                className="bg-white rounded-lg p-4 shadow-sm border border-gray-200 relative"
              >
                <button
                  onClick={() => handleDelete(entry.id)}
                  disabled={deletingId === entry.id}
                  className="absolute top-4 right-4"
                  style={{
                    color: '#6b7280',
                    background: 'none',
                    border: 'none',
                    cursor: 'pointer',
                    padding: '0.25rem',
                    borderRadius: '0.25rem',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    width: '24px',
                    height: '24px',
                    transition: 'all 0.2s',
                    opacity: deletingId === entry.id ? 0.5 : 1,
                    zIndex: 10
                  }}
                  onMouseEnter={(e) => {
                    if (deletingId !== entry.id) {
                      e.currentTarget.style.backgroundColor = '#f3f4f6'
                      e.currentTarget.style.color = '#1f2937'
                    }
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.backgroundColor = 'transparent'
                    e.currentTarget.style.color = '#6b7280'
                  }}
                  title="Удалить"
                >
                  {deletingId === entry.id ? (
                    <svg className="w-5 h-5 animate-spin" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                      <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                      <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                  ) : (
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M3 6h18"></path>
                      <path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"></path>
                      <path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"></path>
                    </svg>
                  )}
                </button>
                <div className="text-gray-800 pr-8">
                  {entry.name}
                </div>
                <div className="text-gray-800 font-semibold mt-1">
                  Объём: {formatVolume(entry.volume)}
                </div>
                <div className="text-xs text-gray-500 mt-2">
                  {formatDate(entry.completed_at)}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

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

export default ShoppingItemHistory
