import type { TaskResponse, KanbanResponse, CompletionResponse } from '@/lib/api/tasks';

const now = new Date();
const dayMs = 86400000;

function daysFromNow(days: number): string {
  return new Date(now.getTime() + days * dayMs).toISOString().split('T')[0];
}

function daysAgo(days: number): string {
  return new Date(now.getTime() - days * dayMs).toISOString();
}

export const demoTasks: TaskResponse[] = [
  // Overdue (2)
  {
    id: 1, residence_id: 1, residence_name: 'Maple Street House',
    title: 'Replace HVAC filter', description: 'Replace the air filter in the furnace',
    category_id: 3, category: { id: 3, name: 'HVAC', icon: '❄️', color: '#6366F1' },
    priority_id: 3, priority: { id: 3, name: 'High', icon: '🟠', color: '#F97316' },
    frequency_id: 3, in_progress: false, is_cancelled: false, is_archived: false,
    due_date: daysFromNow(-5), next_due_date: daysFromNow(-5),
    completion_count: 2, last_completed_at: daysAgo(35),
    created_by_id: 1, created_at: daysAgo(60), updated_at: daysAgo(5),
  },
  {
    id: 2, residence_id: 1, residence_name: 'Maple Street House',
    title: 'Fix leaking faucet', description: 'Kitchen faucet drips when turned off',
    category_id: 1, category: { id: 1, name: 'Plumbing', icon: '🔧', color: '#3B82F6' },
    priority_id: 4, priority: { id: 4, name: 'Urgent', icon: '🔴', color: '#EF4444' },
    in_progress: false, is_cancelled: false, is_archived: false,
    due_date: daysFromNow(-2), next_due_date: daysFromNow(-2),
    estimated_cost: 150, contractor_id: 1,
    contractor: { id: 1, name: 'Mike Johnson', company: 'Johnson Plumbing' },
    completion_count: 0,
    created_by_id: 1, created_at: daysAgo(10), updated_at: daysAgo(2),
  },

  // Due Today (2)
  {
    id: 3, residence_id: 1, residence_name: 'Maple Street House',
    title: 'Test smoke detectors', description: 'Monthly smoke detector test',
    category_id: 9, category: { id: 9, name: 'Safety', icon: '🛡️', color: '#EF4444' },
    priority_id: 3, priority: { id: 3, name: 'High', icon: '🟠', color: '#F97316' },
    frequency_id: 3, in_progress: false, is_cancelled: false, is_archived: false,
    due_date: daysFromNow(0), next_due_date: daysFromNow(0),
    completion_count: 5,
    created_by_id: 1, created_at: daysAgo(180), updated_at: daysAgo(0),
  },
  {
    id: 4, residence_id: 2, residence_name: 'Downtown Apartment',
    title: 'Clean kitchen appliances', description: 'Deep clean oven, microwave, and fridge',
    category_id: 5, category: { id: 5, name: 'Cleaning', icon: '🧹', color: '#EC4899' },
    priority_id: 2, priority: { id: 2, name: 'Medium', icon: '🟡', color: '#F59E0B' },
    frequency_id: 3, in_progress: false, is_cancelled: false, is_archived: false,
    due_date: daysFromNow(0), next_due_date: daysFromNow(0),
    completion_count: 3,
    created_by_id: 1, created_at: daysAgo(90), updated_at: daysAgo(0),
  },

  // Due Soon (3)
  {
    id: 5, residence_id: 1, residence_name: 'Maple Street House',
    title: 'Mow the lawn', description: 'Front and back yard',
    category_id: 4, category: { id: 4, name: 'Landscaping', icon: '🌿', color: '#22C55E' },
    priority_id: 2, priority: { id: 2, name: 'Medium', icon: '🟡', color: '#F59E0B' },
    frequency_id: 1, in_progress: false, is_cancelled: false, is_archived: false,
    due_date: daysFromNow(3), next_due_date: daysFromNow(3),
    completion_count: 10,
    created_by_id: 1, created_at: daysAgo(120), updated_at: daysAgo(4),
  },
  {
    id: 6, residence_id: 1, residence_name: 'Maple Street House',
    title: 'Clean gutters', description: 'Remove leaves and debris from gutters',
    category_id: 8, category: { id: 8, name: 'Exterior', icon: '🏡', color: '#14B8A6' },
    priority_id: 2, priority: { id: 2, name: 'Medium', icon: '🟡', color: '#F59E0B' },
    frequency_id: 5, in_progress: false, is_cancelled: false, is_archived: false,
    due_date: daysFromNow(5), next_due_date: daysFromNow(5),
    estimated_cost: 200,
    completion_count: 1,
    created_by_id: 1, created_at: daysAgo(200), updated_at: daysAgo(5),
  },
  {
    id: 7, residence_id: 2, residence_name: 'Downtown Apartment',
    title: 'Check fire extinguisher', description: 'Verify pressure gauge and expiration',
    category_id: 9, category: { id: 9, name: 'Safety', icon: '🛡️', color: '#EF4444' },
    priority_id: 3, priority: { id: 3, name: 'High', icon: '🟠', color: '#F97316' },
    frequency_id: 6, in_progress: false, is_cancelled: false, is_archived: false,
    due_date: daysFromNow(7), next_due_date: daysFromNow(7),
    completion_count: 0,
    created_by_id: 1, created_at: daysAgo(30), updated_at: daysAgo(7),
  },

  // Upcoming (4)
  {
    id: 8, residence_id: 1, residence_name: 'Maple Street House',
    title: 'Service water heater', description: 'Annual flush and inspection',
    category_id: 1, category: { id: 1, name: 'Plumbing', icon: '🔧', color: '#3B82F6' },
    priority_id: 2, priority: { id: 2, name: 'Medium', icon: '🟡', color: '#F59E0B' },
    frequency_id: 6, in_progress: false, is_cancelled: false, is_archived: false,
    due_date: daysFromNow(45), next_due_date: daysFromNow(45),
    estimated_cost: 200, contractor_id: 1,
    contractor: { id: 1, name: 'Mike Johnson', company: 'Johnson Plumbing' },
    completion_count: 1,
    created_by_id: 1, created_at: daysAgo(365), updated_at: daysAgo(45),
  },
  {
    id: 9, residence_id: 1, residence_name: 'Maple Street House',
    title: 'Paint exterior trim', description: 'Touch up paint on window and door trim',
    category_id: 6, category: { id: 6, name: 'Painting', icon: '🎨', color: '#8B5CF6' },
    priority_id: 1, priority: { id: 1, name: 'Low', icon: '🟢', color: '#22C55E' },
    in_progress: false, is_cancelled: false, is_archived: false,
    due_date: daysFromNow(60), next_due_date: daysFromNow(60),
    estimated_cost: 500,
    completion_count: 0,
    created_by_id: 1, created_at: daysAgo(20), updated_at: daysAgo(20),
  },
  {
    id: 10, residence_id: 2, residence_name: 'Downtown Apartment',
    title: 'Replace light bulbs', description: 'Switch to LED bulbs in all fixtures',
    category_id: 2, category: { id: 2, name: 'Electrical', icon: '⚡', color: '#F59E0B' },
    priority_id: 1, priority: { id: 1, name: 'Low', icon: '🟢', color: '#22C55E' },
    in_progress: false, is_cancelled: false, is_archived: false,
    due_date: daysFromNow(30), next_due_date: daysFromNow(30),
    estimated_cost: 40,
    completion_count: 0,
    created_by_id: 1, created_at: daysAgo(5), updated_at: daysAgo(5),
  },
  {
    id: 11, residence_id: 1, residence_name: 'Maple Street House',
    title: 'Inspect roof', description: 'Annual roof inspection for damage',
    category_id: 8, category: { id: 8, name: 'Exterior', icon: '🏡', color: '#14B8A6' },
    priority_id: 2, priority: { id: 2, name: 'Medium', icon: '🟡', color: '#F59E0B' },
    frequency_id: 6, in_progress: false, is_cancelled: false, is_archived: false,
    due_date: daysFromNow(90), next_due_date: daysFromNow(90),
    estimated_cost: 300, contractor_id: 5,
    contractor: { id: 5, name: 'Tom Williams', company: 'Williams Roofing' },
    completion_count: 1,
    created_by_id: 1, created_at: daysAgo(300), updated_at: daysAgo(90),
  },

  // In Progress (1)
  {
    id: 12, residence_id: 1, residence_name: 'Maple Street House',
    title: 'Repair deck boards', description: 'Replace warped deck boards on back patio',
    category_id: 8, category: { id: 8, name: 'Exterior', icon: '🏡', color: '#14B8A6' },
    priority_id: 3, priority: { id: 3, name: 'High', icon: '🟠', color: '#F97316' },
    in_progress: true, is_cancelled: false, is_archived: false,
    due_date: daysFromNow(10), next_due_date: daysFromNow(10),
    estimated_cost: 400,
    completion_count: 0,
    created_by_id: 1, created_at: daysAgo(14), updated_at: daysAgo(3),
  },

  // Completed (3)
  {
    id: 13, residence_id: 1, residence_name: 'Maple Street House',
    title: 'Replace kitchen faucet', description: 'Install new pull-down sprayer faucet',
    category_id: 1, category: { id: 1, name: 'Plumbing', icon: '🔧', color: '#3B82F6' },
    priority_id: 2, priority: { id: 2, name: 'Medium', icon: '🟡', color: '#F59E0B' },
    in_progress: false, is_cancelled: false, is_archived: false,
    completion_count: 1, last_completed_at: daysAgo(3),
    actual_cost: 175,
    created_by_id: 1, created_at: daysAgo(30), updated_at: daysAgo(3),
  },
  {
    id: 14, residence_id: 2, residence_name: 'Downtown Apartment',
    title: 'Deep clean bathroom', description: 'Scrub tiles, clean grout, organize cabinets',
    category_id: 5, category: { id: 5, name: 'Cleaning', icon: '🧹', color: '#EC4899' },
    priority_id: 1, priority: { id: 1, name: 'Low', icon: '🟢', color: '#22C55E' },
    frequency_id: 3, in_progress: false, is_cancelled: false, is_archived: false,
    completion_count: 4, last_completed_at: daysAgo(1),
    next_due_date: daysFromNow(29),
    created_by_id: 1, created_at: daysAgo(120), updated_at: daysAgo(1),
  },
  {
    id: 15, residence_id: 1, residence_name: 'Maple Street House',
    title: 'Trim hedges', description: 'Shape front yard hedges',
    category_id: 4, category: { id: 4, name: 'Landscaping', icon: '🌿', color: '#22C55E' },
    priority_id: 1, priority: { id: 1, name: 'Low', icon: '🟢', color: '#22C55E' },
    frequency_id: 3, in_progress: false, is_cancelled: false, is_archived: false,
    completion_count: 6, last_completed_at: daysAgo(2),
    next_due_date: daysFromNow(28),
    created_by_id: 1, created_at: daysAgo(180), updated_at: daysAgo(2),
  },
];

