export interface MockTag {
  id: string;
  name: string;
  color: string;
}

export interface MockList {
  id: string;
  name: string;
  color: string;
  icon: string;
  _count?: { tasks: number };
}

export interface MockTask {
  id: string;
  listId: string;
  parentId: string | null;
  title: string;
  note: string | null;
  completed: boolean;
  completedAt: string | null;
  dueDate: string | null;
  priority: number;
  sortOrder: number;
  createdAt: string;
  updatedAt: string;
  deletedAt?: string | null;
  isDeleted?: boolean;
  children: MockTask[];
  tags: { tag: MockTag }[];
}

export interface UserSettings {
  displayName: string;
  email: string;
  trashRetentionDays: number; // 7, 14, 30, 0 (0 means never auto-delete)
  theme: "system" | "light" | "dark";
  language: "en" | "ko" | "ja";
}

const STORAGE_KEY_LISTS = "checkflow_demo_lists";
const STORAGE_KEY_TASKS = "checkflow_demo_tasks";
const STORAGE_KEY_SETTINGS = "checkflow_user_settings";
const STORAGE_KEY_TAGS = "checkflow_custom_tags";

export const DEFAULT_TAGS: MockTag[] = [
  { id: "tag-1", name: "Dev", color: "#4B7BF5" },
  { id: "tag-2", name: "NAS", color: "#10B981" },
  { id: "tag-3", name: "Important", color: "#EF4444" },
  { id: "tag-4", name: "Routine", color: "#F59E0B" },
];

export const DEFAULT_SETTINGS: UserSettings = {
  displayName: "Demo Explorer",
  email: "demo@checkflow.local",
  trashRetentionDays: 30,
  theme: "system",
  language: "en",
};

export const INITIAL_DEMO_LISTS: MockList[] = [
  { id: "list-1", name: "🚀 Project Launch", color: "#4B7BF5", icon: "work" },
  { id: "list-2", name: "🏠 Personal & Daily", color: "#10B981", icon: "personal" },
  { id: "list-3", name: "📚 Tech Research", color: "#8B5CF6", icon: "study" },
];

export const INITIAL_DEMO_TASKS: MockTask[] = [
  {
    id: "task-1",
    listId: "list-1",
    parentId: null,
    title: "Setup Self-Hosted CheckFlow on NAS",
    note: "## 🐳 Docker Deployment Guide\n\n- Deploy with `docker compose up -d`\n- Forward port 3000 to NPM (Nginx Proxy Manager)\n- Setup SSL certificate for custom domain\n\n### 🔗 Key Endpoints\n- Web App: https://todo.yourdomain.com\n- CardDAV: https://todo.yourdomain.com/api/dav",
    completed: false,
    completedAt: null,
    dueDate: new Date(Date.now() + 86400000).toISOString(),
    priority: 3,
    sortOrder: 0,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
    deletedAt: null,
    isDeleted: false,
    tags: [{ tag: DEFAULT_TAGS[1] }, { tag: DEFAULT_TAGS[2] }],
    children: [
      {
        id: "sub-1-1",
        listId: "list-1",
        parentId: "task-1",
        title: "Configure .env environment variables",
        note: "Database URL, NextAuth secret, and port settings",
        completed: false,
        completedAt: null,
        dueDate: null,
        priority: 0,
        sortOrder: 0,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        deletedAt: null,
        isDeleted: false,
        tags: [],
        children: [
          {
            id: "sub-1-1-1",
            listId: "list-1",
            parentId: "sub-1-1",
            title: "Database connection string verification",
            note: null,
            completed: false,
            completedAt: null,
            dueDate: null,
            priority: 2,
            sortOrder: 0,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString(),
            deletedAt: null,
            isDeleted: false,
            children: [],
            tags: [{ tag: DEFAULT_TAGS[0] }],
          },
        ],
      },
      {
        id: "sub-1-2",
        listId: "list-1",
        parentId: "task-1",
        title: "Test DAVx⁵ sync on Samsung Galaxy",
        note: null,
        completed: false,
        completedAt: null,
        dueDate: null,
        priority: 2,
        sortOrder: 1,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        deletedAt: null,
        isDeleted: false,
        children: [],
        tags: [],
      },
      {
        id: "sub-1-3",
        listId: "list-1",
        parentId: "task-1",
        title: "Verify real-time sync with main list",
        note: null,
        completed: false,
        completedAt: null,
        dueDate: null,
        priority: 1,
        sortOrder: 2,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        deletedAt: null,
        isDeleted: false,
        children: [],
        tags: [],
      },
    ],
  },
  {
    id: "task-2",
    listId: "list-1",
    parentId: null,
    title: "Import existing tasks from TickTick",
    note: "1. Export CSV/ICS in TickTick Settings\n2. Click user profile at bottom-left\n3. Select 'Import Tasks'",
    completed: false,
    completedAt: null,
    dueDate: null,
    priority: 2,
    sortOrder: 1,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
    deletedAt: null,
    isDeleted: false,
    children: [],
    tags: [{ tag: DEFAULT_TAGS[3] }],
  },
];

