import {
  mdiAlbum,
  mdiChartTimelineVariant,
  mdiCheckCircleOutline,
  mdiChevronRight,
  mdiClockOutline,
  mdiExportVariant,
  mdiMicrophone,
  mdiMusic,
  mdiOpenInNew,
  mdiRobot,
  mdiTuneVariant,
  mdiWaveform,
} from '@mdi/js';
import axios from 'axios';
import Head from 'next/head';
import Link from 'next/link';
import React, { ReactElement, useEffect, useMemo, useState } from 'react';
import BaseButton from '../components/BaseButton';
import BaseIcon from '../components/BaseIcon';
import CardBox from '../components/CardBox';
import FormField from '../components/FormField';
import NotificationBar from '../components/NotificationBar';
import SectionMain from '../components/SectionMain';
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
import { getPageTitle } from '../config';
import { hasPermission } from '../helpers/userPermissions';
import LayoutAuthenticated from '../layouts/Authenticated';
import { useAppSelector } from '../stores/hooks';

type GenreOption = {
  id: string;
  name: string;
  description?: string;
  typical_bpm_min?: number;
  typical_bpm_max?: number;
};

type LanguageOption = {
  id: string;
  name: string;
  iso_code?: string;
};

type MasteringPresetOption = {
  id: string;
  name: string;
  target: string;
  lufs_target?: number;
  true_peak_db?: number;
};

type AiModelOption = {
  id: string;
  name: string;
  model_type: string;
  provider?: string;
  version?: string;
};

type RecentSession = {
  id: string;
  name: string;
  status: string;
  mood?: string;
  target_bpm?: number;
  target_key?: string;
  updatedAt: string;
  genre?: {
    id: string;
    name: string;
  } | null;
  projectHref: string;
  song?: {
    id: string;
    title: string;
    href: string;
  } | null;
  generationRequest?: {
    id: string;
    status: string;
    request_type: string;
    href: string;
  } | null;
  mixSession?: {
    id: string;
    status: string;
    href: string;
  } | null;
  masteringSession?: {
    id: string;
    status: string;
    href: string;
  } | null;
  exportJob?: {
    id: string;
    status: string;
    format: string;
    href: string;
  } | null;
};

type CreatedLink = {
  id: string;
  href: string;
  status?: string;
  format?: string;
  title?: string;
  bpm?: number;
  key_signature?: string;
  mood?: string;
  request_type?: string;
  distribution_status?: string;
  isrc?: string;
};

type CreatedSession = {
  project: CreatedLink & { name?: string };
  song: CreatedLink;
  generationRequest: CreatedLink;
  recordingSession?: CreatedLink | null;
  mixSession: CreatedLink;
  masteringSession: CreatedLink;
  exportJob: CreatedLink;
  songMetadata: CreatedLink;
  coverArtwork: CreatedLink;
  arrangementSections: Array<{
    id: string;
    label: string;
    section_type: string;
    start_bar: number;
    bar_length: number;
  }>;
  tracks: Array<{
    id: string;
    name: string;
    track_type: string;
    instrument: string;
  }>;
};

type LaunchpadResponse = {
  genres: GenreOption[];
  languages: LanguageOption[];
  masteringPresets: MasteringPresetOption[];
  aiModels: AiModelOption[];
  recentSessions: RecentSession[];
};

type FormState = {
  title: string;
  genreId: string;
  languageId: string;
  mood: string;
  targetBpm: string;
  targetKey: string;
  vocalMode: 'instrumental' | 'upload' | 'record';
  promptText: string;
  notes: string;
  masteringPresetId: string;
  exportFormat: 'wav' | 'mp3' | 'stems_zip';
  includeStems: boolean;
};

const initialForm: FormState = {
  title: '',
  genreId: '',
  languageId: '',
  mood: 'energetic',
  targetBpm: '',
  targetKey: '',
  vocalMode: 'upload',
  promptText: '',
  notes: '',
  masteringPresetId: '',
  exportFormat: 'wav',
  includeStems: true,
};

