import fs from 'fs';
import path from 'path';

// Data storage paths
const DATA_DIR = path.join(process.cwd(), 'data');
const UPLOADS_DIR = path.join(process.cwd(), 'public', 'uploads');

// Ensure directories exist
if (typeof window === 'undefined') {
  if (!fs.existsSync(DATA_DIR)) {
    fs.mkdirSync(DATA_DIR, { recursive: true });
  }
  if (!fs.existsSync(UPLOADS_DIR)) {
    fs.mkdirSync(UPLOADS_DIR, { recursive: true });
  }
}

// Data interfaces
export interface CompanyInfo {
  id: string;
  companyName: string;
  tagline: string;
  description: string;
  phoneNumber: string;
  whatsappNumber: string;
  email: string;
  address: string;
  workingHours: string;
  logo?: string;
  heroImage?: string;
  updatedAt: string;
}

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

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

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

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

export interface SliderSlide {
  id: string;
  title: string;
  subtitle?: string;
  description?: string;
  image: string;
  buttonText?: string;
  buttonLink?: string;
  buttonStyle?: 'primary' | 'secondary' | 'outline';
  textPosition?: 'left' | 'center' | 'right';
  isActive: boolean;
  order: number;
  createdAt: string;
  updatedAt: string;
}

export interface Slider {
  id: string;
  name: string;
  type: 'hero' | 'product' | 'testimonial' | 'gallery';
  slides: SliderSlide[];
  settings: {
    autoPlay: boolean;
    autoPlayDelay: number; // in milliseconds
    showDots: boolean;
    showArrows: boolean;
    infinite: boolean;
    slidesToShow: number;
    slidesToScroll: number;
    responsive?: {
      breakpoint: number;
      settings: {
        slidesToShow: number;
        slidesToScroll: number;
      };
    }[];
  };
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
}

export interface Page {
  id: string;
  title: string;
  slug: string;
  content: string;
  metaDescription: string;
  metaKeywords: string;
  heroImage?: string;
  isActive: boolean;
  showInMenu: boolean;
  menuOrder: number;
  pageType: 'standard' | 'landing' | 'service' | 'about';
  createdAt: string;
  updatedAt: string;
}

// Generic data operations
export class DataStore<T extends { id: string }> {
  private filePath: string;

  constructor(fileName: string) {
    this.filePath = path.join(DATA_DIR, fileName);
  }

  private async readData(): Promise<T[]> {
    try {
      if (!fs.existsSync(this.filePath)) {
        return [];
      }
      const data = fs.readFileSync(this.filePath, 'utf-8');
      return JSON.parse(data);
    } catch (error) {
      console.error('Error reading data:', error);
      return [];
    }
  }

  private async writeData(data: T[]): Promise<void> {
    try {
      fs.writeFileSync(this.filePath, JSON.stringify(data, null, 2));
    } catch (error) {
      console.error('Error writing data:', error);
      throw error;
    }
  }

  async getAll(): Promise<T[]> {
    return this.readData();
  }

  async getById(id: string): Promise<T | null> {
    const data = await this.readData();
    return data.find(item => item.id === id) || null;
  }

  async create(item: Omit<T, 'id' | 'createdAt' | 'updatedAt'>): Promise<T> {
    const data = await this.readData();
    const newItem = {
      ...item,
      id: Date.now().toString(),
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    } as unknown as T;
    
    data.push(newItem);
    await this.writeData(data);
    return newItem;
  }

  async update(id: string, updates: Partial<Omit<T, 'id' | 'createdAt'>>): Promise<T | null> {
    const data = await this.readData();
    const index = data.findIndex(item => item.id === id);
    
    if (index === -1) return null;
    
    data[index] = {
      ...data[index],
      ...updates,
      updatedAt: new Date().toISOString(),
    } as T;
    
    await this.writeData(data);
    return data[index];
  }

  async delete(id: string): Promise<boolean> {
    const data = await this.readData();
    const filteredData = data.filter(item => item.id !== id);
    
    if (filteredData.length === data.length) return false;
    
    await this.writeData(filteredData);
    return true;
  }
}

// Data store instances
export const companyStore = new DataStore<CompanyInfo>('company.json');
export const productStore = new DataStore<Product>('products.json');
export const featureStore = new DataStore<Feature>('features.json');
export const testimonialStore = new DataStore<Testimonial>('testimonials.json');
export const projectStore = new DataStore<Project>('projects.json');
export const pageStore = new DataStore<Page>('pages.json');
export const sliderStore = new DataStore<Slider>('sliders.json');

