import { createDirectus, rest, readItems, readItem, readSingleton, staticToken } from '@directus/sdk';

// Directus collection types
export interface Artwork {
  id: string;
  status: 'draft' | 'published' | 'sold' | 'archived';
  sort?: number;
  title: string;
  slug?: string;
  year?: number;
  medium?: string;
  dimensions?: string;
  price?: number;
  description?: string;
  image?: string | DirectusFile;
  gallery?: string[];
  series?: string | Series;
  tags?: string[];
  zettle_product_id?: string;
  lightroom_id?: string;
  date_created?: string;
  date_updated?: string;
}

export interface Series {
  id: string;
  name: string;
  slug?: string;
  description?: string;
  cover_image?: string | DirectusFile;
  artworks?: Artwork[];
}

export interface Tag {
  id: string;
  name: string;
  slug?: string;
}

export interface Event {
  id: string;
  status: 'draft' | 'published' | 'past';
  title: string;
  start_date?: string;
  end_date?: string;
  location?: string;
  description?: string;
  image?: string | DirectusFile;
  featured_artworks?: Artwork[];
}

export interface Page {
  id: string;
  status: 'draft' | 'published';
  title: string;
  slug: string;
  content?: string;
  seo_title?: string;
  seo_description?: string;
}

export interface Testimonial {
  id: string;
  status: 'draft' | 'published';
  quote: string;
  author?: string;
  role?: string;
  sort?: number;
}

export interface WisdomWord {
  id: string;
  status: 'draft' | 'published';
  quote?: string;
  author?: string;
  image?: string | DirectusFile;
  sort?: number;
}

export interface Location {
  id: string;
  name: string;
  type?: 'gallery' | 'auction' | 'studio' | 'private' | 'other';
  is_active?: boolean;
  contact_name?: string;
  email?: string;
  phone?: string;
  website?: string;
  street?: string;
  city?: string;
  county?: string;
  postcode?: string;
  country?: string;
  sale_cut_percent?: number;
  notes?: string;
}

export interface Contact {
  id: string;
  first_name?: string;
  last_name?: string;
  organisation?: string;
  email?: string;
  phone?: string;
  website?: string;
  street?: string;
  city?: string;
  county?: string;
  postcode?: string;
  country?: string;
  contact_type?: 'customer' | 'collector' | 'press' | 'gallery' | 'other';
  is_press_contact?: boolean;
  has_purchased?: boolean;
  no_mailouts?: boolean;
  notes?: string;
  airtable_id?: string;
}

export interface PricingBand {
  id: string;
  name: string;
  category?: 'fine_art' | 'products';
  price_usd?: number;
  sort?: number;
}

export interface SiteSettings {
  id: number;
  site_title?: string;
  tagline?: string;
  logo?: string | DirectusFile;
  footer_text?: string;
  social_links?: Array<{ platform: string; url: string }>;
  newsletter_enabled?: boolean;
  store_enabled?: boolean;
}

export interface DirectusFile {
  id: string;
  title?: string;
  description?: string;
  filename_download?: string;
  width?: number;
  height?: number;
}

// Create the Directus client (untyped to avoid complex SDK type inference)
const directusUrl = process.env.NEXT_PUBLIC_DIRECTUS_URL || 'https://katheryn-cms.jeffemmett.com';
const apiToken = process.env.DIRECTUS_API_TOKEN || '';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const directus = createDirectus<any>(directusUrl)
  .with(staticToken(apiToken))
  .with(rest());

// Helper to get asset URL
export function getAssetUrl(fileId: string | DirectusFile | undefined, options?: { width?: number; height?: number; quality?: number; format?: 'webp' | 'jpg' | 'png' }): string {
  if (!fileId) return '/placeholder.jpg';

  const id = typeof fileId === 'string' ? fileId : fileId.id;
  let url = `${directusUrl}/assets/${id}`;

  if (options) {
    const params = new URLSearchParams();
    if (options.width) params.append('width', options.width.toString());
    if (options.height) params.append('height', options.height.toString());
    if (options.quality) params.append('quality', options.quality.toString());
    if (options.format) params.append('format', options.format);
    if (params.toString()) url += `?${params.toString()}`;
  }

  return url;
}