const moodOptions = ['happy', 'sad', 'spiritual', 'energetic', 'romantic', 'chill', 'aggressive'];
const vocalModes: Array<{ value: FormState['vocalMode']; title: string; description: string }> = [
  {
    value: 'upload',
    title: 'Upload vocal',
    description: 'Prepare a beat around an imported vocal take and queue vocal treatment.',
  },
  {
    value: 'record',
    title: 'Record later',
    description: 'Start with an instrumental draft and a planned recording session.',
  },
  {
    value: 'instrumental',
    title: 'Instrumental only',
    description: 'Build a beat-first session without a vocal chain yet.',
  },
];

const stageCards = [
  {
    label: 'Beat generation',
    detail: 'Queue a South African genre-aware instrumental brief.',
    icon: mdiRobot,
  },
  {
    label: 'Vocal workflow',
    detail: 'Prepare upload or recording steps with language-aware context.',
    icon: mdiMicrophone,
  },
  {
    label: 'Auto mix & master',
    detail: 'Stage mix, mastering, metadata, artwork, and export in one go.',
    icon: mdiTuneVariant,
  },
];

function getStatusClasses(status?: string) {
  switch (status) {
    case 'completed':
    case 'succeeded':
    case 'generated':
    case 'ready':
      return 'border-emerald-400/40 bg-emerald-500/10 text-emerald-200';
    case 'running':
    case 'recording':
    case 'in_progress':
    case 'ready_for_mix':
    case 'ready_for_master':
      return 'border-sky-400/40 bg-sky-500/10 text-sky-200';
    case 'failed':
      return 'border-rose-400/40 bg-rose-500/10 text-rose-200';
    default:
      return 'border-violet-400/40 bg-violet-500/10 text-violet-200';
  }
}

function prettyStatus(value?: string) {
  return (value || 'queued').replace(/_/g, ' ');
}

function formatRelativeDate(value: string) {
  const date = new Date(value);
  const diffMs = Date.now() - date.getTime();
  const diffHours = Math.max(1, Math.round(diffMs / (1000 * 60 * 60)));

  if (diffHours < 24) {
    return `${diffHours}h ago`;
  }

  const diffDays = Math.round(diffHours / 24);
  return `${diffDays}d ago`;
}

