import { createClient, Asset } from 'contentful';
import { Document } from '@contentful/rich-text-types';

// Contentful client configuration
const client = createClient({
  space: process.env.CONTENTFUL_SPACE_ID || '',
  accessToken: process.env.CONTENTFUL_ACCESS_TOKEN || '',
});

// Content interfaces for our CMS data
export interface CompanyInfo {
  companyName: string;
  tagline: string;
  description: string;
  phoneNumber: string;
  whatsappNumber: string;
  email: string;
  address: string;
  workingHours: string;
  logo?: Asset;
  heroImage?: Asset;
}

export interface Product {
  name: string;
  slug: string;
  category: string;
  shortDescription: string;
  fullDescription: Document;
  features: string[];
  specifications: { name: string; value: string }[];
  applications: string[];
  images: Asset[];
  price?: number;
  isActive: boolean;
  order: number;
}

export interface Page {
  title: string;
  slug: string;
  metaDescription: string;
  content: Document;
  heroImage?: Asset;
  isActive: boolean;
  order: number;
}

export interface Testimonial {
  customerName: string;
  company: string;
  position: string;
  content: string;
  rating: number;
  avatar?: Asset;
  isActive: boolean;
  order: number;
}

export interface Project {
  name: string;
  slug: string;
  description: string;
  client: string;
  location: string;
  completionDate: string;
  category: string;
  images: Asset[];
  details: Document;
  isActive: boolean;
  order: number;
}

export interface Feature {
  title: string;
  description: string;
  icon: string;
  order: number;
  isActive: boolean;
}

// API functions with proper error handling and fallbacks
export async function getCompanyInfo(): Promise<CompanyInfo | null> {
  try {
    const entries = await client.getEntries({
      content_type: 'companyInfo',
      limit: 1,
    });
    
    if (entries.items.length === 0) return null;
    
    const entry = entries.items[0];
    return {
      companyName: entry.fields.companyName as string,
      tagline: entry.fields.tagline as string,
      description: entry.fields.description as string,
      phoneNumber: entry.fields.phoneNumber as string,
      whatsappNumber: entry.fields.whatsappNumber as string,
      email: entry.fields.email as string,
      address: entry.fields.address as string,
      workingHours: entry.fields.workingHours as string,
      logo: entry.fields.logo as Asset | undefined,
      heroImage: entry.fields.heroImage as Asset | undefined,
    };
  } catch (error) {
    console.error('Error fetching company info:', error);
    return null;
  }
}

export async function getAllProducts(): Promise<Product[]> {
  try {
    const entries = await client.getEntries({
      content_type: 'product',
      'fields.isActive': true,
      order: 'fields.order' as any,
    });
    
    return entries.items.map(entry => ({
      name: entry.fields.name as string,
      slug: entry.fields.slug as string,
      category: entry.fields.category as string,
      shortDescription: entry.fields.shortDescription as string,
      fullDescription: entry.fields.fullDescription as Document,
      features: entry.fields.features as string[],
      specifications: entry.fields.specifications as { name: string; value: string }[],
      applications: entry.fields.applications as string[],
      images: entry.fields.images as Asset[],
      price: entry.fields.price as number | undefined,
      isActive: entry.fields.isActive as boolean,
      order: entry.fields.order as number,
    }));
  } catch (error) {
    console.error('Error fetching products:', error);
    return [];
  }
}

export async function getProductBySlug(slug: string): Promise<Product | null> {
  try {
    const entries = await client.getEntries({
      content_type: 'product',
      'fields.slug[in]': slug,
      'fields.isActive': true,
      limit: 1,
    });
    
    if (entries.items.length === 0) return null;
    
    const entry = entries.items[0];
    return {
      name: entry.fields.name as string,
      slug: entry.fields.slug as string,
      category: entry.fields.category as string,
      shortDescription: entry.fields.shortDescription as string,
      fullDescription: entry.fields.fullDescription as Document,
      features: entry.fields.features as string[],
      specifications: entry.fields.specifications as { name: string; value: string }[],
      applications: entry.fields.applications as string[],
      images: entry.fields.images as Asset[],
      price: entry.fields.price as number | undefined,
      isActive: entry.fields.isActive as boolean,
      order: entry.fields.order as number,
    };
  } catch (error) {
    console.error('Error fetching product:', error);
    return null;
  }
}

export async function getProductsByCategory(category: string): Promise<Product[]> {
  try {
    const entries = await client.getEntries({
      content_type: 'product',
      'fields.category': category,
      'fields.isActive': true,
      order: 'fields.order' as any,
    });
    
    return entries.items.map(entry => ({
      name: entry.fields.name as string,
      slug: entry.fields.slug as string,
      category: entry.fields.category as string,
      shortDescription: entry.fields.shortDescription as string,
      fullDescription: entry.fields.fullDescription as Document,
      features: entry.fields.features as string[],
      specifications: entry.fields.specifications as { name: string; value: string }[],
      applications: entry.fields.applications as string[],
      images: entry.fields.images as Asset[],
      price: entry.fields.price as number | undefined,
      isActive: entry.fields.isActive as boolean,
      order: entry.fields.order as number,
    }));
  } catch (error) {
    console.error('Error fetching products by category:', error);
    return [];
  }
}