export function getDemoStore() {
  if (typeof window === "undefined") {
    return { lists: INITIAL_DEMO_LISTS, tasks: INITIAL_DEMO_TASKS };
  }

  let lists: MockList[] = INITIAL_DEMO_LISTS;
  let tasks: MockTask[] = INITIAL_DEMO_TASKS;

  try {
    const savedLists = localStorage.getItem(STORAGE_KEY_LISTS);
    if (savedLists) lists = JSON.parse(savedLists);
    else localStorage.setItem(STORAGE_KEY_LISTS, JSON.stringify(INITIAL_DEMO_LISTS));

    const savedTasks = localStorage.getItem(STORAGE_KEY_TASKS);
    if (savedTasks) tasks = JSON.parse(savedTasks);
    else localStorage.setItem(STORAGE_KEY_TASKS, JSON.stringify(INITIAL_DEMO_TASKS));
  } catch (e) {
    console.error("Failed to read demo storage", e);
  }

  return { lists, tasks };
}

export function saveDemoStore(lists: MockList[], tasks: MockTask[]) {
  if (typeof window === "undefined") return;
  try {
    localStorage.setItem(STORAGE_KEY_LISTS, JSON.stringify(lists));
    localStorage.setItem(STORAGE_KEY_TASKS, JSON.stringify(tasks));
  } catch (e) {
    console.error("Failed to save demo storage", e);
  }
}

// User settings store
export function getUserSettings(): UserSettings {
  if (typeof window === "undefined") return DEFAULT_SETTINGS;
  try {
    const s = localStorage.getItem(STORAGE_KEY_SETTINGS);
    if (s) return { ...DEFAULT_SETTINGS, ...JSON.parse(s) };
  } catch {}
  return DEFAULT_SETTINGS;
}

export function saveUserSettings(settings: UserSettings) {
  if (typeof window === "undefined") return;
  try {
    localStorage.setItem(STORAGE_KEY_SETTINGS, JSON.stringify(settings));
  } catch {}
}

// Custom tags store
export function getCustomTags(): MockTag[] {
  if (typeof window === "undefined") return DEFAULT_TAGS;
  try {
    const t = localStorage.getItem(STORAGE_KEY_TAGS);
    if (t) return JSON.parse(t);
  } catch {}
  return DEFAULT_TAGS;
}

export function saveCustomTags(tags: MockTag[]) {
  if (typeof window === "undefined") return;
  try {
    localStorage.setItem(STORAGE_KEY_TAGS, JSON.stringify(tags));
  } catch {}
}

// Recursive tree helpers for N-depth sub-tasks
export function updateTaskInTree(tree: MockTask[], updated: MockTask): MockTask[] {
  return tree.map((node) => {
    if (node.id === updated.id) {
      return { ...updated, children: updated.children || node.children || [] };
    }
    if (node.children && node.children.length > 0) {
      return { ...node, children: updateTaskInTree(node.children, updated) };
    }
    return node;
  });
}

// Soft delete to Trash
export function moveToTrashInTree(tree: MockTask[], id: string): MockTask[] {
  return tree.map((node) => {
    if (node.id === id) {
      return { ...node, isDeleted: true, deletedAt: new Date().toISOString() };
    }
    if (node.children && node.children.length > 0) {
      return { ...node, children: moveToTrashInTree(node.children, id) };
    }
    return node;
  });
}

// Restore from Trash
export function restoreTaskInTree(tree: MockTask[], id: string): MockTask[] {
  return tree.map((node) => {
    if (node.id === id) {
      return { ...node, isDeleted: false, deletedAt: null };
    }
    if (node.children && node.children.length > 0) {
      return { ...node, children: restoreTaskInTree(node.children, id) };
    }
    return node;
  });
}

// Permanent delete
export function deleteTaskInTree(tree: MockTask[], idToDelete: string): MockTask[] {
  return tree
    .filter((node) => node.id !== idToDelete)
    .map((node) => {
      if (node.children && node.children.length > 0) {
        return { ...node, children: deleteTaskInTree(node.children, idToDelete) };
      }
      return node;
    });
}

export function emptyTrashInTree(tree: MockTask[]): MockTask[] {
  return tree
    .filter((node) => !node.isDeleted)
    .map((node) => {
      if (node.children && node.children.length > 0) {
        return { ...node, children: emptyTrashInTree(node.children) };
      }
      return node;
    });
}

export function addTaskToTree(tree: MockTask[], parentId: string | null, newTask: MockTask): MockTask[] {
  if (!parentId) {
    return [...tree, newTask];
  }
  return tree.map((node) => {
    if (node.id === parentId) {
      const currentChildren = node.children || [];
      return { ...node, children: [...currentChildren, newTask] };
    }
    if (node.children && node.children.length > 0) {
      return { ...node, children: addTaskToTree(node.children, parentId, newTask) };
    }
    return node;
  });
}

export function findTaskInTree(tree: MockTask[], id: string): MockTask | null {
  for (const node of tree) {
    if (node.id === id) return node;
    if (node.children && node.children.length > 0) {
      const found = findTaskInTree(node.children, id);
      if (found) return found;
    }
  }
  return null;
}

// Get all active tasks or all trash tasks flattened
export function getAllTrashTasks(tree: MockTask[]): MockTask[] {
  let trash: MockTask[] = [];
  for (const node of tree) {
    if (node.isDeleted) {
      trash.push(node);
    }
    if (node.children && node.children.length > 0) {
      trash = trash.concat(getAllTrashTasks(node.children));
    }
  }
  return trash;
}

// Filter tasks by custom tag
export function filterTasksByTag(tree: MockTask[], tagName: string): MockTask[] {
  let matched: MockTask[] = [];
  for (const node of tree) {
    if (!node.isDeleted && node.tags?.some((t) => t.tag.name.toLowerCase() === tagName.toLowerCase())) {
      matched.push(node);
    }
    if (node.children && node.children.length > 0) {
      matched = matched.concat(filterTasksByTag(node.children, tagName));
    }
  }
  return matched;
}