// API functions with explicit return types
export async function getArtworks(options?: {
  status?: string;
  series?: string;
  limit?: number;
  fields?: string[];
}): Promise<Artwork[]> {
  const filter: Record<string, unknown> = {};
  if (options?.status) filter.status = { _eq: options.status };
  if (options?.series) filter.series = { _eq: options.series };

  const result = await directus.request(
    readItems('artworks', {
      filter: Object.keys(filter).length > 0 ? filter : undefined,
      limit: options?.limit || -1,
      sort: ['-date_created'],
      fields: options?.fields || ['*', { series: ['id', 'name', 'slug'] }],
    })
  );
  return result as Artwork[];
}

export async function getArtwork(idOrSlug: string): Promise<Artwork> {
  // Try to find by slug first, then by ID
  const bySlug = await directus.request(
    readItems('artworks', {
      filter: { slug: { _eq: idOrSlug } },
      limit: 1,
      fields: ['*', { series: ['*'] }],
    })
  );

  if (bySlug.length > 0) return bySlug[0] as Artwork;

  const result = await directus.request(
    readItem('artworks', idOrSlug, {
      fields: ['*', { series: ['*'] }],
    })
  );
  return result as Artwork;
}

export async function getSeries(options?: { limit?: number }): Promise<Series[]> {
  const result = await directus.request(
    readItems('series', {
      limit: options?.limit || -1,
      fields: ['*', { artworks: ['id', 'title', 'slug', 'image', 'status'] }],
    })
  );
  return result as Series[];
}

export async function getSeriesItem(idOrSlug: string): Promise<Series> {
  const bySlug = await directus.request(
    readItems('series', {
      filter: { slug: { _eq: idOrSlug } },
      limit: 1,
      fields: ['*', { artworks: ['*'] }],
    })
  );

  if (bySlug.length > 0) return bySlug[0] as Series;

  const result = await directus.request(
    readItem('series', idOrSlug, {
      fields: ['*', { artworks: ['*'] }],
    })
  );
  return result as Series;
}

export async function getEvents(options?: { status?: string; limit?: number }): Promise<Event[]> {
  const filter: Record<string, unknown> = {};
  if (options?.status) filter.status = { _eq: options.status };

  const result = await directus.request(
    readItems('events', {
      filter: Object.keys(filter).length > 0 ? filter : undefined,
      limit: options?.limit || -1,
      sort: ['-start_date'],
      fields: ['*'],
    })
  );
  return result as Event[];
}

export async function getPages(): Promise<Page[]> {
  const result = await directus.request(
    readItems('pages', {
      filter: { status: { _eq: 'published' } },
      fields: ['*'],
    })
  );
  return result as Page[];
}

export async function getPage(slug: string): Promise<Page | null> {
  const pages = await directus.request(
    readItems('pages', {
      filter: { slug: { _eq: slug }, status: { _eq: 'published' } },
      limit: 1,
      fields: ['*'],
    })
  );
  return (pages[0] as Page) || null;
}

export async function getTestimonials(options?: { limit?: number }): Promise<Testimonial[]> {
  const result = await directus.request(
    readItems('testimonials', {
      filter: { status: { _eq: 'published' } },
      limit: options?.limit || -1,
      sort: ['sort'],
      fields: ['*'],
    })
  );
  return result as Testimonial[];
}

export async function getWisdomWords(options?: { limit?: number }): Promise<WisdomWord[]> {
  const result = await directus.request(
    readItems('wisdom_words', {
      filter: { status: { _eq: 'published' } },
      limit: options?.limit || -1,
      sort: ['sort'],
      fields: ['*'],
    })
  );
  return result as WisdomWord[];
}

export async function getSiteSettings(): Promise<SiteSettings> {
  const result = await directus.request(readSingleton('site_settings'));
  return result as SiteSettings;
}

export async function getLocations(options?: { type?: string; active?: boolean }): Promise<Location[]> {
  const filter: Record<string, unknown> = {};
  if (options?.type) filter.type = { _eq: options.type };
  if (options?.active !== undefined) filter.is_active = { _eq: options.active };

  const result = await directus.request(
    readItems('locations', {
      filter: Object.keys(filter).length > 0 ? filter : undefined,
      fields: ['*'],
    })
  );
  return result as Location[];
}
