import type { UserReport, User, Client, FitnessProfile } from "@fitai/shared";

// Mock data for testing
const mockUser: User = {
  id: "user_123",
  email: "john.doe@example.com",
  firstName: "John",
  lastName: "Doe",
  role: "client",
  phone: "555-1234",
  createdAt: new Date("2024-01-15"),
  updatedAt: new Date("2024-01-15"),
};

const mockClient: Client = {
  id: "client_123",
  userId: "user_123",
  membershipType: "premium",
  membershipStatus: "active",
  joinDate: new Date("2024-01-15"),
};

const mockProfile: FitnessProfile = {
  id: "profile_123",
  userId: "user_123",
  height: 175,
  weight: 70,
  age: 30,
  gender: "male",
  activityLevel: "moderately_active",
  createdAt: new Date("2024-01-15"),
  updatedAt: new Date("2024-01-15"),
};

const mockReport: UserReport = {
  userId: "user_123",
  user: mockUser,
  client: mockClient,
  fitnessProfile: mockProfile,
  reportPeriod: {
    startDate: "2024-01-01",
    endDate: "2024-01-31",
  },
  weeklyCheckIns: [
    {
      weekStart: "2024-01-01",
      weekEnd: "2024-01-07",
      totalCheckIns: 4,
      totalTimeMinutes: 240,
      averageDurationMinutes: 60,
      checkInsByType: [
        { type: "gym", count: 3 },
        { type: "class", count: 1 },
      ],
    },
    {
      weekStart: "2024-01-08",
      weekEnd: "2024-01-14",
      totalCheckIns: 5,
      totalTimeMinutes: 300,
      averageDurationMinutes: 60,
      checkInsByType: [
        { type: "gym", count: 4 },
        { type: "class", count: 1 },
      ],
    },
  ],
  nutrition: {
    dailySummaries: [
      {
        date: "2024-01-01",
        totalCalories: 2000,
        calorieGoal: 2200,
        caloriesDelta: -200,
        mealsCount: 3,
      },
      {
        date: "2024-01-02",
        totalCalories: 2300,
        calorieGoal: 2200,
        caloriesDelta: 100,
        mealsCount: 4,
      },
    ],
    averageDailyCalories: 2150,
    totalDays: 2,
    daysMetGoal: 1,
  },
  hydration: {
    dailySummaries: [
      {
        date: "2024-01-01",
        totalWater: 2000,
        waterGoal: 2500,
        hydrationPercentage: 80,
      },
      {
        date: "2024-01-02",
        totalWater: 2600,
        waterGoal: 2500,
        hydrationPercentage: 104,
      },
    ],
    averageDailyWater: 2300,
    totalDays: 2,
    daysMetGoal: 1,
  },
  goals: {
    active: [
      {
        id: "goal_1",
        userId: "user_123",
        goalType: "weight_target",
        title: "Lose 5kg",
        description: "Lose weight for summer",
        targetValue: 65,
        currentValue: 70,
        unit: "kg",
        startDate: new Date("2024-01-01"),
        status: "active",
        progress: 0,
        priority: "high",
        createdAt: new Date("2024-01-01"),
        updatedAt: new Date("2024-01-01"),
      },
    ],
    completed: [
      {
        id: "goal_2",
        userId: "user_123",
        goalType: "strength_milestone",
        title: "Bench press 100kg",
        targetValue: 100,
        currentValue: 100,
        unit: "kg",
        startDate: new Date("2023-11-01"),
        completedDate: new Date("2023-12-15"),
        status: "completed",
        progress: 100,
        priority: "medium",
        createdAt: new Date("2023-11-01"),
        updatedAt: new Date("2023-12-15"),
      },
    ],
    totalActive: 1,
    totalCompleted: 1,
    averageProgress: 0,
  },
  profileHistory: [
    {
      changeType: "weight",
      fieldName: "weight",
      previousValue: "72",
      newValue: "70",
      changedAt: new Date("2024-01-15"),
    },
  ],
  recommendations: {
    accepted: [
      {
        id: "rec_1",
        userId: "user_123",
        fitnessProfileId: "profile_123",
        recommendationText: "Increase protein intake to 150g per day",
        activityPlan: "High protein diet",
        dietPlan: "Protein focused",
        status: "approved",
        generatedAt: new Date("2024-01-10"),
        approvedAt: new Date("2024-01-11"),
        approvedBy: "user_trainer",
        createdAt: new Date("2024-01-10"),
        updatedAt: new Date("2024-01-11"),
      },
    ],
    rejected: [],
    pending: [
      {
        id: "rec_2",
        userId: "user_123",
        fitnessProfileId: "profile_123",
        recommendationText: "Try HIIT workouts 3 times per week",
        activityPlan: "HIIT training",
        dietPlan: "No change",
        status: "pending",
        generatedAt: new Date("2024-01-20"),
        createdAt: new Date("2024-01-20"),
        updatedAt: new Date("2024-01-20"),
      },
    ],
    totalAccepted: 1,
    totalRejected: 0,
    totalPending: 1,
  },
  generatedAt: new Date(),
};

// Test function
export async function testPDFGeneration() {
  try {
    const { generateReportPDFBase64 } = await import(
      "@/lib/pdf/report-helpers"
    );

    console.log("Generating PDF from mock report...");
    const pdfBase64 = generateReportPDFBase64(mockReport);

    console.log(`PDF generated successfully!`);
    console.log(`PDF size: ${Math.round(pdfBase64.length / 1024)} KB`);

    // Verify it's a valid base64 string
    if (pdfBase64.startsWith("JVBERi0")) {
      console.log("✓ PDF is valid (starts with PDF header)");
    } else {
      console.log("✗ PDF is invalid");
    }

    return true;
  } catch (error) {
    console.error("✗ PDF generation failed:", error);
    return false;
  }
}

// Run if executed directly
if (typeof window === "undefined" && process.argv[1]?.includes("test-pdf")) {
  testPDFGeneration()
    .then((success) => {
      process.exit(success ? 0 : 1);
    })
    .catch((err) => {
      console.error(err);
      process.exit(1);
    });
}

export default testPDFGeneration;
