import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import apiClient from '../api/client';

// Types
export interface APIToken {
  id: string;
  name: string;
  key_prefix: string;
  scopes: string[];
  is_active: boolean;
  is_sandbox: boolean;
  created_at: string;
  last_used_at: string | null;
  expires_at: string | null;
  created_by: {
    id: number;
    username: string;
    full_name: string;
  } | null;
}

export interface TestTokenForDocs {
  id: string;
  name: string;
  key_prefix: string;
  created_at: string;
}

export interface APITokenCreateResponse extends APIToken {
  key: string; // Full key, only returned on creation
}

export interface CreateTokenData {
  name: string;
  scopes: string[];
  expires_at?: string | null;
  is_sandbox?: boolean;
}

export interface APIScope {
  value: string;
  label: string;
  description: string;
}

// Available scopes
export const API_SCOPES: APIScope[] = [
  { value: 'services:read', label: 'Services (Read)', description: 'View services and pricing' },
  { value: 'resources:read', label: 'Resources (Read)', description: 'View resources and staff' },
  { value: 'availability:read', label: 'Availability (Read)', description: 'Check time slot availability' },
  { value: 'bookings:read', label: 'Bookings (Read)', description: 'View appointments' },
  { value: 'bookings:write', label: 'Bookings (Write)', description: 'Create, update, and cancel appointments' },
  { value: 'customers:read', label: 'Customers (Read)', description: 'View customer information' },
  { value: 'customers:write', label: 'Customers (Write)', description: 'Create and update customers' },
  { value: 'business:read', label: 'Business (Read)', description: 'View business information' },
  { value: 'webhooks:manage', label: 'Webhooks (Manage)', description: 'Manage webhook subscriptions' },
];

// Scope presets for common use cases
export const SCOPE_PRESETS = {
  booking_widget: {
    label: 'Booking Widget',
    description: 'Allow customers to book appointments',
    scopes: ['services:read', 'resources:read', 'availability:read', 'bookings:write', 'customers:write'],
  },
  read_only: {
    label: 'Read Only',
    description: 'View all data without making changes',
    scopes: ['services:read', 'resources:read', 'availability:read', 'bookings:read', 'customers:read', 'business:read'],
  },
  full_access: {
    label: 'Full Access',
    description: 'Complete access to all API features',
    scopes: API_SCOPES.map(s => s.value),
  },
};

// API Functions
const fetchApiTokens = async (): Promise<APIToken[]> => {
  const response = await apiClient.get('/v1/tokens/');
  return response.data;
};

const createApiToken = async (data: CreateTokenData): Promise<APITokenCreateResponse> => {
  const response = await apiClient.post('/v1/tokens/', data);
  return response.data;
};

const revokeApiToken = async (tokenId: string): Promise<void> => {
  await apiClient.delete(`/v1/tokens/${tokenId}/`);
};

const updateApiToken = async ({ tokenId, data }: { tokenId: string; data: Partial<CreateTokenData> & { is_active?: boolean } }): Promise<APIToken> => {
  const response = await apiClient.patch(`/v1/tokens/${tokenId}/`, data);
  return response.data;
};

const fetchTestTokensForDocs = async (): Promise<TestTokenForDocs[]> => {
  const response = await apiClient.get('/v1/tokens/test-tokens/');
  return response.data;
};

// Hooks
export const useApiTokens = () => {
  return useQuery({
    queryKey: ['apiTokens'],
    queryFn: fetchApiTokens,
  });
};

export const useCreateApiToken = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: createApiToken,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['apiTokens'] });
    },
  });
};

export const useRevokeApiToken = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: revokeApiToken,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['apiTokens'] });
    },
  });
};

export const useUpdateApiToken = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: updateApiToken,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['apiTokens'] });
    },
  });
};

export const useTestTokensForDocs = () => {
  return useQuery({
    queryKey: ['testTokensForDocs'],
    queryFn: fetchTestTokensForDocs,
    staleTime: 1000 * 60 * 5, // Cache for 5 minutes
  });
};
