/**
 * Seed Script for Project Manager App
 * Creates demo data in Firebase Firestore
 * 
 * Run with: npm run seed
 * or: npx tsx scripts/seed.ts
 */

import { initializeApp } from 'firebase/app';
import {
  getFirestore,
  collection,
  addDoc,
  serverTimestamp,
  Timestamp,
} from 'firebase/firestore';

// Firebase configuration - replace with your values
const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
  storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

// Collection references
const projectsCollection = collection(db, 'projects');
const tasksCollection = collection(db, 'tasks');
const commentsCollection = collection(db, 'comments');
const activityLogsCollection = collection(db, 'activityLogs');

// Helper to generate dates
function daysFromNow(days: number): Date {
  const date = new Date();
  date.setDate(date.getDate() + days);
  return date;
}

function daysAgo(days: number): Date {
  const date = new Date();
  date.setDate(date.getDate() - days);
  return date;
}

// Demo data
const demoProjects = [
  {
    name: 'Website Redesign',
    description: 'Complete redesign of the company website with modern UI/UX principles.',
    status: 'active',
    startDate: daysAgo(14),
    endDate: daysFromNow(30),
    color: '#8B5CF6',
    taskCount: 8,
    completedTaskCount: 3,
  },
  {
    name: 'Mobile App Development',
    description: 'Build a cross-platform mobile application for iOS and Android.',
    status: 'active',
    startDate: daysAgo(7),
    endDate: daysFromNow(60),
    color: '#3B82F6',
    taskCount: 6,
    completedTaskCount: 1,
  },
  {
    name: 'Marketing Campaign Q1',
    description: 'Plan and execute Q1 marketing campaigns across all channels.',
    status: 'planned',
    startDate: daysFromNow(7),
    endDate: daysFromNow(45),
    color: '#10B981',
    taskCount: 5,
    completedTaskCount: 0,
  },
  {
    name: 'Product Launch Event',
    description: 'Organize and host the annual product launch event.',
    status: 'completed',
    startDate: daysAgo(60),
    endDate: daysAgo(30),
    color: '#F59E0B',
    taskCount: 4,
    completedTaskCount: 4,
  },
];