export async function getAllTestimonials(): Promise<Testimonial[]> {
  try {
    const entries = await client.getEntries({
      content_type: 'testimonial',
      'fields.isActive': true,
      order: 'fields.order' as any,
    });
    
    return entries.items.map(entry => ({
      customerName: entry.fields.customerName as string,
      company: entry.fields.company as string,
      position: entry.fields.position as string,
      content: entry.fields.content as string,
      rating: entry.fields.rating as number,
      avatar: entry.fields.avatar as Asset | undefined,
      isActive: entry.fields.isActive as boolean,
      order: entry.fields.order as number,
    }));
  } catch (error) {
    console.error('Error fetching testimonials:', error);
    return [];
  }
}

export async function getAllProjects(): Promise<Project[]> {
  try {
    const entries = await client.getEntries({
      content_type: 'project',
      'fields.isActive': true,
      order: '-fields.completionDate' as any,
    });
    
    return entries.items.map(entry => ({
      name: entry.fields.name as string,
      slug: entry.fields.slug as string,
      description: entry.fields.description as string,
      client: entry.fields.client as string,
      location: entry.fields.location as string,
      completionDate: entry.fields.completionDate as string,
      category: entry.fields.category as string,
      images: entry.fields.images as Asset[],
      details: entry.fields.details as Document,
      isActive: entry.fields.isActive as boolean,
      order: entry.fields.order as number,
    }));
  } catch (error) {
    console.error('Error fetching projects:', error);
    return [];
  }
}

export async function getHomePageFeatures(): Promise<Feature[]> {
  try {
    const entries = await client.getEntries({
      content_type: 'feature',
      'fields.isActive': true,
      order: 'fields.order' as any,
      limit: 6,
    });
    
    return entries.items.map(entry => ({
      title: entry.fields.title as string,
      description: entry.fields.description as string,
      icon: entry.fields.icon as string,
      order: entry.fields.order as number,
      isActive: entry.fields.isActive as boolean,
    }));
  } catch (error) {
    console.error('Error fetching features:', error);
    return [];
  }
}

// Helper function to get optimized image URL
export function getImageUrl(asset: Asset, width?: number, height?: number, quality?: number): string {
  if (!asset || !asset.fields.file) return '';
  
  let url = `https:${asset.fields.file.url}`;
  
  const params = new URLSearchParams();
  if (width) params.append('w', width.toString());
  if (height) params.append('h', height.toString());
  if (quality) params.append('q', quality.toString());
  params.append('fm', 'webp');
  
  if (params.toString()) {
    url += `?${params.toString()}`;
  }
  
  return url;
}

// Fallback data for development/testing
export const fallbackData = {
  companyInfo: {
    companyName: 'SAAM Cabins',
    tagline: 'Premium Porta Cabins & Containers in UAE',
    description: 'Leading manufacturer of high-quality porta cabins and containers in the UAE',
    phoneNumber: '+971 58 201 2073',
    whatsappNumber: '+971 58 201 2073',
    email: 'info@saamcabins.com',
    address: 'Industrial Area, Sharjah, UAE',
    workingHours: 'Sunday - Thursday: 8:00 AM - 6:00 PM',
  },
  products: [
    {
      name: 'Security Cabins',
      slug: 'security-cabin',
      category: 'Security',
      shortDescription: 'Professional security cabins for monitoring and surveillance',
      features: ['Bullet-proof glass', 'Climate control', 'Communication systems'],
      applications: ['Construction sites', 'Industrial facilities', 'Government buildings'],
    },
    {
      name: 'Office Cabins',
      slug: 'office-cabin',
      category: 'Office',
      shortDescription: 'Modern office solutions for temporary and permanent installations',
      features: ['Professional interiors', 'IT infrastructure', 'Meeting rooms'],
      applications: ['Construction sites', 'Remote locations', 'Expansion projects'],
    },
  ],
};

// Helper function to get data with fallback
export async function getDataWithFallback<T>(
  fetchFunction: () => Promise<T>,
  fallbackValue: T
): Promise<T> {
  try {
    const data = await fetchFunction();
    return data || fallbackValue;
  } catch (error) {
    console.warn('CMS fetch failed, using fallback data:', error);
    return fallbackValue;
  }
}

// Re-export rich text utilities
export { documentToReactComponents } from '@contentful/rich-text-react-renderer';
export { BLOCKS, MARKS, INLINES } from '@contentful/rich-text-types';