import { useState, useEffect, useRef } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { fetchEquipmentDetail } from '../api/equipment';
import type { EquipmentDetail } from '../types';
import { useCart } from '../store/CartContext';
import ErrorState from '../components/ErrorState';

export default function EquipmentDetail() {
  const { id } = useParams();
  const navigate = useNavigate();
  const { addItemByFields } = useCart();
  const [item, setItem] = useState<EquipmentDetail | null>(null);
  const [pending, setPending] = useState(true);
  const [error, setError] = useState(false);
  const [quantity, setQuantity] = useState(1);
  const [rentalStart, setRentalStart] = useState('');
  const [rentalEnd, setRentalEnd] = useState('');
  const mountedRef = useRef(true);

  useEffect(() => {
    mountedRef.current = true;
    setPending(true);
    setError(false);
    if (id) {
      fetchEquipmentDetail(id).then(data => {
        if (mountedRef.current) { setItem(data); setPending(false); }
      }).catch(() => {
        if (mountedRef.current) { setError(true); setPending(false); }
      });
    }
    return () => { mountedRef.current = false; };
  }, [id]);

  function navigateTo(route: string) {
    navigate(route);
    window.scrollTo(0, 0);
  }

  function addToCart() {
    if (!item) return;
    addItemByFields({
      equipment_id: item.id,
      name: item.name,
      rental_price: null,
      image_url: item.image_url || null,
    });
    navigateTo('/warenkorb');
  }

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <nav className="text-sm mb-6" aria-label="Breadcrumb">
        <Link to="/mietkatalog" style={{ color: 'var(--secondary)' }}>← Zurück zum Katalog</Link>
      </nav>
      {pending && (
        <div className="grid lg:grid-cols-2 gap-8" aria-live="polite" aria-busy="true">
          <div className="hms-skeleton aspect-square rounded-lg"></div>
          <div className="space-y-4">
            <div className="hms-skeleton h-8 w-3/4"></div>
            <div className="hms-skeleton h-4 w-1/4"></div>
            <div className="hms-skeleton h-24 w-full"></div>
            <div className="hms-skeleton h-32 w-full"></div>
            <div className="hms-skeleton h-12 w-full" style={{ borderRadius: 'var(--radius-md)' }}></div>
          </div>
        </div>
      )}
      {error && <ErrorState title="Gerät nicht gefunden" message="Das angeforderte Gerät konnte nicht gefunden werden." onRetry={() => navigateTo('/mietkatalog')} />}
      {!pending && !error && item && (
        <div>
          <div className="grid lg:grid-cols-2 gap-8 lg:gap-12">
            <div className="aspect-square rounded-lg flex items-center justify-center relative overflow-hidden border" style={{ background: 'var(--surface)', borderColor: 'var(--border)' }}>
              {item.image_url ? (
                <img src={item.image_url} alt={item.name} className="absolute inset-0 w-full h-full object-cover" />
              ) : (
                <div className="text-center">
                  <div className="text-8xl mb-2" style={{ color: 'var(--secondary)' }}>📦</div>
                  <div className="text-sm" style={{ color: 'var(--secondary)' }}>Kein Bild verfügbar</div>
                </div>
              )}
              {item.category && <span className="hms-badge hms-badge-primary absolute top-4 left-4 text-sm">{item.category}</span>}
            </div>
            <div>
              <div className="text-sm mb-1" style={{ color: 'var(--secondary)' }}>Artikelnummer: {item.number || item.rentman_id}</div>
              <h1 className="text-2xl sm:text-3xl font-bold mb-2" style={{ color: 'var(--text)' }}>{item.name}</h1>
              {item.brand && <div className="text-sm mb-4" style={{ color: 'var(--text-muted)' }}>Marke: <span className="font-medium" style={{ color: 'var(--text)' }}>{item.brand}</span></div>}
              {item.description && <p className="leading-relaxed mb-6" style={{ color: 'var(--text-muted)' }}>{item.description}</p>}
              {item.specifications && (
                <div className="hms-card p-4 mb-6">
                  <h2 className="text-sm font-semibold mb-3" style={{ color: 'var(--text)' }}>Technische Daten</h2>
                  <dl className="divide-y" style={{ borderColor: 'var(--border)' }}>
                    {Object.entries(item.specifications).map(([key, value]) => (
                      <div key={key} className="flex justify-between py-2 text-sm" style={{ borderColor: 'var(--border)' }}>
                        <dt className="capitalize" style={{ color: 'var(--secondary)' }}>{key.replace(/_/g, ' ')}</dt>
                        <dd className="font-medium text-right" style={{ color: 'var(--text)' }}>{String(value)}</dd>
                      </div>
                    ))}
                  </dl>
                </div>
              )}
              <div className="hms-card p-6">
                <h2 className="text-sm font-semibold mb-4" style={{ color: 'var(--text)' }}>Mietanfrage</h2>
                <div className="grid grid-cols-2 gap-3 mb-4">
                  <div>
                    <label htmlFor="rental-start" className="block text-xs font-medium mb-1" style={{ color: 'var(--secondary)' }}>Mietbeginn</label>
                    <input id="rental-start" value={rentalStart} onChange={e => setRentalStart(e.target.value)} type="date" className="hms-input text-sm" />
                  </div>
                  <div>
                    <label htmlFor="rental-end" className="block text-xs font-medium mb-1" style={{ color: 'var(--secondary)' }}>Mietende</label>
                    <input id="rental-end" value={rentalEnd} onChange={e => setRentalEnd(e.target.value)} type="date" className="hms-input text-sm" />
                  </div>
                </div>
                <div className="mb-4">
                  <label htmlFor="quantity" className="block text-xs font-medium mb-1" style={{ color: 'var(--secondary)' }}>Anzahl</label>
                  <div className="flex items-center gap-3">
                    <button onClick={() => setQuantity(q => Math.max(1, q - 1))} className="hms-btn hms-btn-secondary px-3 py-2" aria-label="Anzahl verringern">−</button>
                    <input id="quantity" value={quantity} onChange={e => setQuantity(Math.max(1, Number(e.target.value)))} type="number" min={1} className="hms-input text-center w-20" aria-label="Anzahl" />
                    <button onClick={() => setQuantity(q => q + 1)} className="hms-btn hms-btn-secondary px-3 py-2" aria-label="Anzahl erhöhen">+</button>
                  </div>
                </div>
                <button onClick={addToCart} className="hms-btn hms-btn-primary w-full py-3 text-base">
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"/></svg>
                  Zur Mietanfrage hinzufügen
                </button>
                <p className="text-xs mt-3 text-center" style={{ color: 'var(--secondary)' }}>Preise auf Anfrage – unverbindliche Mietanfrage</p>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