const demoTasksByProject: Record<number, Array<{
  title: string;
  description: string;
  status: string;
  priority: string;
  dueDate: Date;
  assignedTo: string;
  order: number;
}>> = {
  0: [ // Website Redesign
    {
      title: 'Design system setup',
      description: 'Create a comprehensive design system with color palettes, typography, and components.',
      status: 'done',
      priority: 'high',
      dueDate: daysAgo(7),
      assignedTo: 'Sarah Chen',
      order: 0,
    },
    {
      title: 'Homepage wireframe',
      description: 'Create wireframes for the new homepage layout.',
      status: 'done',
      priority: 'high',
      dueDate: daysAgo(5),
      assignedTo: 'Mike Johnson',
      order: 1,
    },
    {
      title: 'Homepage implementation',
      description: 'Implement the homepage based on approved wireframes.',
      status: 'inprogress',
      priority: 'high',
      dueDate: daysFromNow(5),
      assignedTo: 'Alex Rivera',
      order: 0,
    },
    {
      title: 'About page design',
      description: 'Design the about us page with team section.',
      status: 'inprogress',
      priority: 'medium',
      dueDate: daysFromNow(7),
      assignedTo: 'Sarah Chen',
      order: 1,
    },
    {
      title: 'Contact form integration',
      description: 'Implement and test the contact form with email notifications.',
      status: 'todo',
      priority: 'medium',
      dueDate: daysFromNow(14),
      assignedTo: 'Alex Rivera',
      order: 0,
    },
    {
      title: 'Blog section setup',
      description: 'Create the blog layout and integrate with CMS.',
      status: 'todo',
      priority: 'low',
      dueDate: daysFromNow(21),
      assignedTo: 'Mike Johnson',
      order: 1,
    },
    {
      title: 'Performance optimization',
      description: 'Optimize images, implement lazy loading, and improve Core Web Vitals.',
      status: 'review',
      priority: 'high',
      dueDate: daysFromNow(10),
      assignedTo: 'Alex Rivera',
      order: 0,
    },
    {
      title: 'SEO implementation',
      description: 'Add meta tags, structured data, and sitemap.',
      status: 'done',
      priority: 'medium',
      dueDate: daysAgo(3),
      assignedTo: 'Sarah Chen',
      order: 2,
    },
  ],
  1: [ // Mobile App Development
    {
      title: 'App architecture design',
      description: 'Design the overall app architecture and data flow.',
      status: 'done',
      priority: 'high',
      dueDate: daysAgo(3),
      assignedTo: 'David Kim',
      order: 0,
    },
    {
      title: 'Authentication flow',
      description: 'Implement user authentication with social login options.',
      status: 'inprogress',
      priority: 'high',
      dueDate: daysFromNow(7),
      assignedTo: 'Emily Wang',
      order: 0,
    },
    {
      title: 'Dashboard screen',
      description: 'Build the main dashboard with key metrics and navigation.',
      status: 'inprogress',
      priority: 'high',
      dueDate: daysFromNow(10),
      assignedTo: 'David Kim',
      order: 1,
    },
    {
      title: 'Push notifications',
      description: 'Set up push notification service and implement handlers.',
      status: 'todo',
      priority: 'medium',
      dueDate: daysFromNow(20),
      assignedTo: 'Emily Wang',
      order: 0,
    },
    {
      title: 'Offline mode',
      description: 'Implement offline data caching and sync.',
      status: 'todo',
      priority: 'medium',
      dueDate: daysFromNow(30),
      assignedTo: 'David Kim',
      order: 1,
    },
    {
      title: 'App store submission',
      description: 'Prepare app store listings and submit for review.',
      status: 'todo',
      priority: 'low',
      dueDate: daysFromNow(50),
      assignedTo: 'Emily Wang',
      order: 2,
    },
  ],
  2: [ // Marketing Campaign Q1
    {
      title: 'Campaign strategy',
      description: 'Define campaign objectives, target audience, and KPIs.',
      status: 'todo',
      priority: 'high',
      dueDate: daysFromNow(10),
      assignedTo: 'Jessica Lee',
      order: 0,
    },
    {
      title: 'Content calendar',
      description: 'Create content calendar for all channels.',
      status: 'todo',
      priority: 'high',
      dueDate: daysFromNow(14),
      assignedTo: 'Tom Wilson',
      order: 1,
    },
    {
      title: 'Social media assets',
      description: 'Design graphics and videos for social media.',
      status: 'todo',
      priority: 'medium',
      dueDate: daysFromNow(21),
      assignedTo: 'Jessica Lee',
      order: 2,
    },
    {
      title: 'Email sequences',
      description: 'Write and set up automated email sequences.',
      status: 'todo',
      priority: 'medium',
      dueDate: daysFromNow(25),
      assignedTo: 'Tom Wilson',
      order: 3,
    },
    {
      title: 'Analytics setup',
      description: 'Configure tracking and dashboards for campaign metrics.',
      status: 'todo',
      priority: 'low',
      dueDate: daysFromNow(30),
      assignedTo: 'Jessica Lee',
      order: 4,
    },
  ],
  3: [ // Product Launch Event
    {
      title: 'Venue booking',
      description: 'Research and book venue for 200+ attendees.',
      status: 'done',
      priority: 'high',
      dueDate: daysAgo(50),
      assignedTo: 'Amanda Price',
      order: 0,
    },
    {
      title: 'Speaker lineup',
      description: 'Confirm keynote speakers and session hosts.',
      status: 'done',
      priority: 'high',
      dueDate: daysAgo(45),
      assignedTo: 'Robert Taylor',
      order: 1,
    },
    {
      title: 'Event registration',
      description: 'Set up registration page and ticket system.',
      status: 'done',
      priority: 'high',
      dueDate: daysAgo(40),
      assignedTo: 'Amanda Price',
      order: 2,
    },
    {
      title: 'Post-event follow-up',
      description: 'Send thank you emails and gather feedback.',
      status: 'done',
      priority: 'medium',
      dueDate: daysAgo(25),
      assignedTo: 'Robert Taylor',
      order: 3,
    },
  ],
};

