import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { CalendarCheck2, CalendarDays, Megaphone, Users } from 'lucide-react';
import { createEvent, fetchEventById, updateEvent, getEventInfoFromUrl, generateCollabLink, updateArtistCollabDataByOp } from '@/features/event/api/eventService';
import { useApiFetch } from '@/utils/apiFetch';
import { useIsMobile } from '@/hooks/use-mobile';
import EventStammdatenSection from '@/features/event/components/EventStammdatenSection';
import PromotionTemplatesSection from '@/features/event/components/PromotionTemplatesSection';
import ArtistsSection from '@/features/event/components/ArtistsSection';
import ScheduleSection from '@/features/event/components/ScheduleSection';

interface EventFormInlineProps {
  onSuccess: () => void;
  onCancel?: () => void;
  mode?: 'create' | 'edit';
  eventId?: string | number | null;
}

const initialForm = {
  name: '',
  description: '',
  begin_date: '',
  mediaUrl: '',
  ticketUrl: '',
  admissionTimes: '',
  ticketPrice: '',
};

const INITIAL_ARTISTS = 4;

const EventFormInline: React.FC<EventFormInlineProps> = ({ onSuccess, onCancel, mode = 'create', eventId }) => {
  const [form, setForm] = useState(initialForm);
  const [mediaPreview, setMediaPreview] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const fileInputRef = React.useRef<HTMLInputElement>(null);
  const [promotionStartDate, setPromotionStartDate] = useState<string>('');
  const [sectionDates, setSectionDates] = useState<string[]>(() => Array(INITIAL_ARTISTS + 1).fill(''));
  const [artistSections, setArtistSections] = useState(
    Array.from({ length: INITIAL_ARTISTS }, () => ({
      name: '',
      email: '',
      link: '',
      status: 'Wartet auf Künstler' as 'Wartet auf Künstler' | 'Link generiert' | 'Fertig' | 'Künstler einladen',
    }))
  );
  const [promotionSlots, setPromotionSlots] = useState<any[] | null>(null);
  const [previewSlot, setPreviewSlot] = useState<any | null>(null);
  const [previewDraft, setPreviewDraft] = useState<any | null>(null);
  const [isPreviewOpen, setIsPreviewOpen] = useState(false);
  const [isPreviewEditing, setIsPreviewEditing] = useState(false);
  const [savingPreview, setSavingPreview] = useState(false);
  const beginDateRef = React.useRef<HTMLInputElement | null>(null);
  const promotionStartRef = React.useRef<HTMLInputElement | null>(null);
  const sectionDateRefs = React.useRef<Array<HTMLInputElement | null>>([]);
  const apiFetch = useApiFetch();
  const [loadingInitial, setLoadingInitial] = useState(false);
  const [extractingFromUrl, setExtractingFromUrl] = useState(false);
  const [promotionOffsetDays, setPromotionOffsetDays] = useState<string>('2');
  const [generatingLinkIndex, setGeneratingLinkIndex] = useState<number | null>(null);
  const isMobile = useIsMobile();
  const [activeTab, setActiveTab] = useState<'stammdaten' | 'promotion' | 'artists' | 'schedule'>('stammdaten');
  const navExpanded = !isMobile;

  const initialSnapshotRef = useRef<string | null>(null);
  const [isDirty, setIsDirty] = useState(false);

  const currentSnapshot = useMemo(() => {
    return JSON.stringify({
      form,
      promotionStartDate,
      promotionOffsetDays,
      sectionDates,
      artistSections,
    });
  }, [artistSections, form, promotionOffsetDays, promotionStartDate, sectionDates]);

  useEffect(() => {
    if (initialSnapshotRef.current === null) return;
    setIsDirty(initialSnapshotRef.current !== currentSnapshot);
  }, [currentSnapshot]);

  useEffect(() => {
    if (!isDirty) return;
    const handler = (e: BeforeUnloadEvent) => {
      e.preventDefault();
      e.returnValue = '';
    };
    window.addEventListener('beforeunload', handler);
    return () => window.removeEventListener('beforeunload', handler);
  }, [isDirty]);

  useEffect(() => {
    return () => {
      setForm(initialForm);
      setError(null);
    };
  }, []);

  useEffect(() => {
    // establish baseline snapshot for create mode immediately
    if (mode !== 'create') return;
    if (initialSnapshotRef.current !== null) return;
    initialSnapshotRef.current = currentSnapshot;
  }, [currentSnapshot, mode]);

  useEffect(() => {
    // establish baseline snapshot for edit mode after initial load finished
    if (mode !== 'edit') return;
    if (loadingInitial) return;
    if (initialSnapshotRef.current !== null) return;
    initialSnapshotRef.current = currentSnapshot;
    setIsDirty(false);
  }, [currentSnapshot, loadingInitial, mode]);

  useEffect(() => {
    if (mode !== 'edit' || !eventId) return;

    let cancelled = false;

    const load = async () => {
      setLoadingInitial(true);
      try {
        const detail = await fetchEventById(apiFetch, eventId);
        if (cancelled) return;

        setForm({
          name: detail.title || '',
          description: detail.description || '',
          begin_date: detail.eventDate || '',
          mediaUrl: detail.coverMediaUrl || '',
          ticketUrl: (detail as any).ticketUrl || '',
          admissionTimes: (detail as any).admissionTimes || '',
          ticketPrice: (detail as any).ticketPrice || '',
        });

        const start = detail.promotionStartDate || '';
        setPromotionStartDate(start);

        const slots = detail.promotionSlots || [];
        setPromotionSlots(slots);

        const section1 = slots.find((s) => s.slotIndex === 1);

        const artistSlots = slots
          .filter((s) => s.slotIndex && s.slotIndex >= 2)
          .sort((a, b) => (a.slotIndex || 0) - (b.slotIndex || 0));

        const artistCount = Math.max(artistSlots.length || INITIAL_ARTISTS, 1);

        const dates = Array(artistCount + 1).fill('');
        const artists = Array.from({ length: artistCount }, () => ({
          name: '',
          email: '',
          link: '',
          status: 'Wartet auf Künstler' as 'Wartet auf Künstler' | 'Link generiert' | 'Fertig' | 'Künstler einladen',
        }));

        dates[0] = section1?.promoDate || start;

        artistSlots.forEach((slot, idx) => {
          artists[idx] = {
            name: slot.artistName || '',
            email: (slot as any).artistEmail || '',
            link: (slot as any).artistLink || '',
            status: (slot as any).artistStatus || 'Wartet auf Künstler',
          };
          dates[idx + 1] = slot.promoDate || '';

          const collabUrl = (slot as any).collabUrl || (slot as any).collab_url;
          const collabToken = (slot as any).collabToken || (slot as any).collab_token;
          if (collabUrl) {
            artists[idx].link = collabUrl;
          } else if (collabToken) {
            artists[idx].link = `/collab/${collabToken}`;
          }
        });

        setSectionDates(dates);
        setArtistSections(artists);

        // reset baseline so it can be re-established after all state updates
        initialSnapshotRef.current = null;
        setIsDirty(false);
      } catch (err) {
        console.error('Error loading event details', err);
        setError('Event konnte nicht geladen werden');
      } finally {
        if (!cancelled) setLoadingInitial(false);
      }
    };

    load();

    return () => {
      cancelled = true;
    };
  }, [mode, eventId, apiFetch]);

  const handleInput = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setForm({ ...form, [e.target.name]: e.target.value });
  };

  const formatDateForInput = (date: Date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  const formatDateForDisplay = (iso: string) => {
    if (!iso) return '';
    const d = new Date(iso);
    if (Number.isNaN(d.getTime())) return '';
    const day = String(d.getDate()).padStart(2, '0');
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const year = d.getFullYear();
    return `${day}.${month}.${year}`;
  };

  const recalcPromotionDatesFromEvent = () => {
    if (!form.begin_date) return;

    const eventDate = new Date(form.begin_date);
    if (Number.isNaN(eventDate.getTime())) return;

    const today = new Date();
    today.setHours(0, 0, 0, 0);

    const eventMidnight = new Date(eventDate);
    eventMidnight.setHours(0, 0, 0, 0);

    // Wenn Event heute oder in der Vergangenheit liegt, keine Promotion mehr möglich
    if (eventMidnight.getTime() <= today.getTime()) {
      setError('Promotion-Zeitraum ist bereits vorbei.');
      return;
    }

    const offset = parseInt(promotionOffsetDays || '0', 10);
    const safeOffset = Number.isNaN(offset) || offset < 1 ? 2 : offset;

    // Kandidat für letzten Promotion-Tag: event - offset Tage, aber strikt vor dem Event
    const last = new Date(eventMidnight);
    last.setDate(last.getDate() - safeOffset);

    // Falls der Offset zu groß ist und nach dem Event landet, auf Tag vor Event begrenzen
    if (last.getTime() >= eventMidnight.getTime()) {
      last.setDate(eventMidnight.getDate() - 1);
    }

    // Mindestens heute, wir können nicht in die Vergangenheit posten
    if (last.getTime() < today.getTime()) {
      last.setTime(today.getTime());
    }

    // Wenn selbst der letzte Slot nicht mehr vor dem Event liegt, ist die Promotionzeit vorbei
    if (last.getTime() >= eventMidnight.getTime()) {
      setError('Promotion-Zeitraum ist bereits vorbei.');
      return;
    }

    const slotCount = artistSections.length + 1;
    const slotDates: Date[] = new Array(slotCount);

    // Von hinten nach vorne füllen: letzter Slot = letzter Tag, davor jeweils max(heute, Vortag)
    slotDates[slotCount - 1] = new Date(last);
    for (let i = slotCount - 2; i >= 0; i--) {
      const d = new Date(slotDates[i + 1]);
      d.setDate(d.getDate() - 1);
      if (d.getTime() < today.getTime()) {
        d.setTime(today.getTime());
      }
      slotDates[i] = d;
    }

    // Slot 1 (Index 0) ist das Promotion-Startdatum
    const startIso = formatDateForInput(slotDates[0]);
    const sectionIso = slotDates.map((d) => formatDateForInput(d));

    setPromotionStartDate(startIso);
    setSectionDates(sectionIso);
  };

  const handlePromotionStartChange = (iso: string) => {
    setPromotionStartDate(iso);

    if (!iso) {
      setSectionDates(['', '', '', '', '']);
      return;
    }

    const base = new Date(iso);
    if (Number.isNaN(base.getTime())) {
      setSectionDates(['', '', '', '', '']);
      return;
    }

    const count = artistSections.length + 1;
    const isoDates: string[] = [];
    for (let idx = 0; idx < count; idx++) {
      const d = new Date(base);
      d.setDate(d.getDate() + idx);
      const isoStr = formatDateForInput(d);
      isoDates.push(isoStr);
    }
    setSectionDates(isoDates);
  };

  useEffect(() => {
    // Automatische Berechnung der Promotion-Daten, wenn Eventdatum oder Offset sich ändern
    if (!form.begin_date) return;
    recalcPromotionDatesFromEvent();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [form.begin_date, promotionOffsetDays, artistSections.length]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.name.trim() || !form.begin_date) {
      setError('Bitte Titel und Datum ausfüllen');
      return;
    }

    if (!form.description.trim()) {
      setError('Bitte eine Beschreibung eintragen');
      return;
    }

    if (!form.admissionTimes.trim() || !form.ticketPrice.trim()) {
      setError('Bitte Einlasszeiten und Ticketpreis ausfüllen');
      return;
    }

    if (!promotionStartDate) {
      setError('Bitte Promotions-Startdatum wählen');
      return;
    }

    const hasEmptyArtistName = artistSections.some((artist) => !artist.name.trim());
    if (hasEmptyArtistName) {
      setError('Bitte für jede Künstler-Sektion einen Künstlernamen eintragen');
      return;
    }

    setError(null);
    setSaving(true);

    const payload = {
      title: form.name,
      description: form.description || undefined,
      eventDate: form.begin_date,
      promotionStartDate: promotionStartDate,
      coverMediaUrl: form.mediaUrl || undefined,
      ticketUrl: form.ticketUrl || undefined,
      admissionTimes: form.admissionTimes || undefined,
      ticketPrice: form.ticketPrice || undefined,
      promotionSlots: [
        // Sektion 1 – Event-Promotion
        {
          slotIndex: 1,
          slotType: 'EVENT_MAIN' as const,
          promoDate: promotionStartDate,
        },
        // Sektionen 2–N – Künstler 1–N
        ...artistSections.map((artist, idx) => ({
          slotIndex: idx + 2,
          slotType: 'ARTIST' as const,
          promoDate: sectionDates[idx + 1] || promotionStartDate,
          artistName: artist.name || undefined,
        })),
      ],
    };

    try {
      if (mode === 'edit' && eventId) {
        await updateEvent(eventId, payload);
      } else {
        await createEvent(payload);
      }
      onSuccess();

      // mark clean after successful save
      initialSnapshotRef.current = currentSnapshot;
      setIsDirty(false);
    } catch (err) {
      console.error('Error saving event:', err);
      setError('Speichern fehlgeschlagen');
    } finally {
      setSaving(false);
    }
  };

  const handleExtractFromUrl = async () => {
    if (!form.ticketUrl) return;
    setError(null);
    try {
      setExtractingFromUrl(true);
      const raw = await getEventInfoFromUrl(form.ticketUrl);

      // n8n / Backend kann verschiedene Strukturen liefern:
      // - direktes Objekt mit Feldern
      // - Array von Items, ggf. mit data-Wrapper
      const normalized = (() => {
        if (!raw) return null;

        // Falls als String-JSON zurückkommt
        if (typeof raw === 'string') {
          try {
            const parsed = JSON.parse(raw);
            return parsed;
          } catch {
            return null;
          }
        }

        if (Array.isArray(raw)) {
          const first = raw[0] ?? null;
          if (!first) return null;
          return (first as any).data ?? first;
        }

        // Einzelnes Objekt
        return (raw as any).data ?? raw;
      })();

      if (!normalized || typeof normalized !== 'object') {
        setError('Daten konnten aus der Event-URL nicht gelesen werden');
        return;
      }

      const info = normalized as any;

      const next = { ...form };

      // Titel -> Name
      if (info.title) {
        next.name = String(info.title);
      }

      // Beschreibung
      if (info.description) {
        next.description = String(info.description);
      }

      // Datum: "DD.MM.YYYY" -> "YYYY-MM-DD"
      if (info.date && typeof info.date === 'string') {
        const dateStr = info.date.trim();
        const match = dateStr.match(/^(\d{1,2})\.(\d{1,2})\.(\d{4})$/);
        if (match) {
          const [, d, m, y] = match;
          const iso = `${y}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
          next.begin_date = iso;
        }
      }

      // Zeitplan -> Einlasszeiten
      if (info.schedule) {
        next.admissionTimes = String(info.schedule);
      }

      // Preis(e)
      if (info.price) {
        next.ticketPrice = String(info.price);
      }

      // Fallbacks für evtl. schon bestehende Felder aus älteren Implementationen
      if (info.admissionTimes && !next.admissionTimes) {
        next.admissionTimes = String(info.admissionTimes);
      }
      if (info.ticketPrice && !next.ticketPrice) {
        next.ticketPrice = String(info.ticketPrice);
      }

      setForm(next);
    } catch (err) {
      console.error('Error extracting data from URL', err);
      setError('Daten konnten aus der Event-URL nicht gelesen werden');
    } finally {
      setExtractingFromUrl(false);
    }
  };

  const isSaveDisabled = (() => {
    if (!form.name.trim()) return true;
    if (!form.description.trim()) return true;
    if (!form.begin_date) return true;
    if (!form.admissionTimes.trim()) return true;
    if (!form.ticketPrice.trim()) return true;
    if (!promotionStartDate) return true;
    const hasEmptyArtistName = artistSections.some((artist) => !artist.name.trim());
    if (hasEmptyArtistName) return true;
    return false;
  })();

  const hasPreviewChanges = (() => {
    if (!previewSlot || !previewDraft) return false;
    const fields: Array<keyof any> = [
      'artistDescription',
      'artistInstagram',
      'artistFacebook',
      'artistLinkedin',
      'artistTiktok',
      'artistYoutube',
    ];
    return fields.some((key) => (previewDraft as any)[key] !== (previewSlot as any)[key]);
  })();

  const sidebarWidthClass = navExpanded ? 'w-56' : 'w-14';

  const NavItemButton = ({
    tab,
    label,
    Icon,
  }: {
    tab: 'stammdaten' | 'promotion' | 'artists' | 'schedule';
    label: string;
    Icon: React.ComponentType<{ className?: string }>;
  }) => {
    const isActive = activeTab === tab;
    return (
      <Button
        type="button"
        variant="ghost"
        size="sm"
        className={
          navExpanded
            ? `relative w-full h-10 justify-start gap-3 rounded-xl px-3 text-sm transition-colors ${
                isActive
                  ? 'bg-primary/10 text-primary shadow-sm'
                  : 'text-foreground/80 hover:bg-primary/5 hover:text-foreground'
              } focus-visible:ring-0 focus-visible:ring-offset-0`
            : `relative w-10 h-10 justify-center rounded-xl px-0 transition-colors ${
                isActive
                  ? 'bg-primary/10 text-primary shadow-sm'
                  : 'text-foreground/80 hover:bg-primary/5 hover:text-foreground'
              } focus-visible:ring-0 focus-visible:ring-offset-0`
        }
        onClick={() => setActiveTab(tab)}
      >
        <span
          className={
            navExpanded
              ? `absolute left-0 top-1/2 -translate-y-1/2 h-6 w-1 rounded-r ${isActive ? 'bg-primary' : 'bg-transparent'}`
              : 'hidden'
          }
        />
        <Icon className="h-4 w-4" />
        {navExpanded && <span className="truncate">{label}</span>}
      </Button>
    );
  };

  const MobileTabButton = ({
    tab,
    label,
    Icon,
  }: {
    tab: 'stammdaten' | 'promotion' | 'artists' | 'schedule';
    label: string;
    Icon: React.ComponentType<{ className?: string }>;
  }) => {
    const isActive = activeTab === tab;
    return (
      <Button
        type="button"
        variant="ghost"
        size="sm"
        className={`flex-1 h-11 px-1 justify-center rounded-xl transition-colors focus-visible:ring-0 focus-visible:ring-offset-0 ${
          isActive ? 'bg-primary/10 text-primary' : 'text-muted-foreground hover:bg-primary/5 hover:text-foreground'
        }`}
        onClick={() => setActiveTab(tab)}
      >
        <span className="flex flex-col items-center justify-center leading-tight">
          <Icon className="h-4 w-4" />
          <span className="hidden min-[390px]:block text-[10px] mt-0.5">{label}</span>
        </span>
      </Button>
    );
  };

  return (
    <div
      className={
        isMobile
          ? 'w-screen relative left-1/2 right-1/2 -ml-[50vw] -mr-[50vw] p-0 border-0 rounded-none'
          : 'rounded-lg border p-4'
      }
    >
      <form onSubmit={handleSubmit} className="relative">
        <div className={isMobile ? 'sticky top-16 z-20 border-b bg-background' : 'sticky top-16 z-20 -mx-4 px-4 py-2 border-b bg-background'}>
          {isMobile ? (
            <div className="px-3 py-2">
              <div className="flex items-center justify-between gap-2">
                <div className="text-xs text-muted-foreground">{loadingInitial ? 'Lade…' : ''}</div>
              </div>
              {error && <div className="text-sm text-destructive pt-1">{error}</div>}

              <div className="pt-2">
                <div className="flex gap-1">
                  <MobileTabButton tab="stammdaten" label="Stammdaten" Icon={CalendarDays} />
                  <MobileTabButton tab="promotion" label="Promotion" Icon={Megaphone} />
                  <MobileTabButton tab="artists" label="Künstler" Icon={Users} />
                  <MobileTabButton tab="schedule" label="Zeitplan" Icon={CalendarCheck2} />
                </div>
              </div>
            </div>
          ) : (
            <>
              <div className="flex items-center justify-between gap-2">
                <div className="text-xs text-muted-foreground">{loadingInitial ? 'Lade…' : ''}</div>
              </div>
              {error && <div className="text-sm text-destructive pt-1">{error}</div>}
            </>
          )}
        </div>

        <div className={isMobile ? 'pt-4 pb-24 px-3' : 'flex gap-4 pt-4'}>
          {!isMobile && (
            <aside className={`sticky top-20 self-start shrink-0 ${sidebarWidthClass} transition-[width] duration-200`}>
              <div className="rounded-2xl border bg-background p-2 shadow-sm">
                {navExpanded && <div className="text-xs text-muted-foreground px-2 pb-2">Menü</div>}

                <div className="space-y-1">
                  <NavItemButton tab="stammdaten" label="Stammdaten" Icon={CalendarDays} />
                  <NavItemButton tab="promotion" label="Promotion" Icon={Megaphone} />
                  <NavItemButton tab="artists" label="Künstler" Icon={Users} />
                  <NavItemButton tab="schedule" label="Zeitplan" Icon={CalendarCheck2} />
                </div>
              </div>
            </aside>
          )}

          <div className={isMobile ? '' : 'flex-1 min-w-0'}>
            {activeTab === 'stammdaten' && (
              <EventStammdatenSection
                form={form}
                mode={mode}
                extractingFromUrl={extractingFromUrl}
                onExtractFromUrl={handleExtractFromUrl}
                onInput={handleInput}
                beginDateRef={beginDateRef}
                setForm={setForm}
                formatDateForDisplay={formatDateForDisplay}
              />
            )}

            {activeTab === 'promotion' && (
              <PromotionTemplatesSection
                mediaUrl={form.mediaUrl}
                onMediaUrlChange={(url) => {
                  setForm((prev) => ({ ...prev, mediaUrl: url }));
                  setMediaPreview(url || null);
                }}
                fileInputRef={fileInputRef}
                onFileSelected={(file) => {
                  const url = URL.createObjectURL(file);
                  setMediaPreview(url);
                }}
                mediaPreview={mediaPreview}
              />
            )}

            {activeTab === 'artists' && (
              <ArtistsSection
                mode={mode}
                eventId={eventId}
                artistSections={artistSections}
                setArtistSections={setArtistSections}
                sectionDates={sectionDates}
                setSectionDates={setSectionDates}
                sectionDateRefs={sectionDateRefs}
                promotionSlots={promotionSlots}
                generatingLinkIndex={generatingLinkIndex}
                setGeneratingLinkIndex={setGeneratingLinkIndex}
                generateCollabLink={generateCollabLink}
                setError={setError}
                formatDateForDisplay={formatDateForDisplay}
                onOpenPreview={(slot) => {
                  setPreviewSlot(slot);
                  setPreviewDraft(slot ? { ...slot } : null);
                  setIsPreviewEditing(false);
                  setIsPreviewOpen(true);
                }}
              />
            )}

            {activeTab === 'schedule' && (
              <ScheduleSection
                promotionOffsetDays={promotionOffsetDays}
                setPromotionOffsetDays={setPromotionOffsetDays}
                promotionStartDate={promotionStartDate}
                handlePromotionStartChange={handlePromotionStartChange}
                promotionStartRef={promotionStartRef}
                formatDateForDisplay={formatDateForDisplay}
              />
            )}
          </div>
        </div>

        <div
          className={
            isMobile
              ? 'fixed bottom-0 left-0 right-0 z-30 px-3 py-3 border-t bg-background'
              : 'sticky bottom-0 z-20 -mx-4 mt-4 px-4 py-3 border-t bg-background'
          }
        >
          <div className="flex items-center justify-between gap-3">
            <div className="flex gap-2">
              {onCancel && (
                <Button type="button" variant="outline" onClick={onCancel}>
                  Abbrechen
                </Button>
              )}
              <Button type="submit" disabled={isSaveDisabled}>
                Speichern
              </Button>
            </div>
          </div>
        </div>
      </form>

      <Dialog
        open={isPreviewOpen}
        onOpenChange={(open) => {
          if (!open) {
            setIsPreviewOpen(false);
            setPreviewSlot(null);
            setPreviewDraft(null);
            setIsPreviewEditing(false);
          }
        }}
      >
        <DialogContent className="max-w-xl">
          <DialogHeader>
            <DialogTitle>Künstler-Vorschau</DialogTitle>
            <DialogDescription>
              {(previewDraft?.artistName || previewSlot?.artistName || 'Künstler')}
              {(previewDraft?.promoDate || previewSlot?.promoDate)
                ? ` – ${formatDateForDisplay(previewDraft?.promoDate || previewSlot?.promoDate)}`
                : ''}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 text-sm">
            <div className="flex justify-between items-center">
              <div className="text-xs text-muted-foreground">
                {previewSlot?.slotIndex ? `Slot ${previewSlot.slotIndex}` : ''}
              </div>
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() => {
                  // Beim ersten Wechsel in den Edit-Modus sicherstellen, dass ein Draft existiert
                  if (!isPreviewEditing && previewSlot && !previewDraft) {
                    setPreviewDraft({ ...previewSlot });
                  }
                  setIsPreviewEditing((prev) => !prev);
                }}
              >
                {isPreviewEditing ? 'Ansicht' : 'Bearbeiten'}
              </Button>
            </div>

            {/* Beschreibung */}
            {(previewSlot?.artistDescription || isPreviewEditing) && (
              <div className="space-y-1">
                <Label>Beschreibung</Label>
                {isPreviewEditing ? (
                  <Textarea
                    value={previewDraft?.artistDescription || ''}
                    onChange={(e) =>
                      setPreviewDraft((prev: any) => ({
                        ...(prev || {}),
                        artistDescription: e.target.value,
                      }))
                    }
                    rows={5}
                  />
                ) : (
                  <p className="mt-1 whitespace-pre-line">{previewDraft?.artistDescription || previewSlot?.artistDescription}</p>
                )}
              </div>
            )}

            {/* Social Media */}
            {(
              previewSlot?.artistInstagram ||
              previewSlot?.artistFacebook ||
              previewSlot?.artistLinkedin ||
              previewSlot?.artistTiktok ||
              previewSlot?.artistYoutube ||
              isPreviewEditing
            ) && (
              <div className="space-y-1">
                <Label>Social Media</Label>
                <div className="mt-1 space-y-2 text-xs">
                  {/* Instagram */}
                  {(isPreviewEditing || previewDraft?.artistInstagram || previewSlot?.artistInstagram) && (
                    <div className="flex items-center gap-2">
                      <span className="w-20">Instagram</span>
                      {isPreviewEditing ? (
                        <Input
                          value={previewDraft?.artistInstagram || ''}
                          onChange={(e) =>
                            setPreviewDraft((prev: any) => ({
                              ...(prev || {}),
                              artistInstagram: e.target.value,
                            }))
                          }
                        />
                      ) : (
                        <span className="break-all">{previewDraft?.artistInstagram || previewSlot?.artistInstagram}</span>
                      )}
                    </div>
                  )}

                  {/* Facebook */}
                  {(isPreviewEditing || previewDraft?.artistFacebook || previewSlot?.artistFacebook) && (
                    <div className="flex items-center gap-2">
                      <span className="w-20">Facebook</span>
                      {isPreviewEditing ? (
                        <Input
                          value={previewDraft?.artistFacebook || ''}
                          onChange={(e) =>
                            setPreviewDraft((prev: any) => ({
                              ...(prev || {}),
                              artistFacebook: e.target.value,
                            }))
                          }
                        />
                      ) : (
                        <span className="break-all">{previewDraft?.artistFacebook || previewSlot?.artistFacebook}</span>
                      )}
                    </div>
                  )}

                  {/* LinkedIn */}
                  {(isPreviewEditing || previewDraft?.artistLinkedin || previewSlot?.artistLinkedin) && (
                    <div className="flex items-center gap-2">
                      <span className="w-20">LinkedIn</span>
                      {isPreviewEditing ? (
                        <Input
                          value={previewDraft?.artistLinkedin || ''}
                          onChange={(e) =>
                            setPreviewDraft((prev: any) => ({
                              ...(prev || {}),
                              artistLinkedin: e.target.value,
                            }))
                          }
                        />
                      ) : (
                        <span className="break-all">{previewDraft?.artistLinkedin || previewSlot?.artistLinkedin}</span>
                      )}
                    </div>
                  )}

                  {/* TikTok */}
                  {(isPreviewEditing || previewDraft?.artistTiktok || previewSlot?.artistTiktok) && (
                    <div className="flex items-center gap-2">
                      <span className="w-20">TikTok</span>
                      {isPreviewEditing ? (
                        <Input
                          value={previewDraft?.artistTiktok || ''}
                          onChange={(e) =>
                            setPreviewDraft((prev: any) => ({
                              ...(prev || {}),
                              artistTiktok: e.target.value,
                            }))
                          }
                        />
                      ) : (
                        <span className="break-all">{previewDraft?.artistTiktok || previewSlot?.artistTiktok}</span>
                      )}
                    </div>
                  )}

                  {/* YouTube */}
                  {(isPreviewEditing || previewDraft?.artistYoutube || previewSlot?.artistYoutube) && (
                    <div className="flex items-center gap-2">
                      <span className="w-20">YouTube</span>
                      {isPreviewEditing ? (
                        <Input
                          value={previewDraft?.artistYoutube || ''}
                          onChange={(e) =>
                            setPreviewDraft((prev: any) => ({
                              ...(prev || {}),
                              artistYoutube: e.target.value,
                            }))
                          }
                        />
                      ) : (
                        <span className="break-all">{previewDraft?.artistYoutube || previewSlot?.artistYoutube}</span>
                      )}
                    </div>
                  )}
                </div>
              </div>
            )}

            {/* Medien nur zur Ansicht */}
            {Array.isArray(previewSlot?.media) && previewSlot.media.length > 0 && (
              <div className="space-y-1">
                <Label>Medien</Label>
                <div className="grid grid-cols-2 gap-2 mt-1">
                  {previewSlot.media.map((m: any) => (
                    <div key={m.id} className="border rounded overflow-hidden">
                      {m.type === 'video' ? (
                        <video src={m.url} className="w-full h-32 object-cover" controls />
                      ) : (
                        <img
                          src={m.url}
                          alt={previewSlot?.artistName || 'Artist media'}
                          className="w-full h-32 object-cover"
                        />
                      )}
                    </div>
                  ))}
                </div>
              </div>
            )}

            {previewSlot?.collabStatus && (
              <div className="space-y-1">
                <Label>Status</Label>
                <div className="mt-1 text-xs font-medium">{previewSlot.collabStatus}</div>
              </div>
            )}

            {isPreviewEditing && (
              <div className="pt-2 flex justify-end gap-2">
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  disabled={!previewSlot || !eventId || !previewSlot.slotId || savingPreview || !hasPreviewChanges}
                  onClick={async () => {
                  if (!previewSlot || !eventId || !previewSlot.slotId) return;

                  const payload: any = {
                    eventId,
                    slotId: previewSlot.slotId,
                    artistDescription: previewDraft?.artistDescription || undefined,
                    artistInstagram: previewDraft?.artistInstagram || undefined,
                    artistFacebook: previewDraft?.artistFacebook || undefined,
                    artistLinkedin: previewDraft?.artistLinkedin || undefined,
                    artistTiktok: previewDraft?.artistTiktok || undefined,
                    artistYoutube: previewDraft?.artistYoutube || undefined,
                  };

                  setSavingPreview(true);
                  const result = await updateArtistCollabDataByOp(payload);
                  setSavingPreview(false);

                  if (!result.success) {
                    setError(result.message || 'Künstlerdaten konnten nicht gespeichert werden');
                    return;
                  }

                  setPromotionSlots((prev) => {
                    if (!prev) return prev;
                    return prev.map((slot: any) => {
                      if (slot.slotIndex !== previewSlot.slotIndex) return slot;
                      return {
                        ...slot,
                        artistDescription: previewDraft?.artistDescription ?? slot.artistDescription,
                        artistInstagram: previewDraft?.artistInstagram ?? slot.artistInstagram,
                        artistFacebook: previewDraft?.artistFacebook ?? slot.artistFacebook,
                        artistLinkedin: previewDraft?.artistLinkedin ?? slot.artistLinkedin,
                        artistTiktok: previewDraft?.artistTiktok ?? slot.artistTiktok,
                        artistYoutube: previewDraft?.artistYoutube ?? slot.artistYoutube,
                      };
                    });
                  });

                  setPreviewSlot((prev) => {
                    if (!prev) return prev;
                    if (prev.slotIndex !== previewSlot.slotIndex) return prev;
                    return {
                      ...prev,
                      artistDescription: previewDraft?.artistDescription ?? prev.artistDescription,
                      artistInstagram: previewDraft?.artistInstagram ?? prev.artistInstagram,
                      artistFacebook: previewDraft?.artistFacebook ?? prev.artistFacebook,
                      artistLinkedin: previewDraft?.artistLinkedin ?? prev.artistLinkedin,
                      artistTiktok: previewDraft?.artistTiktok ?? prev.artistTiktok,
                      artistYoutube: previewDraft?.artistYoutube ?? prev.artistYoutube,
                    };
                  });

                  setIsPreviewEditing(false);
                }}
                >
                  {savingPreview ? 'Speichere…' : 'Änderungen speichern'}
                </Button>
              </div>
            )}
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default EventFormInline;
