'use client';

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useState } from 'react';

import Button, { ButtonSize, ButtonVariant } from '@/components/button/Button';
import { useDialogModal } from '@/components/modal/DialogModal';
import { useApiClient } from '@/lib/apiClient';
import type { components } from '@/lib/gen';

import ContestEditor from './components/ContestEditor';
import ContestList from './components/ContestList';

export const ADMIN_CONTESTS_QUERY_KEY = 'admin-contests';
const THIRTY_SECONDS_IN_MS = 30_000;

type ContestSchema = components['schemas']['ContestSchema'];

export default function ContestManagementClient() {
  const [selectedContest, setSelectedContest] = useState<ContestSchema | null>(
    null
  );
  const [isCreating, setIsCreating] = useState(false);
  const apiClient = useApiClient();
  const queryClient = useQueryClient();
  const { launchDialog } = useDialogModal();

  const {
    data: contestsData,
    isLoading,
    isError,
    error,
  } = useQuery({
    queryKey: [ADMIN_CONTESTS_QUERY_KEY],
    queryFn: async () => {
      const { data, error } = await apiClient.GET('/api/contests/');
      if (error) throw new Error('Failed to fetch contests');
      return data;
    },
    staleTime: THIRTY_SECONDS_IN_MS,
  });

  const deleteMutation = useMutation({
    mutationFn: async (contestId: string) => {
      const { error } = await apiClient.DELETE(
        '/api/contests/contest/{contest_id}',
        {
          params: { path: { contest_id: contestId } },
        }
      );
      if (error) throw new Error('Failed to delete contest');
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [ADMIN_CONTESTS_QUERY_KEY] });
      setSelectedContest(null);
    },
  });

  const handleCreateNew = () => {
    setSelectedContest(null);
    setIsCreating(true);
  };

  const handleSelectContest = (contest: ContestSchema) => {
    setSelectedContest(contest);
    setIsCreating(false);
  };

  const handleCloseEditor = () => {
    setIsCreating(false);
    setSelectedContest(null);
  };

  const handleSaveSuccess = () => {
    queryClient.invalidateQueries({ queryKey: [ADMIN_CONTESTS_QUERY_KEY] });
    setIsCreating(false);
  };

  const handleDelete = async (contestId: string) => {
    const confirmed = await launchDialog(
      'Are you sure you want to delete this contest? This action cannot be undone.',
      [
        { label: 'Cancel', action: false, isCancel: true },
        { label: 'Delete Contest', action: true },
      ]
    );

    if (confirmed) {
      deleteMutation.mutate(contestId);
    }
  };

  if (isLoading) {
    return (
      <div className='flex h-screen w-full items-center justify-center'>
        <div className='text-lg text-foreground-secondary'>
          Loading contests...
        </div>
      </div>
    );
  }

  if (isError) {
    return (
      <div className='flex h-screen w-full items-center justify-center'>
        <div className='text-lg text-red-600'>
          {error instanceof Error ? error.message : 'Failed to load contests'}
        </div>
      </div>
    );
  }

  const contests = contestsData?.contests || [];

  return (
    <div className='flex h-screen w-full pb-[100px]'>
      {/* Left Sidebar - Contest List (hidden on mobile when contest is selected) */}
      <div
        className={`w-80 flex-shrink-0 overflow-y-auto border-r border-border-primary bg-background-secondary ${
          isCreating || selectedContest ? 'hidden md:block' : 'block'
        }`}
      >
        <div className='sticky top-0 z-10 border-b border-border-primary bg-background-primary p-4'>
          <h1 className='mb-3 text-xl font-bold text-foreground-primary'>
            Contest Management
          </h1>
          <Button
            onClick={handleCreateNew}
            variant={ButtonVariant.Aura}
            size={ButtonSize.Medium}
            className='w-full'
          >
            + Create New Contest
          </Button>
        </div>
        <ContestList
          contests={contests}
          selectedContest={selectedContest}
          onSelectContest={handleSelectContest}
          isCreating={isCreating}
        />
      </div>

      {/* Right Panel - Contest Editor (full width on mobile when contest is selected) */}
      <div
        className={`flex-1 overflow-y-auto bg-background-primary ${
          isCreating || selectedContest ? 'block' : 'hidden md:block'
        }`}
      >
        {isCreating || selectedContest ? (
          <ContestEditor
            contest={selectedContest}
            onClose={handleCloseEditor}
            onSaveSuccess={handleSaveSuccess}
            onDelete={handleDelete}
          />
        ) : (
          <div className='flex h-full items-center justify-center px-6'>
            <div className='max-w-md text-center'>
              <div className='mb-4 text-6xl'>🎵</div>
              <div className='text-lg text-foreground-secondary'>
                Select a contest to edit or create a new one
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
