import { useState } from 'react';
import {
  useTradeEvents,
  useCreateTradeEvent,
  useUpdateTradeEvent,
  useDeleteTradeEvent,
} from '../crm/hooks';
import type { TradeEvent, CreateTradeEventPayload, UpdateTradeEventPayload } from '../crm/types';
import styles from './AdminEventsPage.module.css';

// ============================================================
//  Helpers
// ============================================================

function formatDateDE(iso: string): string {
  return new Date(iso).toLocaleDateString('de-DE', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
  });
}

/** ISO date string → "YYYY-MM-DD" for <input type="date"> */
function toInputDate(iso: string): string {
  return iso.slice(0, 10);
}

function eventStatus(event: TradeEvent): 'upcoming' | 'ongoing' | 'ended' {
  const now = new Date();
  const start = new Date(event.startDate);
  const end = new Date(event.endDate);
  // Set end to end of day
  end.setHours(23, 59, 59, 999);
  if (now < start) return 'upcoming';
  if (now <= end) return 'ongoing';
  return 'ended';
}

// ============================================================
//  Event Form Modal
// ============================================================

interface EventFormModalProps {
  event?: TradeEvent | null;
  onClose: () => void;
  onSave: (data: CreateTradeEventPayload | UpdateTradeEventPayload) => void;
  isSaving: boolean;
}

