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;
  currency?: 'GBP' | 'USD';
  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 (includes auth token since Directus assets require authentication)
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;
  const params = new URLSearchParams();

  // Auth token required for asset access
  if (apiToken) params.append('access_token', apiToken);

  if (options) {
    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);
  }

  return `${directusUrl}/assets/${id}?${params.toString()}`;
}

// Map Directus artwork fields to frontend Artwork interface
// Directus has: name, price_gbp, price_usd, notes, creation_date
// Frontend expects: title, price, description, slug, year
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function mapArtwork(raw: any): Artwork {
  const gbp = parseFloat(raw.price_gbp);
  const usd = parseFloat(raw.price_usd);
  const hasGbp = !isNaN(gbp) && gbp > 0;
  const hasUsd = !isNaN(usd) && usd > 0;

  return {
    ...raw,
    title: raw.name || raw.title || '',
    price: hasGbp ? gbp : hasUsd ? usd : (raw.price || 0),
    currency: hasGbp ? 'GBP' : 'USD',
    description: raw.notes || raw.description || '',
    slug: raw.slug || String(raw.id),
    year: raw.creation_date ? new Date(raw.creation_date).getFullYear() : raw.year,
  };
}

// 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 || ['*'],
    })
  );
  return (result as Artwork[]).map(mapArtwork);
}

export async function getArtwork(idOrSlug: string): Promise<Artwork> {
  // Try by ID first (since Directus artworks use numeric IDs as slugs)
  try {
    const result = await directus.request(
      readItem('artworks', idOrSlug, {
        fields: ['*'],
      })
    );
    return mapArtwork(result);
  } catch {
    // Fall back to slug search
    const bySlug = await directus.request(
      readItems('artworks', {
        filter: { slug: { _eq: idOrSlug } },
        limit: 1,
        fields: ['*'],
      })
    );
    if (bySlug.length > 0) return mapArtwork(bySlug[0]);
    throw new Error(`Artwork not found: ${idOrSlug}`);
  }
}

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[]> {
  try {
    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[];
  } catch {
    // Events collection may not exist yet
    console.warn('Failed to fetch events - collection may not exist yet');
    return [];
  }
}

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[];
}