const StudioPage = () => {
  const { currentUser } = useAppSelector((state) => state.auth);
  const canCreateProjects = hasPermission(currentUser, 'CREATE_PROJECTS');

  const [isLoading, setIsLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');
  const [successMessage, setSuccessMessage] = useState('');
  const [form, setForm] = useState<FormState>(initialForm);
  const [genres, setGenres] = useState<GenreOption[]>([]);
  const [languages, setLanguages] = useState<LanguageOption[]>([]);
  const [masteringPresets, setMasteringPresets] = useState<MasteringPresetOption[]>([]);
  const [aiModels, setAiModels] = useState<AiModelOption[]>([]);
  const [recentSessions, setRecentSessions] = useState<RecentSession[]>([]);
  const [createdSession, setCreatedSession] = useState<CreatedSession | null>(null);

  const selectedGenre = useMemo(
    () => genres.find((genre) => genre.id === form.genreId) || null,
    [form.genreId, genres],
  );

  const selectedPreset = useMemo(
    () => masteringPresets.find((preset) => preset.id === form.masteringPresetId) || null,
    [form.masteringPresetId, masteringPresets],
  );

  const loadLaunchpad = async () => {
    const { data } = await axios.get<LaunchpadResponse>('/studio/launchpad');

    setGenres(data.genres || []);
    setLanguages(data.languages || []);
    setMasteringPresets(data.masteringPresets || []);
    setAiModels(data.aiModels || []);
    setRecentSessions(data.recentSessions || []);
    setForm((current) => ({
      ...current,
      genreId: current.genreId || data.genres?.[0]?.id || '',
      languageId: current.languageId || data.languages?.[0]?.id || '',
      masteringPresetId: current.masteringPresetId || data.masteringPresets?.[0]?.id || '',
      targetBpm:
        current.targetBpm ||
        (data.genres?.[0]?.typical_bpm_min ? String(data.genres[0].typical_bpm_min) : ''),
    }));
  };

  useEffect(() => {
    const run = async () => {
      try {
        setIsLoading(true);
        setErrorMessage('');
        await loadLaunchpad();
      } catch (error) {
        console.error('Failed to load studio launchpad:', error);
        setErrorMessage('We could not load the studio launchpad right now. Please refresh and try again.');
      } finally {
        setIsLoading(false);
      }
    };

    run();
  }, []);

  useEffect(() => {
    if (!selectedGenre) {
      return;
    }

    setForm((current) => {
      if (current.targetBpm) {
        return current;
      }

      return {
        ...current,
        targetBpm: selectedGenre.typical_bpm_min ? String(selectedGenre.typical_bpm_min) : '',
      };
    });
  }, [selectedGenre]);

  const handleChange =
    (field: keyof FormState) =>
    (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
      const target = event.target;
      const value = target instanceof HTMLInputElement && target.type === 'checkbox' ? target.checked : target.value;

      setForm((current) => ({
        ...current,
        [field]: value,
      } as FormState));
    };

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    try {
      setIsSubmitting(true);
      setErrorMessage('');
      setSuccessMessage('');

      const { data } = await axios.post<{ message: string; session: CreatedSession }>('/studio/launchpad', form);
      setCreatedSession(data.session);
      setSuccessMessage(data.message);
      setForm((current) => ({
        ...initialForm,
        genreId: current.genreId,
        languageId: current.languageId,
        masteringPresetId: current.masteringPresetId,
        targetBpm: current.targetBpm,
      }));
      await loadLaunchpad();
    } catch (error) {
      console.error('Failed to create studio session:', error);
      setErrorMessage(
        axios.isAxiosError(error)
          ? error.response?.data || 'We could not create the session. Please review the form and try again.'
          : 'We could not create the session. Please review the form and try again.',
      );
    } finally {
      setIsSubmitting(false);
    }
  };

  const quickStats = [
    {
      label: 'SA genres ready',
      value: genres.length || '—',
      icon: mdiMusic,
    },
    {
      label: 'Languages supported',
      value: languages.length || '—',
      icon: mdiMicrophone,
    },
    {
      label: 'AI engines online',
      value: aiModels.length || '—',
      icon: mdiRobot,
    },
    {
      label: 'Recent sessions',
      value: recentSessions.length || '0',
      icon: mdiAlbum,
    },
  ];

  return (
    <>
      <Head>
        <title>{getPageTitle('Studio Launchpad')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="Studio Launchpad" main>
          {''}
        </SectionTitleLineWithButton>

        <div className="mb-6 grid gap-6 xl:grid-cols-[1.8fr_1fr]">
          <CardBox className="overflow-hidden border border-violet-500/20 bg-gradient-to-br from-slate-950 via-slate-900 to-violet-950 text-white shadow-2xl shadow-violet-950/30">
            <div className="grid gap-6 lg:grid-cols-[1.5fr_1fr]">
              <div>
                <div className="mb-4 inline-flex items-center rounded-full border border-white/10 bg-white/5 px-3 py-1 text-xs uppercase tracking-[0.24em] text-violet-200">
                  South African AI music workflow
                </div>
                <h1 className="max-w-2xl text-3xl font-semibold leading-tight md:text-4xl">
                  Turn a beat idea into a staged studio session in one launch.
                </h1>
                <p className="mt-4 max-w-2xl text-sm leading-7 text-slate-300 md:text-base">
                  Pick your genre, vocal workflow, language, mastering target, and export format. The launchpad instantly creates a linked project, song, AI generation request, arrangement, mix, mastering, metadata, artwork, and export job.
                </p>
                <div className="mt-6 flex flex-wrap gap-3">
                  <Link
                    href="/projects/projects-list"
                    className="inline-flex items-center rounded-full border border-white/10 bg-white/10 px-4 py-2 text-sm font-medium text-white transition hover:bg-white/15"
                  >
                    View all projects
                    <BaseIcon path={mdiChevronRight} size={16} className="ml-1" />
                  </Link>
                  <Link
                    href="/generation_requests/generation_requests-list"
                    className="inline-flex items-center rounded-full border border-white/10 px-4 py-2 text-sm font-medium text-slate-200 transition hover:border-violet-300/40 hover:text-white"
                  >
                    AI queue
                    <BaseIcon path={mdiChevronRight} size={16} className="ml-1" />
                  </Link>
                </div>
              </div>

              <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-1">
                {quickStats.map((item) => (
                  <div key={item.label} className="rounded-2xl border border-white/10 bg-white/5 p-4 backdrop-blur">
                    <div className="flex items-center justify-between">
                      <span className="text-xs uppercase tracking-[0.18em] text-slate-400">{item.label}</span>
                      <BaseIcon path={item.icon} size={22} className="text-violet-200" />
                    </div>
                    <div className="mt-3 text-3xl font-semibold text-white">{item.value}</div>
                  </div>
                ))}
              </div>
            </div>
          </CardBox>

          <CardBox className="border border-slate-800 bg-slate-950 text-white">
            <div className="mb-5 flex items-center justify-between">
              <div>
                <p className="text-xs uppercase tracking-[0.24em] text-violet-300">Active AI chain</p>
                <h2 className="mt-2 text-xl font-semibold">What gets staged automatically</h2>
              </div>
              <BaseIcon path={mdiWaveform} size={26} className="text-violet-300" />
            </div>
            <div className="space-y-4">
              {stageCards.map((card) => (
                <div key={card.label} className="rounded-2xl border border-white/10 bg-white/5 p-4">
                  <div className="flex items-start gap-3">
                    <div className="rounded-xl border border-white/10 bg-white/10 p-2 text-violet-200">
                      <BaseIcon path={card.icon} size={20} />
                    </div>
                    <div>
                      <div className="font-medium text-white">{card.label}</div>
                      <p className="mt-1 text-sm leading-6 text-slate-300">{card.detail}</p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </CardBox>
        </div>

        {errorMessage ? (
          <NotificationBar color="danger" icon={mdiClockOutline}>
            {errorMessage}
          </NotificationBar>
        ) : null}

        {successMessage ? (
          <NotificationBar color="success" icon={mdiCheckCircleOutline}>
            {successMessage}
          </NotificationBar>
        ) : null}

        {!canCreateProjects ? (
          <NotificationBar color="warning" icon={mdiClockOutline}>
            Your role can review studio sessions, but it cannot launch new ones yet. Ask an admin for project creation access.
          </NotificationBar>
        ) : null}

        <div className="grid gap-6 2xl:grid-cols-[1.55fr_1fr]">
          <CardBox className="border border-slate-800 bg-slate-950 text-white">
            <div className="mb-6 flex items-center justify-between gap-4">
              <div>
                <p className="text-xs uppercase tracking-[0.24em] text-violet-300">First delivery workflow</p>
                <h2 className="mt-2 text-2xl font-semibold">Create a launch-ready studio session</h2>
              </div>
              <div className="rounded-full border border-violet-500/30 bg-violet-500/10 px-4 py-2 text-xs uppercase tracking-[0.2em] text-violet-200">
                Project → Song → Mix → Master → Export
              </div>
            </div>

            <form onSubmit={handleSubmit}>
              <div className="grid gap-6 md:grid-cols-2">
                <FormField label="Project title" help="Use a release-ready working title for the session.">
                  <input
                    name="title"
                    placeholder="Midnight Log Drum Prayer"
                    value={form.title}
                    onChange={handleChange('title')}
                    disabled={!canCreateProjects || isSubmitting}
                  />
                </FormField>

                <FormField label="Main vocal language" help="Used to stage vocal processing and metadata context.">
                  <select value={form.languageId} onChange={handleChange('languageId')} disabled={!canCreateProjects || isSubmitting}>
                    <option value="">Select language</option>
                    {languages.map((language) => (
                      <option key={language.id} value={language.id}>
                        {language.name}
                        {language.iso_code ? ` (${language.iso_code})` : ''}
                      </option>
                    ))}
                  </select>
                </FormField>
              </div>

              <div className="grid gap-6 md:grid-cols-3">
                <FormField label="South African genre" help="Choose the dominant production style for the generated beat.">
                  <select value={form.genreId} onChange={handleChange('genreId')} disabled={!canCreateProjects || isSubmitting}>
                    <option value="">Select genre</option>
                    {genres.map((genre) => (
                      <option key={genre.id} value={genre.id}>
                        {genre.name}
                      </option>
                    ))}
                  </select>
                </FormField>

                <FormField label="Mood" help="Controls arrangement, energy, and mastering direction.">
                  <select value={form.mood} onChange={handleChange('mood')} disabled={!canCreateProjects || isSubmitting}>
                    {moodOptions.map((mood) => (
                      <option key={mood} value={mood}>
                        {prettyStatus(mood)}
                      </option>
                    ))}
                  </select>
                </FormField>

                <FormField label="Vocal workflow" help="Choose whether this starts from vocals, a planned recording, or an instrumental draft.">
                  <select value={form.vocalMode} onChange={handleChange('vocalMode')} disabled={!canCreateProjects || isSubmitting}>
                    {vocalModes.map((mode) => (
                      <option key={mode.value} value={mode.value}>
                        {mode.title}
                      </option>
                    ))}
                  </select>
                </FormField>
              </div>

              <FormField label="Beat prompt" help="Describe the groove, emotion, instrumentation, and arrangement vibe.">
                <textarea
                  name="promptText"
                  placeholder="Soulful Amapiano with warm log drum movement, emotional piano chords, and a radio-ready vocal pocket for Xitsonga hooks."
                  value={form.promptText}
                  onChange={handleChange('promptText')}
                  disabled={!canCreateProjects || isSubmitting}
                />
              </FormField>

              <div className="grid gap-6 md:grid-cols-2">
                <FormField label="Creative notes" help="Optional notes for mix balance, vocal texture, or arrangement details.">
                  <textarea
                    name="notes"
                    placeholder="Keep the intro DJ-friendly, push the bass in the chorus, and leave space for call-and-response adlibs."
                    value={form.notes}
                    onChange={handleChange('notes')}
                    disabled={!canCreateProjects || isSubmitting}
                  />
                </FormField>

                <div className="rounded-3xl border border-white/10 bg-white/5 p-5">
                  <div className="grid gap-5 md:grid-cols-2">
                    <FormField label="Target BPM" help="You can refine the genre default.">
                      <input
                        name="targetBpm"
                        type="number"
                        min={60}
                        max={180}
                        value={form.targetBpm}
                        onChange={handleChange('targetBpm')}
                        disabled={!canCreateProjects || isSubmitting}
                      />
                    </FormField>

                    <FormField label="Target key" help="Optional if you already know the vocal key center.">
                      <input
                        name="targetKey"
                        placeholder="F# minor"
                        value={form.targetKey}
                        onChange={handleChange('targetKey')}
                        disabled={!canCreateProjects || isSubmitting}
                      />
                    </FormField>
                  </div>

                  <div className="grid gap-5 md:grid-cols-2">
                    <FormField label="Mastering preset" help="This stages the master destination and loudness profile.">
                      <select
                        value={form.masteringPresetId}
                        onChange={handleChange('masteringPresetId')}
                        disabled={!canCreateProjects || isSubmitting}
                      >
                        <option value="">Select mastering preset</option>
                        {masteringPresets.map((preset) => (
                          <option key={preset.id} value={preset.id}>
                            {preset.name}
                          </option>
                        ))}
                      </select>
                    </FormField>

                    <FormField label="Export target" help="Choose the initial delivery format to queue.">
                      <select value={form.exportFormat} onChange={handleChange('exportFormat')} disabled={!canCreateProjects || isSubmitting}>
                        <option value="wav">WAV · studio quality</option>
                        <option value="mp3">MP3 · quick share</option>
                        <option value="stems_zip">Stems ZIP · distribution prep</option>
                      </select>
                    </FormField>
                  </div>

                  <label className="mt-2 flex items-center gap-3 rounded-2xl border border-white/10 bg-slate-900/60 px-4 py-3 text-sm text-slate-200">
                    <input
                      type="checkbox"
                      checked={form.includeStems}
                      onChange={handleChange('includeStems')}
                      disabled={!canCreateProjects || isSubmitting}
                      className="h-4 w-4 rounded border-slate-600 bg-slate-950 text-violet-400 focus:ring-violet-500"
                    />
                    Include stems export in the first session package.
                  </label>
                </div>
              </div>

              <div className="mt-6 flex flex-wrap gap-3">
                <BaseButton
                  type="submit"
                  color="info"
                  label={isSubmitting ? 'Launching session…' : 'Launch studio session'}
                  icon={mdiRobot}
                  disabled={!canCreateProjects || isSubmitting || isLoading}
                  className="!rounded-full !px-6"
                />
                <BaseButton
                  color="white"
                  outline
                  label="Open songs"
                  href="/songs/songs-list"
                  icon={mdiAlbum}
                  className="!rounded-full !px-6 !text-slate-200"
                />
              </div>
            </form>
          </CardBox>

          <div className="space-y-6">
            <CardBox className="border border-slate-800 bg-slate-950 text-white">
              <div className="flex items-start justify-between gap-4">
                <div>
                  <p className="text-xs uppercase tracking-[0.24em] text-violet-300">Session preview</p>
                  <h3 className="mt-2 text-xl font-semibold">Current setup</h3>
                </div>
                <BaseIcon path={mdiExportVariant} size={24} className="text-violet-300" />
              </div>

              <div className="mt-5 space-y-4 text-sm text-slate-300">
                <div className="rounded-2xl border border-white/10 bg-white/5 p-4">
                  <div className="text-xs uppercase tracking-[0.2em] text-slate-400">Genre DNA</div>
                  <div className="mt-2 text-lg font-medium text-white">{selectedGenre?.name || 'Choose a genre'}</div>
                  <p className="mt-2 leading-6 text-slate-300">{selectedGenre?.description || 'South African groove details will appear here once you pick a genre.'}</p>
                  {selectedGenre?.typical_bpm_min || selectedGenre?.typical_bpm_max ? (
                    <div className="mt-3 text-xs uppercase tracking-[0.18em] text-violet-200">
                      Typical BPM {selectedGenre?.typical_bpm_min || '—'}–{selectedGenre?.typical_bpm_max || '—'}
                    </div>
                  ) : null}
                </div>

                <div className="rounded-2xl border border-white/10 bg-white/5 p-4">
                  <div className="text-xs uppercase tracking-[0.2em] text-slate-400">Mastering target</div>
                  <div className="mt-2 text-lg font-medium text-white">{selectedPreset?.name || 'Select a preset'}</div>
                  <p className="mt-2 leading-6 text-slate-300">
                    {selectedPreset
                      ? `${prettyStatus(selectedPreset.target)} master${selectedPreset.lufs_target ? ` · LUFS ${selectedPreset.lufs_target}` : ''}${selectedPreset.true_peak_db ? ` · Peak ${selectedPreset.true_peak_db} dB` : ''}`
                      : 'Choose how the first export should be prepared for streaming, radio, or club playback.'}
                  </p>
                </div>

                <div className="rounded-2xl border border-white/10 bg-white/5 p-4">
                  <div className="text-xs uppercase tracking-[0.2em] text-slate-400">Vocal route</div>
                  <div className="mt-2 text-lg font-medium text-white">
                    {vocalModes.find((mode) => mode.value === form.vocalMode)?.title || 'Upload vocal'}
                  </div>
                  <p className="mt-2 leading-6 text-slate-300">
                    {vocalModes.find((mode) => mode.value === form.vocalMode)?.description}
                  </p>
                </div>
              </div>
            </CardBox>

            <CardBox className="border border-slate-800 bg-slate-950 text-white">
              <div className="flex items-center justify-between gap-3">
                <div>
                  <p className="text-xs uppercase tracking-[0.24em] text-violet-300">AI engines</p>
                  <h3 className="mt-2 text-xl font-semibold">Available models</h3>
                </div>
                <BaseIcon path={mdiRobot} size={24} className="text-violet-300" />
              </div>
              <div className="mt-5 space-y-3">
                {aiModels.length ? (
                  aiModels.map((model) => (
                    <div key={model.id} className="rounded-2xl border border-white/10 bg-white/5 p-4">
                      <div className="flex items-center justify-between gap-3">
                        <div>
                          <div className="font-medium text-white">{model.name}</div>
                          <p className="text-sm text-slate-300">
                            {prettyStatus(model.model_type)} · {model.provider || 'Internal'}
                            {model.version ? ` · ${model.version}` : ''}
                          </p>
                        </div>
                        <BaseIcon path={mdiCheckCircleOutline} size={20} className="text-emerald-300" />
                      </div>
                    </div>
                  ))
                ) : (
                  <div className="rounded-2xl border border-dashed border-white/10 bg-white/5 p-4 text-sm text-slate-300">
                    No active AI models are visible for this workspace yet.
                  </div>
                )}
              </div>
            </CardBox>
          </div>
        </div>

        {createdSession ? (
          <CardBox className="mt-6 border border-emerald-500/20 bg-gradient-to-br from-emerald-950/70 via-slate-950 to-slate-950 text-white">
            <div className="mb-6 flex flex-wrap items-center justify-between gap-4">
              <div>
                <p className="text-xs uppercase tracking-[0.24em] text-emerald-300">Session created</p>
                <h2 className="mt-2 text-2xl font-semibold">Everything is linked and ready for review</h2>
              </div>
              <span className="rounded-full border border-emerald-400/30 bg-emerald-500/10 px-4 py-2 text-xs uppercase tracking-[0.2em] text-emerald-200">
                End-to-end MVP slice complete
              </span>
            </div>

            <div className="grid gap-4 lg:grid-cols-3">
              {[
                { label: 'Project', item: createdSession.project, icon: mdiMusic },
                { label: 'Song', item: createdSession.song, icon: mdiAlbum },
                { label: 'Generation', item: createdSession.generationRequest, icon: mdiRobot },
                { label: 'Recording', item: createdSession.recordingSession, icon: mdiMicrophone },
                { label: 'Mix', item: createdSession.mixSession, icon: mdiWaveform },
                { label: 'Master', item: createdSession.masteringSession, icon: mdiTuneVariant },
                { label: 'Export', item: createdSession.exportJob, icon: mdiExportVariant },
                { label: 'Metadata', item: createdSession.songMetadata, icon: mdiCheckCircleOutline },
                { label: 'Artwork', item: createdSession.coverArtwork, icon: mdiOpenInNew },
              ].map((entry) =>
                entry.item ? (
                  <Link
                    key={entry.label}
                    href={entry.item.href}
                    className="rounded-2xl border border-white/10 bg-white/5 p-4 transition hover:border-emerald-300/40 hover:bg-white/10"
                  >
                    <div className="flex items-center justify-between gap-3">
                      <div className="flex items-center gap-3">
                        <div className="rounded-xl border border-white/10 bg-white/10 p-2 text-emerald-200">
                          <BaseIcon path={entry.icon} size={18} />
                        </div>
                        <div>
                          <div className="text-xs uppercase tracking-[0.18em] text-slate-400">{entry.label}</div>
                          <div className="mt-1 text-base font-medium text-white">
                            {entry.item.title || entry.item.name || prettyStatus(entry.item.format || entry.item.status)}
                          </div>
                        </div>
                      </div>
                      <BaseIcon path={mdiChevronRight} size={18} className="text-slate-400" />
                    </div>
                  </Link>
                ) : null,
              )}
            </div>

            <div className="mt-6 grid gap-6 lg:grid-cols-2">
              <div className="rounded-2xl border border-white/10 bg-white/5 p-5">
                <div className="text-xs uppercase tracking-[0.2em] text-slate-400">Arrangement builder</div>
                <div className="mt-4 space-y-3">
                  {createdSession.arrangementSections.map((section) => (
                    <div key={section.id} className="flex items-center justify-between gap-4 rounded-2xl border border-white/10 bg-slate-950/60 px-4 py-3">
                      <div>
                        <div className="font-medium text-white">{section.label}</div>
                        <div className="text-sm text-slate-400">{prettyStatus(section.section_type)}</div>
                      </div>
                      <div className="text-right text-sm text-slate-300">
                        <div>Bar {section.start_bar}</div>
                        <div>{section.bar_length} bars</div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              <div className="rounded-2xl border border-white/10 bg-white/5 p-5">
                <div className="text-xs uppercase tracking-[0.2em] text-slate-400">Track blueprint</div>
                <div className="mt-4 space-y-3">
                  {createdSession.tracks.map((track) => (
                    <div key={track.id} className="flex items-center justify-between gap-4 rounded-2xl border border-white/10 bg-slate-950/60 px-4 py-3">
                      <div>
                        <div className="font-medium text-white">{track.name}</div>
                        <div className="text-sm text-slate-400">{prettyStatus(track.track_type)}</div>
                      </div>
                      <div className="rounded-full border border-violet-400/30 bg-violet-500/10 px-3 py-1 text-xs uppercase tracking-[0.16em] text-violet-200">
                        {prettyStatus(track.instrument)}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </CardBox>
        ) : null}

        <CardBox className="mt-6 border border-slate-800 bg-slate-950 text-white">
          <div className="mb-6 flex flex-wrap items-center justify-between gap-4">
            <div>
              <p className="text-xs uppercase tracking-[0.24em] text-violet-300">Recent work</p>
              <h2 className="mt-2 text-2xl font-semibold">Recent studio sessions</h2>
            </div>
            <Link
              href="/projects/projects-list"
              className="inline-flex items-center rounded-full border border-white/10 px-4 py-2 text-sm font-medium text-slate-200 transition hover:border-violet-300/40 hover:text-white"
            >
              Full project library
              <BaseIcon path={mdiOpenInNew} size={16} className="ml-2" />
            </Link>
          </div>

          {isLoading ? (
            <div className="rounded-2xl border border-white/10 bg-white/5 p-6 text-sm text-slate-300">
              Loading the latest studio sessions…
            </div>
          ) : recentSessions.length ? (
            <div className="grid gap-4 xl:grid-cols-2">
              {recentSessions.map((session) => (
                <div key={session.id} className="rounded-3xl border border-white/10 bg-white/5 p-5">
                  <div className="flex flex-wrap items-start justify-between gap-3">
                    <div>
                      <div className="text-xs uppercase tracking-[0.18em] text-slate-400">
                        {session.genre?.name || 'Studio session'}
                      </div>
                      <h3 className="mt-2 text-xl font-semibold text-white">{session.name}</h3>
                    </div>
                    <div className={`rounded-full border px-3 py-1 text-xs uppercase tracking-[0.16em] ${getStatusClasses(session.status)}`}>
                      {prettyStatus(session.status)}
                    </div>
                  </div>

                  <div className="mt-4 flex flex-wrap gap-2 text-xs uppercase tracking-[0.16em] text-slate-300">
                    {session.target_bpm ? <span className="rounded-full border border-white/10 px-3 py-1">{session.target_bpm} BPM</span> : null}
                    {session.target_key ? <span className="rounded-full border border-white/10 px-3 py-1">{session.target_key}</span> : null}
                    {session.mood ? <span className="rounded-full border border-white/10 px-3 py-1">{prettyStatus(session.mood)}</span> : null}
                    <span className="rounded-full border border-white/10 px-3 py-1">Updated {formatRelativeDate(session.updatedAt)}</span>
                  </div>

                  <div className="mt-5 grid gap-3 sm:grid-cols-2">
                    {[
                      session.song ? { label: 'Song', href: session.song.href, status: session.song.title } : null,
                      session.generationRequest
                        ? {
                            label: 'Generation',
                            href: session.generationRequest.href,
                            status: prettyStatus(session.generationRequest.status),
                          }
                        : null,
                      session.mixSession
                        ? { label: 'Mix', href: session.mixSession.href, status: prettyStatus(session.mixSession.status) }
                        : null,
                      session.masteringSession
                        ? {
                            label: 'Master',
                            href: session.masteringSession.href,
                            status: prettyStatus(session.masteringSession.status),
                          }
                        : null,
                      session.exportJob
                        ? {
                            label: 'Export',
                            href: session.exportJob.href,
                            status: `${prettyStatus(session.exportJob.status)} · ${session.exportJob.format.toUpperCase()}`,
                          }
                        : null,
                    ]
                      .filter(Boolean)
                      .map((item) => (
                        <Link
                          key={`${session.id}-${item?.label}`}
                          href={item?.href || session.projectHref}
                          className="rounded-2xl border border-white/10 bg-slate-950/60 px-4 py-3 transition hover:border-violet-300/30 hover:bg-slate-900"
                        >
                          <div className="text-xs uppercase tracking-[0.16em] text-slate-400">{item?.label}</div>
                          <div className="mt-1 text-sm font-medium text-white">{item?.status}</div>
                        </Link>
                      ))}
                  </div>

                  <div className="mt-5 flex items-center justify-between border-t border-white/10 pt-4">
                    <Link href={session.projectHref} className="inline-flex items-center text-sm font-medium text-violet-200 transition hover:text-white">
                      Open project
                      <BaseIcon path={mdiChevronRight} size={16} className="ml-1" />
                    </Link>
                    <div className="text-xs uppercase tracking-[0.16em] text-slate-500">Studio pipeline live</div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="rounded-2xl border border-dashed border-white/10 bg-white/5 p-8 text-center text-sm text-slate-300">
              No studio sessions yet. Launch your first beat-to-master workflow above and it will appear here instantly.
            </div>
          )}
        </CardBox>
      </SectionMain>
    </>
  );
};

StudioPage.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated permission={'READ_PROJECTS'}>{page}</LayoutAuthenticated>;
};

export default StudioPage;
