import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { fetchArtistSlotByToken, CollabInfo, updateArtistCollabData } from '@/features/event/api/eventService';
import { Facebook, Instagram, Linkedin, Music2, Youtube } from 'lucide-react';
import MediaUpload, { MediaItem, MediaItemType } from '@/shared/components/MediaUpload';
import { getWebhookUrl } from '@/lib/config';
import { uploadMediaWithContext, deleteMediaWithContext } from '@/services/fileService';

const ArtistCollabForm: React.FC = () => {
  const { token } = useParams<{ token: string }>();
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [submitted, setSubmitted] = useState(false);
  const [data, setData] = useState<CollabInfo | null>(null);

  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [media, setMedia] = useState<MediaItem[]>([]);
  const [instagram, setInstagram] = useState('');
  const [facebook, setFacebook] = useState('');
  const [linkedin, setLinkedin] = useState('');
  const [tiktok, setTiktok] = useState('');
  const [youtube, setYoutube] = useState('');

  useEffect(() => {
    if (!token) {
      setError('Ungültiger Link.');
      setLoading(false);
      return;
    }

    const load = async () => {
      setLoading(true);
      setError(null);
      try {
        const info = await fetchArtistSlotByToken(token);
        if (!info) {
          setError('Link ungültig oder abgelaufen.');
          return;
        }

        setData(info);
        setName(info.artistName || '');
        setDescription(info.artistDescription || '');
        setInstagram(info.artistInstagram || '');

        if (Array.isArray(info.media)) {
          setMedia(
            info.media.map((m) => ({
              id: m.id,
              type: m.type === 'video' ? 'video' : 'image',
              url: m.url,
            }))
          );
        }
      } catch (e) {
        setError('Link ungültig oder abgelaufen.');
      } finally {
        setLoading(false);
      }
    };

    load();
  }, [token]);

  const handleArtistMediaUpload = async ({ file, type }: { file: File; type: MediaItemType }) => {
    if (!token) {
      throw new Error('Kein gültiger Token für den Upload vorhanden.');
    }

    if (!data?.slotId) {
      throw new Error('Keine Slot-ID für den Upload vorhanden.');
    }

    const response = await uploadMediaWithContext(file, {
      endpoint: '/events/artist_upload',
      id: data.slotId,
      token,
      type,
      extraFields: {
        eventId: data.eventId,
      },
    });

    if (!response.success || !(response.url || response.fileUrl)) {
      throw new Error(response.message || 'Upload fehlgeschlagen');
    }

    return {
      url: response.url || response.fileUrl!,
      id: response.id,
    };
  };

  const handleArtistMediaDelete = async (item: MediaItem) => {
    if (!token) {
      throw new Error('Kein gültiger Token für die Löschung vorhanden.');
    }

    const response = await deleteMediaWithContext({
      endpoint: '/events/artist_remove',
      mediaId: item.id,
      token,
      extraFields: {
        slotId: data?.slotId,
        eventId: data?.eventId,
      },
    });

    if (!response.success) {
      throw new Error(response.message || 'Löschung fehlgeschlagen');
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!token) return;

    setError(null);
    setSubmitting(true);
    try {
      const result = await updateArtistCollabData({
        token,
        slotId: data?.slotId,
        eventId: data?.eventId,
        artistDescription: description || undefined,
        artistInstagram: instagram || undefined,
        artistFacebook: facebook || undefined,
        artistLinkedin: linkedin || undefined,
        artistTiktok: tiktok || undefined,
        artistYoutube: youtube || undefined,
      });

      if (!result.success) {
        throw new Error(result.message || 'Daten konnten nicht gespeichert werden.');
      }

      setSubmitted(true);
    } catch (e) {
      setError('Daten konnten nicht gespeichert werden.');
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-sm text-muted-foreground">Lade Link…</div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-sm text-destructive">{error}</div>
      </div>
    );
  }

  if (!data) {
    return null;
  }

  if (submitted) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="max-w-md w-full rounded-lg border p-6 space-y-2 text-center">
          <div className="text-lg font-semibold">Vielen Dank!</div>
          <div className="text-sm text-muted-foreground">
            Deine Daten wurden übermittelt.
          </div>
        </div>
      </div>
    );
  }

  const deadlineText = (() => {
    if (!data?.promoDate) return null;
    const d = new Date(data.promoDate);
    if (isNaN(d.getTime())) return null;
    d.setDate(d.getDate() - 1);
    return d.toLocaleDateString('de-DE');
  })();

  return (
    <div className="min-h-screen flex flex-col p-4 bg-background">
      <header className="mb-6 border-b pb-3">
        <div className="max-w-4xl mx-auto flex items-center justify-between gap-4">
          <div className="flex items-center gap-2">
            <img
              src="/Logo.png"
              alt="Kimaschine Logo"
              className="h-10 w-auto object-contain"
            />
          </div>
          <div className="text-center flex-1">
            {/* <div className="text-xs uppercase tracking-[0.18em] text-muted-foreground">Eventmodul</div> */}
            <div className="text-lg font-semibold tracking-tight">Kunst gegen Bares Düsseldorf</div>
          </div>
          <div className="flex items-center justify-end">
            <img
              src="/kgblogo.png"
              alt="Kunst gegen Bares Logo"
              className="h-10 w-auto object-contain"
            />
          </div>
        </div>
      </header>

      <div className="flex-1 flex items-center justify-center">
        <div className="w-full max-w-xl rounded-lg border p-6 space-y-4 bg-background">
          <div>
            {/* <div className="text-xs uppercase tracking-wide text-muted-foreground">Künstler-Formular</div> */}
            <h1 className="text-xl font-semibold">
              Hallo {data.artistName || name}, wir freuen uns, dich zum<br/>
              "{data.eventTitle}"<br/>
              im Ratinger Hof zu begrüßen.
            </h1>
            <p className="mt-2 text-sm text-muted-foreground">
              Im Rahmen unserer Promotion bitten wir dich, dich hier kurz vorzustellen.
              {deadlineText && <> Bitte sende uns die Daten bis spätestens {deadlineText}.</>}
            </p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="description">Kurzbeschreibung</Label>
              <Textarea
                id="description"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                rows={5}
              />
            </div>

            <div className="space-y-2">
              <MediaUpload
                label="Bild / Video"
                description="Lade bis zu 3 Bilder und optional ein Video hoch. Bilder werden direkt hochkant zugeschnitten."
                value={media}
                onChange={setMedia}
                maxImages={3}
                allowVideo
                aspectRatio={9 / 16}
                uploadFile={handleArtistMediaUpload}
                onRemoveItem={handleArtistMediaDelete}
              />
            </div>

            <div className="space-y-2">
              <Label>Deine Social-Media-Profile (optional)</Label>
              <div className="space-y-2">
                <div className="flex items-center gap-2">
                  <Facebook className="h-4 w-4 text-muted-foreground" />
                  <Input
                    id="facebook"
                    value={facebook}
                    onChange={(e) => setFacebook(e.target.value)}
                    placeholder="Facebook Benutzername oder Profil-URL"
                  />
                </div>
                <div className="flex items-center gap-2">
                  <Instagram className="h-4 w-4 text-muted-foreground" />
                  <Input
                    id="instagram"
                    value={instagram}
                    onChange={(e) => setInstagram(e.target.value)}
                    placeholder="Instagram Benutzername (@…)"
                  />
                </div>
                <div className="flex items-center gap-2">
                  <Linkedin className="h-4 w-4 text-muted-foreground" />
                  <Input
                    id="linkedin"
                    value={linkedin}
                    onChange={(e) => setLinkedin(e.target.value)}
                    placeholder="LinkedIn Profil (Name oder URL)"
                  />
                </div>
                <div className="flex items-center gap-2">
                  <Music2 className="h-4 w-4 text-muted-foreground" />
                  <Input
                    id="tiktok"
                    value={tiktok}
                    onChange={(e) => setTiktok(e.target.value)}
                    placeholder="TikTok Benutzername (@…)"
                  />
                </div>
                <div className="flex items-center gap-2">
                  <Youtube className="h-4 w-4 text-muted-foreground" />
                  <Input
                    id="youtube"
                    value={youtube}
                    onChange={(e) => setYoutube(e.target.value)}
                    placeholder="YouTube Kanal (Name oder URL)"
                  />
                </div>
              </div>
            </div>

            <div className="pt-2 flex justify-end">
              <Button type="submit" disabled={submitting}>
                {submitting ? 'Sende…' : 'Daten senden'}
              </Button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default ArtistCollabForm;
