import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useCart } from '../store/CartContext';
import EmptyState from '../components/EmptyState';

export default function Warenkorb() {
  const navigate = useNavigate();
  const { items: cartItems, totalCount, removeItem, incrementQuantity, decrementQuantity, clearCart } = useCart();
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [form, setForm] = useState({ name: '', email: '', phone: '', event_date: '', event_location: '', message: '' });
  const [errors, setErrors] = useState<Record<string, string>>({});

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

  function validate(): boolean {
    const e: Record<string, string> = {};
    if (!form.name.trim()) e.name = 'Name ist erforderlich';
    if (!form.email.trim()) e.email = 'E-Mail ist erforderlich';
    else if (!/^\S+@\S+\.\S+$/.test(form.email)) e.email = 'Ungültige E-Mail';
    if (!form.event_date) e.event_date = 'Veranstaltungsdatum erforderlich';
    if (!form.event_location.trim()) e.event_location = 'Veranstaltungsort erforderlich';
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  function submitRequest(e: React.FormEvent) {
    e.preventDefault();
    if (!validate()) return;
    setSubmitting(true);
    setTimeout(() => {
      setSubmitting(false);
      setSubmitted(true);
      clearCart();
    }, 1800);
  }

  return (
    <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <h1 className="text-3xl sm:text-4xl font-bold mb-2" style={{ color: 'var(--text)' }}>Mietanfrage</h1>
      <p className="mb-8" style={{ color: 'var(--secondary)' }}>Überprüfen Sie Ihre Geräteauswahl und senden Sie die Anfrage ab.</p>
      {submitted ? (
        <div className="hms-card p-8 text-center" role="status">
          <div className="inline-flex items-center justify-center w-16 h-16 rounded-full mb-4" style={{ background: 'var(--color-success-bg)', color: 'var(--color-success)' }}>
            <svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7"/></svg>
          </div>
          <h2 className="text-xl font-semibold mb-2" style={{ color: 'var(--text)' }}>Mietanfrage übermittelt</h2>
          <p className="mb-6" style={{ color: 'var(--secondary)' }}>Vielen Dank! Wir melden uns innerhalb von 24 Stunden mit einem unverbindlichen Angebot.</p>
          <div className="flex flex-col sm:flex-row gap-4 justify-center">
            <button onClick={() => navigateTo('/mietkatalog')} className="hms-btn hms-btn-secondary">Weiter stöbern</button>
            <button onClick={() => navigateTo('/')} className="hms-btn hms-btn-primary">Zur Startseite</button>
          </div>
        </div>
      ) : cartItems.length === 0 ? (
        <EmptyState icon="🛒" title="Warenkorb ist leer" message="Fügen Sie Geräte aus dem Mietkatalog hinzu, um eine Mietanfrage zu stellen." actionLabel="Zum Mietkatalog" onAction={() => navigateTo('/mietkatalog')} />
      ) : (
        <div className="grid lg:grid-cols-3 gap-8">
          <div className="lg:col-span-2 space-y-4">
            {cartItems.map((item, index) => (
              <div key={index} className="hms-card p-4 sm:p-6">
                <div className="flex gap-4">
                  <div className="w-20 h-20 rounded-lg flex items-center justify-center flex-shrink-0 text-2xl" style={{ background: 'var(--surface)', color: 'var(--secondary)' }}>📦</div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-start justify-between gap-2">
                      <div>
                        <h3 className="font-semibold text-sm sm:text-base" style={{ color: 'var(--text)' }}>{item.name}</h3>
                        <div className="text-xs mt-0.5" style={{ color: 'var(--secondary)' }}>{item.equipment_id}</div>
                      </div>
                      <button onClick={() => removeItem(item.equipment_id)} className="p-1" style={{ color: 'var(--secondary)' }} aria-label={item.name + ' entfernen'}>
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                      </button>
                    </div>
                    <div className="flex flex-wrap items-center gap-3 mt-3">
                      <div className="flex items-center gap-2">
                        <button onClick={() => decrementQuantity(item.equipment_id)} className="w-7 h-7 rounded border flex items-center justify-center" style={{ borderColor: 'var(--border-strong)', color: 'var(--text-muted)' }} aria-label="Anzahl verringern">−</button>
                        <span className="w-8 text-center text-sm font-medium" style={{ color: 'var(--text)' }}>{item.quantity}</span>
                        <button onClick={() => incrementQuantity(item.equipment_id)} className="w-7 h-7 rounded border flex items-center justify-center" style={{ borderColor: 'var(--border-strong)', color: 'var(--text-muted)' }} aria-label="Anzahl erhöhen">+</button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            ))}
            <button onClick={clearCart} className="text-sm hover:text-[var(--color-error)]" style={{ color: 'var(--secondary)' }}>Warenkorb leeren</button>
          </div>
          <div>
            <div className="hms-card p-6 sticky top-20">
              <h2 className="text-lg font-semibold mb-4" style={{ color: 'var(--text)' }}>Anfrage senden</h2>
              <div className="text-sm mb-4 pb-4 border-b" style={{ borderColor: 'var(--border)', color: 'var(--secondary)' }}>
                <div className="flex justify-between mb-1"><span>Geräte gesamt:</span><span className="font-medium" style={{ color: 'var(--text)' }}>{totalCount}</span></div>
                <div className="flex justify-between"><span>Positionen:</span><span className="font-medium" style={{ color: 'var(--text)' }}>{cartItems.length}</span></div>
              </div>
              <form onSubmit={submitRequest} noValidate>
                <div className="space-y-3">
                  <div>
                    <label htmlFor="req-name" className="block text-xs font-medium mb-1" style={{ color: 'var(--secondary)' }}>Name <span style={{ color: 'var(--color-error)' }}>*</span></label>
                    <input id="req-name" value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} type="text" className={`hms-input text-sm ${errors.name ? 'hms-input-error' : ''}`} placeholder="Ihr Name" />
                    {errors.name && <p className="text-xs mt-1" style={{ color: 'var(--color-error)' }}>{errors.name}</p>}
                  </div>
                  <div>
                    <label htmlFor="req-email" className="block text-xs font-medium mb-1" style={{ color: 'var(--secondary)' }}>E-Mail <span style={{ color: 'var(--color-error)' }}>*</span></label>
                    <input id="req-email" value={form.email} onChange={e => setForm(f => ({ ...f, email: e.target.value }))} type="email" className={`hms-input text-sm ${errors.email ? 'hms-input-error' : ''}`} placeholder="ihre@email.de" />
                    {errors.email && <p className="text-xs mt-1" style={{ color: 'var(--color-error)' }}>{errors.email}</p>}
                  </div>
                  <div>
                    <label htmlFor="req-phone" className="block text-xs font-medium mb-1" style={{ color: 'var(--secondary)' }}>Telefon</label>
                    <input id="req-phone" value={form.phone} onChange={e => setForm(f => ({ ...f, phone: e.target.value }))} type="tel" className="hms-input text-sm" placeholder="+49 ..." />
                  </div>
                  <div>
                    <label htmlFor="req-date" className="block text-xs font-medium mb-1" style={{ color: 'var(--secondary)' }}>Veranstaltungsdatum <span style={{ color: 'var(--color-error)' }}>*</span></label>
                    <input id="req-date" value={form.event_date} onChange={e => setForm(f => ({ ...f, event_date: e.target.value }))} type="date" className={`hms-input text-sm ${errors.event_date ? 'hms-input-error' : ''}`} />
                    {errors.event_date && <p className="text-xs mt-1" style={{ color: 'var(--color-error)' }}>{errors.event_date}</p>}
                  </div>
                  <div>
                    <label htmlFor="req-location" className="block text-xs font-medium mb-1" style={{ color: 'var(--secondary)' }}>Veranstaltungsort <span style={{ color: 'var(--color-error)' }}>*</span></label>
                    <input id="req-location" value={form.event_location} onChange={e => setForm(f => ({ ...f, event_location: e.target.value }))} type="text" className={`hms-input text-sm ${errors.event_location ? 'hms-input-error' : ''}`} placeholder="Ort / Location" />
                    {errors.event_location && <p className="text-xs mt-1" style={{ color: 'var(--color-error)' }}>{errors.event_location}</p>}
                  </div>
                  <div>
                    <label htmlFor="req-message" className="block text-xs font-medium mb-1" style={{ color: 'var(--secondary)' }}>Anmerkung</label>
                    <textarea id="req-message" value={form.message} onChange={e => setForm(f => ({ ...f, message: e.target.value }))} rows={3} className="hms-input text-sm" placeholder="Zusätzliche Informationen..." />
                  </div>
                  <button type="submit" disabled={submitting} className="hms-btn hms-btn-primary w-full py-3">
                    {submitting ? <span className="hms-spinner" style={{ width: 18, height: 18, borderWidth: 2 }} /> : <span>Anfrage absenden</span>}
                  </button>
                  <p className="text-xs text-center" style={{ color: 'var(--secondary)' }}>Unverbindlich – Angebot innerhalb 24 Std.</p>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