// Initialize default data
export async function initializeDefaultData() {
  try {
    // Check if company info exists
    const companies = await companyStore.getAll();
    if (companies.length === 0) {
      await companyStore.create({
        companyName: 'SAAM Cabins',
        tagline: 'Premium Porta Cabins & Containers in UAE',
        description: 'Leading manufacturer and supplier of high-quality porta cabins, security cabins, and containers across the United Arab Emirates.',
        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',
      });
    }

    // Check if features exist
    const features = await featureStore.getAll();
    if (features.length === 0) {
      const defaultFeatures = [
        { title: 'Premium Quality', description: 'ISO certified manufacturing with premium materials', icon: 'Award', order: 1, isActive: true },
        { title: 'Fast Delivery', description: 'Quick manufacturing and delivery across UAE', icon: 'Zap', order: 2, isActive: true },
        { title: 'Custom Solutions', description: 'Tailored designs for specific requirements', icon: 'Wrench', order: 3, isActive: true },
        { title: 'Professional Service', description: 'Expert consultation and support', icon: 'Users', order: 4, isActive: true },
        { title: 'Nationwide Coverage', description: 'Service across all UAE emirates', icon: 'Globe', order: 5, isActive: true },
        { title: 'Security & Safety', description: 'Enhanced security and safety compliance', icon: 'Shield', order: 6, isActive: true },
      ];

      for (const feature of defaultFeatures) {
        await featureStore.create(feature);
      }
    }

    // Check if products exist
    const products = await productStore.getAll();
    if (products.length === 0) {
      const defaultProducts = [
        {
          name: 'Security Cabins',
          slug: 'security-cabin',
          category: 'Security',
          shortDescription: 'Professional security cabins for monitoring and surveillance',
          fullDescription: 'Our security cabins are designed for professional security applications with enhanced features for monitoring and surveillance.',
          features: ['Bullet-proof glass options', 'Climate control systems', 'Communication equipment', 'CCTV integration'],
          specifications: [
            { name: 'Dimensions', value: '8ft x 6ft x 8ft' },
            { name: 'Material', value: 'Steel frame with insulation' },
            { name: 'Windows', value: 'Bullet-proof glass' },
            { name: 'Door', value: 'Security door with multiple locks' }
          ],
          applications: ['Construction sites', 'Industrial facilities', 'Government buildings'],
          images: [],
          isActive: true,
          order: 1
        },
        {
          name: 'Office Cabins',
          slug: 'office-cabin',
          category: 'Office',
          shortDescription: 'Modern office solutions for temporary and permanent installations',
          fullDescription: 'Professional office cabins designed for business use with modern amenities and professional interiors.',
          features: ['Professional interiors', 'IT infrastructure ready', 'Meeting room configurations', 'Ergonomic design'],
          specifications: [
            { name: 'Dimensions', value: '20ft x 10ft x 9ft' },
            { name: 'Material', value: 'Insulated steel panels' },
            { name: 'Flooring', value: 'Raised floor with carpet' },
            { name: 'Electrical', value: 'Full electrical installation' }
          ],
          applications: ['Construction site offices', 'Remote work locations', 'Business expansion'],
          images: [],
          isActive: true,
          order: 2
        }
      ];

      for (const product of defaultProducts) {
        await productStore.create(product);
      }
    }

    // Check if sliders exist
    const sliders = await sliderStore.getAll();
    if (sliders.length === 0) {
      const createSlide = (slide: Omit<SliderSlide, 'id' | 'createdAt' | 'updatedAt'>): SliderSlide => ({
        ...slide,
        id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      });

      const defaultSliders: Omit<Slider, 'id' | 'createdAt' | 'updatedAt'>[] = [
        {
          name: 'Hero Banner Slider',
          type: 'hero',
          slides: [
            createSlide({
              title: 'Premium Porta Cabins & Containers in UAE',
              subtitle: 'Quality & Innovation',
              description: 'Leading manufacturer and supplier of high-quality porta cabins, security cabins, and containers across the United Arab Emirates.',
              image: '/hero-slide-1.jpg',
              buttonText: 'Get Quote',
              buttonLink: '/contact',
              buttonStyle: 'primary',
              textPosition: 'center',
              isActive: true,
              order: 1
            }),
            createSlide({
              title: 'Professional Security Solutions',
              subtitle: 'Security & Reliability',
              description: 'Specialized security cabins and monitoring solutions for construction sites, industrial facilities, and commercial properties.',
              image: '/hero-slide-2.jpg',
              buttonText: 'View Products',
              buttonLink: '/products',
              buttonStyle: 'primary',
              textPosition: 'center',
              isActive: true,
              order: 2
            }),
            createSlide({
              title: 'Custom Office Solutions',
              subtitle: 'Comfort & Efficiency',
              description: 'Modern office porta cabins with professional interiors, climate control, and all necessary amenities for your business needs.',
              image: '/hero-slide-3.jpg',
              buttonText: 'Learn More',
              buttonLink: '/about',
              buttonStyle: 'outline',
              textPosition: 'center',
              isActive: true,
              order: 3
            })
          ],
          settings: {
            autoPlay: true,
            autoPlayDelay: 5000,
            showDots: true,
            showArrows: true,
            infinite: true,
            slidesToShow: 1,
            slidesToScroll: 1
          },
          isActive: true
        }
      ];

      for (const slider of defaultSliders) {
        await sliderStore.create(slider);
      }
    }

    console.log('Default data initialized successfully');
  } catch (error) {
    console.error('Error initializing default data:', error);
  }
}