'use client';

import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';
import RecordingForm from '@/components/pages/production/recording/form/RecordingForm';
import { RecordingApi } from '@/services/api/production';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';

const RecordingEdit = () => {
  const router = useRouter();
  const searchParams = useSearchParams();

  const recordingId = searchParams.get('recordingId');
  const recordingDetailKey = recordingId
    ? ['recording-detail', recordingId]
    : null;

  const { data: recording, isLoading: isLoadingRecording } = useSWR(
    recordingDetailKey,
    ([, id]: [string, string]) => RecordingApi.getSingle(parseInt(id))
  );

  if (!recordingId) {
    router.back();

    return (
      <div className='w-full flex flex-row justify-center items-center p-4'>
        <span className='loading loading-spinner loading-xl' />
      </div>
    );
  }

  if (!isLoadingRecording && (!recording || isResponseError(recording))) {
    router.replace('/404');
    return;
  }

  return (
    <div className='w-full p-4 flex flex-row justify-center'>
      {isLoadingRecording && (
        <span className='loading loading-spinner loading-xl' />
      )}
      {!isLoadingRecording && isResponseSuccess(recording) && (
        <RecordingForm type='edit' initialValues={recording.data} />
      )}
    </div>
  );
};

export default RecordingEdit;