const demoComments = [
  'Great progress on this! Let me know if you need any help.',
  'Updated the design based on feedback from the team.',
  'Can we schedule a quick call to discuss this further?',
  'Looks good to me. Moving to review.',
  'Found a small issue. Adding some notes.',
];

const actors = ['Sarah Chen', 'Mike Johnson', 'Alex Rivera', 'David Kim', 'Emily Wang', 'Jessica Lee', 'Tom Wilson', 'Amanda Price', 'Robert Taylor'];

async function seed() {
  console.log('🌱 Starting seed process...\n');

  try {
    // Create projects and store their IDs
    console.log('📁 Creating projects...');
    const projectIds: string[] = [];

    for (const project of demoProjects) {
      const docRef = await addDoc(projectsCollection, {
        ...project,
        startDate: Timestamp.fromDate(project.startDate),
        endDate: Timestamp.fromDate(project.endDate),
        createdAt: serverTimestamp(),
        updatedAt: serverTimestamp(),
      });
      projectIds.push(docRef.id);
      console.log(`  ✓ Created project: ${project.name}`);
    }

    // Create tasks for each project
    console.log('\n📋 Creating tasks...');
    const taskIds: string[] = [];

    for (let i = 0; i < projectIds.length; i++) {
      const projectId = projectIds[i];
      const tasks = demoTasksByProject[i] || [];

      for (const task of tasks) {
        const docRef = await addDoc(tasksCollection, {
          ...task,
          projectId,
          dueDate: Timestamp.fromDate(task.dueDate),
          subtasks: [],
          attachments: [],
          createdAt: serverTimestamp(),
          updatedAt: serverTimestamp(),
        });
        taskIds.push(docRef.id);
        console.log(`  ✓ Created task: ${task.title}`);
      }
    }

    // Create some comments
    console.log('\n💬 Creating comments...');
    for (let i = 0; i < 5; i++) {
      const taskIndex = Math.floor(Math.random() * taskIds.length);
      const projectIndex = Math.floor(Math.random() * projectIds.length);
      const actorIndex = Math.floor(Math.random() * actors.length);
      const commentIndex = Math.floor(Math.random() * demoComments.length);

      await addDoc(commentsCollection, {
        taskId: taskIds[taskIndex],
        projectId: projectIds[projectIndex],
        authorName: actors[actorIndex],
        content: demoComments[commentIndex],
        createdAt: serverTimestamp(),
        updatedAt: serverTimestamp(),
      });
      console.log(`  ✓ Created comment by ${actors[actorIndex]}`);
    }

    // Create activity logs
    console.log('\n📊 Creating activity logs...');
    const activities = [
      { action: 'project_created', description: 'Created project "Website Redesign"' },
      { action: 'task_created', description: 'Created task "Homepage wireframe"' },
      { action: 'task_moved', description: 'Moved task "Design system setup" to Done' },
      { action: 'comment_added', description: 'Added comment on "Homepage implementation"' },
      { action: 'project_updated', description: 'Updated project "Mobile App Development"' },
    ];

    for (const activity of activities) {
      const projectIndex = Math.floor(Math.random() * projectIds.length);
      const actorIndex = Math.floor(Math.random() * actors.length);

      await addDoc(activityLogsCollection, {
        projectId: projectIds[projectIndex],
        action: activity.action,
        actorName: actors[actorIndex],
        description: activity.description,
        createdAt: serverTimestamp(),
        updatedAt: serverTimestamp(),
      });
      console.log(`  ✓ Created activity: ${activity.action}`);
    }

    console.log('\n✅ Seed completed successfully!');
    console.log(`   - ${projectIds.length} projects created`);
    console.log(`   - ${taskIds.length} tasks created`);
    console.log(`   - 5 comments created`);
    console.log(`   - ${activities.length} activity logs created`);

  } catch (error) {
    console.error('\n❌ Seed failed:', error);
    process.exit(1);
  }

  process.exit(0);
}

// Run the seed function
seed();

