import { createQuery, createMutation, useQueryClient } from '@tanstack/solid-query';
import { trpc } from './trpc-client';

// Project hooks
export function useProjects() {
  return createQuery(() => ({
    queryKey: ['projects'],
    queryFn: async () => {
      return await trpc.project.listProjects.query(undefined);
    },
  }));
}

export function useProject(id: number) {
  return createQuery(() => ({
    queryKey: ['project', id],
    queryFn: async () => {
      return await trpc.project.getProject.query({ id });
    },
    enabled: !!id,
  }));
}

export function useCreateProject() {
  const qc = useQueryClient();
  return createMutation(() => ({
    mutationFn: async (input: { name: string; description?: string }) => {
      return await trpc.project.createProject.mutate(input);
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['projects'] });
    },
  }));
}

export function useUpdateProject() {
  const qc = useQueryClient();
  return createMutation(() => ({
    mutationFn: async (input: { id: number; name?: string; description?: string }) => {
      return await trpc.project.updateProject.mutate(input);
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['projects'] });
    },
  }));
}

export function useDeleteProject() {
  const qc = useQueryClient();
  return createMutation(() => ({
    mutationFn: async (id: number) => {
      return await trpc.project.deleteProject.mutate({ id });
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['projects'] });
    },
  }));
}

// Character hooks
export function useCharacters(projectId: number) {
  return createQuery(() => ({
    queryKey: ['characters', projectId],
    queryFn: async () => {
      return await trpc.project.listCharacters.query({ projectId });
    },
    enabled: !!projectId,
  }));
}

export function useCharacter(id: number) {
  return createQuery(() => ({
    queryKey: ['character', id],
    queryFn: async () => {
      return await trpc.project.getCharacter.query({ id });
    },
    enabled: !!id,
  }));
}

export function useSearchCharacters(projectId: number, query?: string, role?: 'protagonist' | 'antagonist' | 'supporting' | 'background' | 'ensemble', arcType?: 'positive' | 'negative' | 'flat' | 'complex') {
  return createQuery(() => ({
    queryKey: ['searchCharacters', projectId, query, role, arcType],
    queryFn: async () => {
      return await trpc.project.searchCharacters.query({
        projectId,
        query,
        role,
        arcType,
      });
    },
    enabled: !!projectId,
  }));
}

export function useCharacterStats(characterId: number) {
  return createQuery(() => ({
    queryKey: ['characterStats', characterId],
    queryFn: async () => {
      return await trpc.project.getCharacterStats.query({ characterId });
    },
    enabled: !!characterId,
  }));
}

export function useProjectCharacterStats(projectId: number) {
  return createQuery(() => ({
    queryKey: ['projectCharacterStats', projectId],
    queryFn: async () => {
      return await trpc.project.getProjectCharacterStats.query(undefined, {
        context: { projectId },
      });
    },
    enabled: !!projectId,
  }));
}

export function useCreateCharacter() {
  const qc = useQueryClient();
  return createMutation(() => ({
    mutationFn: async (input: {
      name: string;
      description?: string;
      bio?: string;
      role?: 'protagonist' | 'antagonist' | 'supporting' | 'background' | 'ensemble';
      arc?: string;
      arcType?: 'positive' | 'negative' | 'flat' | 'complex';
      age?: number;
      gender?: string;
      voice?: string;
      traits?: string;
      motivation?: string;
      conflict?: string;
      secret?: string;
      imageUrl?: string;
      projectId: number;
    }) => {
      return await trpc.project.createCharacter.mutate(input);
    },
    onSuccess: (_, variables) => {
      qc.invalidateQueries({ queryKey: ['characters', variables.projectId] });
    },
  }));
}

export function useUpdateCharacter() {
  const qc = useQueryClient();
  return createMutation(() => ({
    mutationFn: async (input: {
      id: number;
      name?: string;
      description?: string;
      bio?: string;
      role?: 'protagonist' | 'antagonist' | 'supporting' | 'background' | 'ensemble';
      arc?: string;
      arcType?: 'positive' | 'negative' | 'flat' | 'complex';
      age?: number;
      gender?: string;
      voice?: string;
      traits?: string;
      motivation?: string;
      conflict?: string;
      secret?: string;
      imageUrl?: string;
      projectId?: number;
    }) => {
      return await trpc.project.updateCharacter.mutate(input);
    },
    onSuccess: (_, variables) => {
      qc.invalidateQueries({ queryKey: ['character', variables.id] });
      qc.invalidateQueries({ queryKey: ['characters'] });
    },
  }));
}

export function useDeleteCharacter() {
  const qc = useQueryClient();
  return createMutation(() => ({
    mutationFn: async (id: number) => {
      return await trpc.project.deleteCharacter.mutate({ id });
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['characters'] });
      qc.invalidateQueries({ queryKey: ['characterRelationships'] });
    },
  }));
}