// Build kanban columns from tasks
export function buildKanbanResponse(tasks: TaskResponse[]): KanbanResponse {
  const overdue: TaskResponse[] = [];
  const dueSoon: TaskResponse[] = [];
  const upcoming: TaskResponse[] = [];
  const inProgress: TaskResponse[] = [];
  const completed: TaskResponse[] = [];

  const today = new Date();
  today.setHours(0, 0, 0, 0);

  for (const task of tasks) {
    if (task.is_cancelled || task.is_archived) continue;

    // Completed: has completions and no next_due_date (one-time), or last_completed recently
    const isCompleted = task.completion_count > 0 && !task.next_due_date;
    // Also treat as completed if last_completed_at is recent and task.next_due_date is far out
    const recentlyCompleted = task.last_completed_at && task.next_due_date &&
      new Date(task.next_due_date) > new Date(today.getTime() + 14 * dayMs);

    if (task.in_progress) {
      inProgress.push(task);
    } else if (isCompleted || recentlyCompleted) {
      completed.push(task);
    } else if (task.next_due_date || task.due_date) {
      const dueDate = new Date(task.next_due_date || task.due_date!);
      dueDate.setHours(0, 0, 0, 0);
      const diffDays = Math.floor((dueDate.getTime() - today.getTime()) / dayMs);

      if (diffDays < 0) {
        overdue.push(task);
      } else if (diffDays <= 7) {
        dueSoon.push(task);
      } else {
        upcoming.push(task);
      }
    } else {
      upcoming.push(task);
    }
  }

  const columns = [
    { name: 'overdue', display_name: 'Overdue', count: overdue.length, tasks: overdue },
    { name: 'due_soon', display_name: 'Due Soon', count: dueSoon.length, tasks: dueSoon },
    { name: 'upcoming', display_name: 'Upcoming', count: upcoming.length, tasks: upcoming },
    { name: 'in_progress', display_name: 'In Progress', count: inProgress.length, tasks: inProgress },
    { name: 'completed', display_name: 'Completed', count: completed.length, tasks: completed },
  ];

  return {
    columns,
    total_summary: {
      total: tasks.filter(t => !t.is_cancelled && !t.is_archived).length,
      overdue: overdue.length,
      due_soon: dueSoon.length,
      upcoming: upcoming.length,
      in_progress: inProgress.length,
      completed: completed.length,
    },
  };
}

export const demoCompletions: CompletionResponse[] = [
  {
    id: 1, task_id: 13, task_title: 'Replace kitchen faucet',
    completed_at: daysAgo(3),
    completed_by_id: 1,
    completed_by: { id: 1, username: 'demo_user', first_name: 'Demo', last_name: 'User' },
    notes: 'Installed new Moen pull-down sprayer. Works great!',
    actual_cost: 175,
    rating: 5,
    images: [],
    created_at: daysAgo(3),
  },
  {
    id: 2, task_id: 14, task_title: 'Deep clean bathroom',
    completed_at: daysAgo(1),
    completed_by_id: 1,
    completed_by: { id: 1, username: 'demo_user', first_name: 'Demo', last_name: 'User' },
    notes: 'Used new grout cleaner — big improvement.',
    images: [],
    created_at: daysAgo(1),
  },
  {
    id: 3, task_id: 15, task_title: 'Trim hedges',
    completed_at: daysAgo(2),
    completed_by_id: 1,
    completed_by: { id: 1, username: 'demo_user', first_name: 'Demo', last_name: 'User' },
    notes: 'Shaped front hedges nicely.',
    images: [],
    created_at: daysAgo(2),
  },
];