function EventFormModal({ event, onClose, onSave, isSaving }: EventFormModalProps) {
  const [name, setName] = useState(event?.name ?? '');
  const [description, setDescription] = useState(event?.description ?? '');
  const [startDate, setStartDate] = useState(
    event?.startDate ? toInputDate(event.startDate) : '',
  );
  const [endDate, setEndDate] = useState(
    event?.endDate ? toInputDate(event.endDate) : '',
  );
  const [location, setLocation] = useState(event?.location ?? '');
  const [boothInfo, setBoothInfo] = useState(event?.boothInfo ?? '');
  const [websiteUrl, setWebsiteUrl] = useState(event?.websiteUrl ?? '');
  const [isActive, setIsActive] = useState(event?.isActive ?? true);
  const [sortOrder, setSortOrder] = useState(event?.sortOrder ?? 0);
  const [error, setError] = useState('');

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    if (!name.trim()) {
      setError('Name ist erforderlich');
      return;
    }
    if (!startDate || !endDate) {
      setError('Start- und Enddatum sind erforderlich');
      return;
    }
    if (new Date(endDate) < new Date(startDate)) {
      setError('Enddatum darf nicht vor dem Startdatum liegen');
      return;
    }

    const payload: CreateTradeEventPayload = {
      name: name.trim(),
      description: description.trim() || undefined,
      startDate: new Date(startDate).toISOString(),
      endDate: new Date(endDate).toISOString(),
      location: location.trim() || undefined,
      boothInfo: boothInfo.trim() || undefined,
      websiteUrl: websiteUrl.trim() || undefined,
      isActive,
      sortOrder,
    };

    onSave(payload);
  };

  return (
    <div className={styles.overlay} onClick={onClose}>
      <div className={styles.modal} onClick={(e) => e.stopPropagation()}>
        <div className={styles.modalHeader}>
          <h2 className={styles.modalTitle}>
            {event ? 'Event bearbeiten' : 'Neues Event erstellen'}
          </h2>
          <button className={styles.closeBtn} onClick={onClose}>
            <svg width="18" height="18" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
              <path d="M4 4l8 8M12 4l-8 8" />
            </svg>
          </button>
        </div>

        <form onSubmit={handleSubmit} className={styles.form}>
          {error && <div className={styles.formError}>{error}</div>}

          <div className={styles.fieldGroup}>
            <label className={styles.label}>Name *</label>
            <input
              type="text"
              className={styles.input}
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="z.B. LogiMAT 2026"
              maxLength={200}
              autoFocus
            />
          </div>

          <div className={styles.fieldGroup}>
            <label className={styles.label}>Beschreibung</label>
            <textarea
              className={styles.textarea}
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Optionale Beschreibung..."
              rows={2}
              maxLength={2000}
            />
          </div>

          <div className={styles.fieldRow}>
            <div className={styles.fieldGroup}>
              <label className={styles.label}>Startdatum *</label>
              <input
                type="date"
                className={styles.input}
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
              />
            </div>
            <div className={styles.fieldGroup}>
              <label className={styles.label}>Enddatum *</label>
              <input
                type="date"
                className={styles.input}
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
              />
            </div>
          </div>

          <div className={styles.fieldRow}>
            <div className={styles.fieldGroup}>
              <label className={styles.label}>Standort</label>
              <input
                type="text"
                className={styles.input}
                value={location}
                onChange={(e) => setLocation(e.target.value)}
                placeholder="z.B. Stuttgart"
                maxLength={300}
              />
            </div>
            <div className={styles.fieldGroup}>
              <label className={styles.label}>Halle / Stand</label>
              <input
                type="text"
                className={styles.input}
                value={boothInfo}
                onChange={(e) => setBoothInfo(e.target.value)}
                placeholder="z.B. Halle 7, Stand B42"
                maxLength={200}
              />
            </div>
          </div>

          <div className={styles.fieldGroup}>
            <label className={styles.label}>Website</label>
            <input
              type="url"
              className={styles.input}
              value={websiteUrl}
              onChange={(e) => setWebsiteUrl(e.target.value)}
              placeholder="https://..."
              maxLength={500}
            />
          </div>

          <div className={styles.fieldRow}>
            <div className={styles.fieldGroup}>
              <label className={styles.label}>Sortierung</label>
              <input
                type="number"
                className={styles.input}
                value={sortOrder}
                onChange={(e) => setSortOrder(parseInt(e.target.value, 10) || 0)}
                min={0}
                style={{ width: 100 }}
              />
            </div>
            <div className={styles.fieldGroup}>
              <label className={styles.toggleLabel}>
                <input
                  type="checkbox"
                  checked={isActive}
                  onChange={(e) => setIsActive(e.target.checked)}
                />
                <span>Auf Dashboard anzeigen</span>
              </label>
            </div>
          </div>

          <div className={styles.modalActions}>
            <button type="button" className={styles.btnSecondary} onClick={onClose}>
              Abbrechen
            </button>
            <button type="submit" className={styles.btnPrimary} disabled={isSaving}>
              {isSaving ? 'Speichern...' : event ? 'Aktualisieren' : 'Erstellen'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ============================================================
//  Delete Confirmation Modal
// ============================================================

function DeleteConfirmModal({
  eventName,
  onClose,
  onConfirm,
  isDeleting,
}: {
  eventName: string;
  onClose: () => void;
  onConfirm: () => void;
  isDeleting: boolean;
}) {
  return (
    <div className={styles.overlay} onClick={onClose}>
      <div
        className={styles.modal}
        style={{ maxWidth: 420 }}
        onClick={(e) => e.stopPropagation()}
      >
        <div className={styles.modalHeader}>
          <h2 className={styles.modalTitle}>Event loeschen</h2>
          <button className={styles.closeBtn} onClick={onClose}>
            <svg width="18" height="18" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
              <path d="M4 4l8 8M12 4l-8 8" />
            </svg>
          </button>
        </div>
        <p className={styles.deleteText}>
          Soll das Event <strong>{eventName}</strong> wirklich geloescht werden?
          Diese Aktion kann nicht rueckgaengig gemacht werden.
        </p>
        <div className={styles.modalActions}>
          <button className={styles.btnSecondary} onClick={onClose}>
            Abbrechen
          </button>
          <button
            className={styles.btnDanger}
            onClick={onConfirm}
            disabled={isDeleting}
          >
            {isDeleting ? 'Loeschen...' : 'Endgueltig loeschen'}
          </button>
        </div>
      </div>
    </div>
  );
}

// ============================================================
//  AdminEventsPage — Main Component
// ============================================================

export function AdminEventsPage() {
  const { data, isLoading } = useTradeEvents();
  const createEvent = useCreateTradeEvent();
  const updateEvent = useUpdateTradeEvent();
  const deleteEvent = useDeleteTradeEvent();

  const [editingEvent, setEditingEvent] = useState<TradeEvent | null>(null);
  const [isCreating, setIsCreating] = useState(false);
  const [deletingEvent, setDeletingEvent] = useState<TradeEvent | null>(null);

  const events: TradeEvent[] = data?.data ?? [];

  const handleCreate = (payload: CreateTradeEventPayload | UpdateTradeEventPayload) => {
    createEvent.mutate(payload as CreateTradeEventPayload, {
      onSuccess: () => setIsCreating(false),
    });
  };

  const handleUpdate = (payload: CreateTradeEventPayload | UpdateTradeEventPayload) => {
    if (!editingEvent) return;
    updateEvent.mutate(
      { id: editingEvent.id, data: payload as UpdateTradeEventPayload },
      { onSuccess: () => setEditingEvent(null) },
    );
  };

  const handleDelete = () => {
    if (!deletingEvent) return;
    deleteEvent.mutate(deletingEvent.id, {
      onSuccess: () => setDeletingEvent(null),
    });
  };

  return (
    <div>
      <div className={styles.pageHeader}>
        <div>
          <h1 className={styles.pageTitle}>Messe-Events</h1>
          <p className={styles.pageSubtitle}>
            Verwalten Sie Messen und Veranstaltungen. Aktive Events werden als
            Countdown-Kacheln auf dem Dashboard angezeigt.
          </p>
        </div>
        <button className={styles.btnPrimary} onClick={() => setIsCreating(true)}>
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
            <path d="M8 3v10M3 8h10" />
          </svg>
          Neues Event
        </button>
      </div>

      {isLoading ? (
        <p className={styles.loadingText}>Events werden geladen...</p>
      ) : events.length === 0 ? (
        <div className={styles.emptyState}>
          <svg width="40" height="40" viewBox="0 0 16 16" fill="none" stroke="var(--color-text-muted)" strokeWidth="1" strokeLinecap="round">
            <rect x="2" y="3" width="12" height="11" rx="1" />
            <path d="M5 1v4M11 1v4M2 7h12" />
          </svg>
          <p>Noch keine Events vorhanden</p>
          <button className={styles.btnPrimary} onClick={() => setIsCreating(true)}>
            Erstes Event erstellen
          </button>
        </div>
      ) : (
        <div className={styles.tableCard}>
          <table className={styles.table}>
            <thead>
              <tr>
                <th>Name</th>
                <th>Zeitraum</th>
                <th>Ort / Stand</th>
                <th>Status</th>
                <th>Dashboard</th>
                <th style={{ width: 100 }}>Aktionen</th>
              </tr>
            </thead>
            <tbody>
              {events.map((ev) => {
                const status = eventStatus(ev);
                return (
                  <tr key={ev.id}>
                    <td className={styles.nameCell}>
                      <span className={styles.eventName}>{ev.name}</span>
                      {ev.websiteUrl && (
                        <a
                          href={ev.websiteUrl}
                          target="_blank"
                          rel="noopener noreferrer"
                          className={styles.websiteLink}
                        >
                          Website
                        </a>
                      )}
                    </td>
                    <td className={styles.dateCell}>
                      {formatDateDE(ev.startDate)} – {formatDateDE(ev.endDate)}
                    </td>
                    <td>
                      {ev.location && (
                        <span className={styles.locationText}>{ev.location}</span>
                      )}
                      {ev.boothInfo && (
                        <span className={styles.boothText}>{ev.boothInfo}</span>
                      )}
                      {!ev.location && !ev.boothInfo && '—'}
                    </td>
                    <td>
                      <span className={`${styles.statusBadge} ${styles[`status_${status}`]}`}>
                        {status === 'upcoming'
                          ? 'Bevorstehend'
                          : status === 'ongoing'
                            ? 'Laeuft'
                            : 'Beendet'}
                      </span>
                    </td>
                    <td>
                      <span
                        className={`${styles.activeBadge} ${
                          ev.isActive ? styles.activeYes : styles.activeNo
                        }`}
                      >
                        {ev.isActive ? 'Aktiv' : 'Inaktiv'}
                      </span>
                    </td>
                    <td>
                      <div className={styles.actionBtns}>
                        <button
                          className={styles.iconBtn}
                          title="Bearbeiten"
                          onClick={() => setEditingEvent(ev)}
                        >
                          <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                            <path d="M11.5 1.5l3 3L5 14H2v-3L11.5 1.5z" />
                          </svg>
                        </button>
                        <button
                          className={`${styles.iconBtn} ${styles.iconBtnDanger}`}
                          title="Loeschen"
                          onClick={() => setDeletingEvent(ev)}
                        >
                          <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                            <path d="M3 4h10M5 4V3a1 1 0 011-1h4a1 1 0 011 1v1M6 7v5M10 7v5M4 4l1 9a1 1 0 001 1h4a1 1 0 001-1l1-9" />
                          </svg>
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {/* Create Modal */}
      {isCreating && (
        <EventFormModal
          onClose={() => setIsCreating(false)}
          onSave={handleCreate}
          isSaving={createEvent.isPending}
        />
      )}

      {/* Edit Modal */}
      {editingEvent && (
        <EventFormModal
          event={editingEvent}
          onClose={() => setEditingEvent(null)}
          onSave={handleUpdate}
          isSaving={updateEvent.isPending}
        />
      )}

      {/* Delete Confirmation */}
      {deletingEvent && (
        <DeleteConfirmModal
          eventName={deletingEvent.name}
          onClose={() => setDeletingEvent(null)}
          onConfirm={handleDelete}
          isDeleting={deleteEvent.isPending}
        />
      )}
    </div>
  );
}
