import React from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

type ArtistSection = {
  name: string;
  email: string;
  link: string;
  status: 'Wartet auf Künstler' | 'Link generiert' | 'Fertig' | 'Künstler einladen';
};

type Props = {
  mode: 'create' | 'edit';
  eventId?: string | number | null;

  artistSections: ArtistSection[];
  setArtistSections: React.Dispatch<React.SetStateAction<ArtistSection[]>>;

  sectionDates: string[];
  setSectionDates: React.Dispatch<React.SetStateAction<string[]>>;
  sectionDateRefs: React.MutableRefObject<Array<HTMLInputElement | null>>;

  promotionSlots: any[] | null;

  generatingLinkIndex: number | null;
  setGeneratingLinkIndex: React.Dispatch<React.SetStateAction<number | null>>;

  generateCollabLink: (eventId: string | number, slotIndex: number, artistName: string, artistEmail: string) => Promise<any>;

  setError: React.Dispatch<React.SetStateAction<string | null>>;
  formatDateForDisplay: (iso: string) => string;

  onOpenPreview: (slot: any) => void;
};

const ArtistsSection: React.FC<Props> = ({
  mode,
  eventId,
  artistSections,
  setArtistSections,
  sectionDates,
  setSectionDates,
  sectionDateRefs,
  promotionSlots,
  generatingLinkIndex,
  setGeneratingLinkIndex,
  generateCollabLink,
  setError,
  formatDateForDisplay,
  onOpenPreview,
}) => {
  return (
    <div className="space-y-3">
      {artistSections.map((section, idx) => {
        const slot = promotionSlots?.find((s) => s.slotIndex === idx + 2);
        const hasArtistData = !!slot?.artistDescription || (Array.isArray(slot?.media) && slot.media.length > 0);
        const canOpenPreview = mode === 'edit' && !!slot && hasArtistData;

        return (
          <div key={idx} className="space-y-2 rounded-md border p-3">
            <div className="flex items-center justify-between text-sm font-medium">
              <span>{`Künstler ${idx + 1}`}</span>
              <span className="text-xs text-muted-foreground">{artistSections[idx].status}</span>
            </div>

            <div className="space-y-3">
              <div className="space-y-1">
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <span>{formatDateForDisplay(sectionDates[idx + 1]) || 'Noch kein Datum gewählt'}</span>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => {
                      const ref = sectionDateRefs.current[idx + 1];
                      if (ref) {
                        if (ref.showPicker) {
                          ref.showPicker();
                        } else {
                          ref.focus();
                        }
                      }
                    }}
                  >
                    Datum wählen
                  </Button>
                </div>
                <Input
                  ref={(el) => (sectionDateRefs.current[idx + 1] = el)}
                  id={`section_date_${idx + 2}`}
                  type="date"
                  className="hidden"
                  value={sectionDates[idx + 1]}
                  onChange={(e) => {
                    const next = [...sectionDates];
                    next[idx + 1] = e.target.value;
                    setSectionDates(next);
                  }}
                />
              </div>

              <div className="space-y-2">
                <div className="space-y-1">
                  <Label htmlFor={`artist_name_${idx}`}>Künstlername *</Label>
                  <Input
                    id={`artist_name_${idx}`}
                    type="text"
                    placeholder="Name des Künstlers"
                    value={section.name}
                    onChange={(e) => {
                      const next = [...artistSections];
                      next[idx] = { ...next[idx], name: e.target.value };
                      setArtistSections(next);
                    }}
                  />
                </div>

                <div className="flex flex-col sm:flex-row sm:items-center gap-2 text-xs text-muted-foreground">
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={async () => {
                      if (mode !== 'edit' || !eventId) {
                        setError('Bitte Event zuerst speichern, bevor Links generiert werden.');
                        return;
                      }
                      try {
                        setGeneratingLinkIndex(idx);
                        const raw = await generateCollabLink(eventId, idx + 2, section.name, section.email || '');

                        const res: any = (() => {
                          if (!raw) return null;
                          if (Array.isArray(raw)) {
                            return raw[0] ?? null;
                          }
                          if (typeof raw === 'string') {
                            try {
                              const parsed = JSON.parse(raw);
                              return Array.isArray(parsed) ? parsed[0] ?? null : parsed;
                            } catch {
                              return null;
                            }
                          }
                          return raw as any;
                        })();

                        const link = res?.url || (res?.token ? `/collab/${res.token}` : '');
                        if (!link) {
                          setError('Kollaborationslink konnte nicht erzeugt werden.');
                          return;
                        }
                        const next = [...artistSections];
                        next[idx] = { ...next[idx], link, status: 'Link generiert' };
                        setArtistSections(next);
                      } catch (e) {
                        setError('Kollaborationslink konnte nicht erzeugt werden.');
                      } finally {
                        setGeneratingLinkIndex((current) => (current === idx ? null : current));
                      }
                    }}
                    disabled={!section.name || !eventId || mode !== 'edit' || generatingLinkIndex === idx}
                  >
                    {generatingLinkIndex === idx && (
                      <span className="h-3 w-3 mr-1 rounded-full border-2 border-current border-t-transparent animate-spin" />
                    )}
                    Link generieren
                  </Button>

                  {section.link && (
                    <div className="flex flex-1 items-center gap-2 w-full">
                      <Input readOnly className="text-xs flex-1" value={section.link} onFocus={(e) => e.target.select()} />
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={async () => {
                          try {
                            if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
                              await navigator.clipboard.writeText(section.link || '');
                            }
                          } catch (e) {
                            console.error('Clipboard copy failed', e);
                          }
                        }}
                      >
                        Kopieren
                      </Button>
                    </div>
                  )}
                </div>

                <div className="pt-1">
                  <Button type="button" variant="outline" size="sm" disabled={!canOpenPreview} onClick={() => slot && onOpenPreview(slot)}>
                    Künstlerdaten ansehen
                  </Button>
                </div>
              </div>
            </div>
          </div>
        );
      })}

      <div className="flex flex-wrap gap-2 pt-2">
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={() => {
            setArtistSections((prev) => {
              const next = [
                ...prev,
                {
                  name: '',
                  email: '',
                  link: '',
                  status: 'Wartet auf Künstler' as const,
                },
              ];
              return next;
            });
          }}
        >
          Künstler hinzufügen
        </Button>
        <Button
          type="button"
          variant="outline"
          size="sm"
          disabled={artistSections.length <= 1}
          onClick={() => {
            if (artistSections.length <= 1) return;
            setArtistSections((prev) => prev.slice(0, -1));
            setSectionDates((prev) => {
              if (prev.length <= 2) return prev;
              return prev.slice(0, -1);
            });
          }}
        >
          Letzten Künstler entfernen
        </Button>
      </div>
    </div>
  );
};

export default ArtistsSection;