// Relationship hooks
export function useRelationships(projectId: number) {
  return createQuery(() => ({
    queryKey: ['characterRelationships', projectId],
    queryFn: async () => {
      return await trpc.project.listRelationships.query(undefined, {
        context: { projectId },
      });
    },
    enabled: !!projectId,
  }));
}

export function useCharacterRelationships(characterId: number) {
  return createQuery(() => ({
    queryKey: ['characterRelationships', characterId],
    queryFn: async () => {
      return await trpc.project.getRelationshipsForCharacter.query({ characterId });
    },
    enabled: !!characterId,
  }));
}

export function useCreateRelationship() {
  const qc = useQueryClient();
  return createMutation(() => ({
    mutationFn: async (input: {
      characterIdA: number;
      characterIdB: number;
      relationshipType: 'family' | 'romantic' | 'friendship' | 'rivalry' | 'mentor' | 'alliance' | 'conflict' | 'professional' | 'other';
      description?: string;
      strength?: number;
      isAntagonistic?: boolean;
    }) => {
      return await trpc.project.createRelationship.mutate(input);
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['characterRelationships'] });
    },
  }));
}

export function useUpdateRelationship() {
  const qc = useQueryClient();
  return createMutation(() => ({
    mutationFn: async (input: {
      id: number;
      relationshipType?: 'family' | 'romantic' | 'friendship' | 'rivalry' | 'mentor' | 'alliance' | 'conflict' | 'professional' | 'other';
      description?: string;
      strength?: number;
      isAntagonistic?: boolean;
    }) => {
      return await trpc.project.updateRelationship.mutate(input);
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['characterRelationships'] });
    },
  }));
}

export function useDeleteRelationship() {
  const qc = useQueryClient();
  return createMutation(() => ({
    mutationFn: async (id: number) => {
      return await trpc.project.deleteRelationship.mutate({ id });
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['characterRelationships'] });
    },
  }));
}

// Scene hooks
export function useScenes(projectId: number) {
  return createQuery(() => ({
    queryKey: ['scenes', projectId],
    queryFn: async () => {
      return await trpc.project.listScenes.query({ projectId });
    },
    enabled: !!projectId,
  }));
}

export function useScene(id: number) {
  return createQuery(() => ({
    queryKey: ['scene', id],
    queryFn: async () => {
      return await trpc.project.getScene.query({ id });
    },
    enabled: !!id,
  }));
}

export function useCreateScene() {
  const qc = useQueryClient();
  return createMutation(() => ({
    mutationFn: async (input: {
      title: string;
      content?: string;
      projectId: number;
      order: number;
    }) => {
      return await trpc.project.createScene.mutate(input);
    },
    onSuccess: (_, variables) => {
      qc.invalidateQueries({ queryKey: ['scenes', variables.projectId] });
    },
  }));
}

export function useUpdateScene() {
  const qc = useQueryClient();
  return createMutation(() => ({
    mutationFn: async (input: {
      id: number;
      title?: string;
      content?: string;
      order?: number;
    }) => {
      return await trpc.project.updateScene.mutate(input);
    },
    onSuccess: (_, variables) => {
      qc.invalidateQueries({ queryKey: ['scenes'] });
    },
  }));
}

export function useDeleteScene() {
  const qc = useQueryClient();
  return createMutation(() => ({
    mutationFn: async (id: number) => {
      return await trpc.project.deleteScene.mutate({ id });
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['scenes'] });
    },
  }));
}

// Waitlist hooks
export function useWaitlistSignup() {
  return createMutation(() => ({
    mutationFn: async (input: { email: string; name?: string; source?: string; referralCode?: string }) => {
      return await trpc.waitlist.signup.mutate(input);
    },
  }));
}

export function useWaitlistCount() {
  return createQuery(() => ({
    queryKey: ['waitlistCount'],
    queryFn: async () => {
      return await trpc.waitlist.getCount.query(undefined);
    },
    refetchInterval: 30000,
  }));
}

export function useReferralCount(referralCode: string) {
  return createQuery(() => ({
    queryKey: ['referralCount', referralCode],
    queryFn: async () => {
      return await trpc.waitlist.getReferralCount.query({ referralCode });
    },
    enabled: !!referralCode,
  }));
}

export function useBetaSignup() {
  return createMutation(() => ({
    mutationFn: async (input: {
      name: string;
      email: string;
      primaryRole: string;
      scriptsWritten?: string;
      currentSoftware?: string;
      softwareLove?: string;
      softwareFrustrate?: string;
      hoursPerWeek?: string;
      willingFeedback?: string;
      joinDiscord?: string;
      discordUsername?: string;
      excitedFeatures?: string[];
      heardAbout?: string;
      additionalInfo?: string;
      utmSource?: string;
      utmMedium?: string;
      utmCampaign?: string;
      utmContent?: string;
      utmTerm?: string;
    }) => {
      return await trpc.beta.signup.mutate(input);
    },
  }));
}
