'use client';

import { create } from 'zustand';
import { Product } from '@ftb/shared';
import { api } from '@/lib/api';
import { shouldPersistRemoteOverview } from '@/lib/product-overview-persistence';
import { loadServerData, saveServerData } from '@/lib/server-data';
import type { Stage, Role } from '@/lib/stage';
import type { Priority, VersionLinks } from '@/lib/derive';

interface VersionMember {
  role: Role;
  name: string;
}

interface RoleProgress {
  role: Role;
  percent: number;
  daysSpent: number;
}

interface VersionItem {
  id: string;
  name: string;
  status?: string;
  releaseDate: string | null;
  createdAt: string;
  currentStage?: Stage;
  startDate?: string | null;
  expectedReleaseDate?: string | null;
  members?: VersionMember[];
  progress?: RoleProgress[];
  priority?: Priority;
  links?: VersionLinks;
}

const MOCK_OVERVIEW: ProductOverview[] = [];

interface ProductWithCount {
  id: string;
  name: string;
  description: string;
  createdAt: string;
  updatedAt: string;
  _count?: { requirements: number; projects: number; versions?: number };
}

interface ProductOverview extends ProductWithCount {
  projects: { id: string; name: string; description: string; createdAt: string }[];
  versions: VersionItem[];
}

interface ProductState {
  products: ProductWithCount[];
  overview: ProductOverview[];
  currentProduct: (Product & { requirements?: any[]; versions?: any[] }) | null;
  loading: boolean;
  error: string | null;
  fetchProducts: () => Promise<void>;
  fetchOverview: () => Promise<void>;
  fetchProduct: (id: string) => Promise<void>;
  createProduct: (data: { name: string; description?: string }) => Promise<void>;
  updateProduct: (id: string, data: { name?: string; description?: string }) => Promise<void>;
  deleteProduct: (id: string) => Promise<void>;
  reorderProducts: (ids: string[]) => void;
  migrateAndDeleteProduct: (sourceId: string, targetId: string) => void;
  createProject: (productId: string, data: { name: string; description?: string }) => void;
  updateProject: (productId: string, projectId: string, data: { name?: string; description?: string }) => void;
  createVersion: (productId: string, data: { name: string; status: string }) => void;
  updateVersion: (productId: string, versionId: string, data: Partial<VersionItem>) => void;
  deleteVersion: (productId: string, versionId: string) => void;
  deleteProject: (productId: string, projectId: string) => void;
}

export const useProductStore = create<ProductState>((set, get) => ({
  products: [],
  overview: [],
  currentProduct: null,
  loading: false,
  error: null,

  fetchProducts: async () => {
    set({ loading: true, error: null });
    try {
      const products = await api.get<ProductWithCount[]>('/products');
      set({ products, loading: false });
    } catch {
      set({ products: [], error: null, loading: false });
    }
  },

  fetchOverview: async () => {
    if (get().overview.length > 0) return;
    const cached = await loadStoredOverview();
    if (cached) {
      // 有本地缓存，直接用，不再调远端覆盖（mock 模式核心数据在本地）
      set({ overview: cached, loading: false });
      return;
    }
    set({ loading: true, error: null });
    try {
      const overview = await api.get<ProductOverview[]>('/products/overview');
      set({ overview, loading: false });
      if (shouldPersistRemoteOverview(overview)) {
        saveStoredOverview(overview);
      }
    } catch {
      set({ overview: MOCK_OVERVIEW, error: null, loading: false });
    }
  },

  fetchProduct: async (id) => {
    set({ loading: true, error: null });
    try {
      const product = await api.get<Product>(`/products/${id}`);
      set({ currentProduct: product, loading: false });
    } catch {
      const found = get().overview.find((p) => p.id === id);
      if (found) {
        set({ currentProduct: found as any, loading: false });
      } else {
        set({ error: '产品不存在', loading: false });
      }
    }
  },

  createProduct: async (data) => {
    // 直接本地新增（mock 模式核心，保留远端兼容但不依赖）
    const newProduct: ProductOverview = {
      id: `local-${Date.now()}`,
      name: data.name || '',
      description: data.description || '',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      projects: [],
      versions: [],
      _count: { requirements: 0, projects: 0, versions: 0 },
    };
    const updated = [newProduct, ...get().overview];
    set({ overview: updated });
    saveStoredOverview(updated);
    // 异步尝试同步远端（失败也无所谓，本地已更新）
    try { await api.post('/products', data); } catch {}
  },

  updateProduct: async (id, data) => {
    try {
      await api.patch(`/products/${id}`, data);
      await get().fetchOverview();
    } catch {
      const updated = get().overview.map((p) =>
        p.id === id ? { ...p, ...data } : p,
      );
      set({ overview: updated });
      saveStoredOverview(updated);
    }
  },

  deleteProduct: async (id) => {
    try {
      await api.delete(`/products/${id}`);
    } catch {}
    const updated = get().overview.filter((p) => p.id !== id);
    set({
      products: get().products.filter((p) => p.id !== id),
      overview: updated,
    });
    saveStoredOverview(updated);
  },

  reorderProducts: (ids) => {
    const map = new Map(get().overview.map((p) => [p.id, p]));
    const reordered = ids.map((id) => map.get(id)).filter(Boolean) as ProductOverview[];
    set({ overview: reordered });
    saveStoredOverview(reordered);
  },

  migrateAndDeleteProduct: (sourceId, targetId) => {
    const source = get().overview.find((p) => p.id === sourceId);
    const target = get().overview.find((p) => p.id === targetId);
    if (!source || !target) return;

    const migratedTarget: ProductOverview = {
      ...target,
      projects: [...target.projects, ...source.projects],
      versions: [...target.versions, ...source.versions],
      _count: {
        requirements: (target._count?.requirements ?? 0) + (source._count?.requirements ?? 0),
        projects: (target._count?.projects ?? 0) + (source._count?.projects ?? 0),
        versions: (target._count?.versions ?? 0) + (source._count?.versions ?? 0),
      },
    };

    const updated = get().overview
      .filter((p) => p.id !== sourceId)
      .map((p) => (p.id === targetId ? migratedTarget : p));
    set({ overview: updated });
    saveStoredOverview(updated);
  },

  createProject: (productId, data) => {
    const newProject = {
      id: `proj-${Date.now()}`,
      name: data.name || '',
      description: data.description || '',
      createdAt: new Date().toISOString(),
    };
    const updated = get().overview.map((p) => {
      if (p.id !== productId) return p;
      return {
        ...p,
        projects: [...p.projects, newProject],
        _count: { ...p._count, projects: (p._count?.projects ?? 0) + 1 } as any,
      };
    });
    set({ overview: updated });
    saveStoredOverview(updated);
  },

  updateProject: (productId, projectId, data) => {
    const updated = get().overview.map((p) => {
      if (p.id !== productId) return p;
      const currentProject = p.projects.find((proj) => proj.id === projectId);
      if (!currentProject) return p;

      const nextName = data.name?.trim();
      const shouldRename = !!nextName && nextName !== currentProject.name;
      const nextProjects = p.projects.map((proj) =>
        proj.id === projectId
          ? {
              ...proj,
              ...data,
              name: nextName || proj.name,
            }
          : proj,
      );
      const nextVersions = shouldRename
        ? p.versions.map((version) => {
            if (!version.name.toLowerCase().startsWith(currentProject.name.toLowerCase())) return version;
            return {
              ...version,
              name: `${nextName}${version.name.slice(currentProject.name.length)}`,
            };
          })
        : p.versions;

      return {
        ...p,
        projects: nextProjects,
        versions: nextVersions,
      };
    });
    set({ overview: updated });
    saveStoredOverview(updated);
  },

  createVersion: (productId, data) => {
    const newVersion: VersionItem = {
      id: `ver-${Date.now()}`,
      name: data.name,
      status: data.status,
      releaseDate: null,
      createdAt: new Date().toISOString(),
      ...(data as any),
    };
    const updated = get().overview.map((p) => {
      if (p.id !== productId) return p;
      return {
        ...p,
        versions: [...p.versions, newVersion],
        _count: { ...p._count, versions: (p._count?.versions ?? 0) + 1 } as any,
      };
    });
    set({ overview: updated });
    saveStoredOverview(updated);
  },

  updateVersion: (productId, versionId, data) => {
    const updated = get().overview.map((p) => {
      if (p.id !== productId) return p;
      return {
        ...p,
        versions: p.versions.map((v) =>
          v.id === versionId ? { ...v, ...data } : v,
        ),
      };
    });
    set({ overview: updated });
    saveStoredOverview(updated);
  },

  deleteVersion: (productId, versionId) => {
    const updated = get().overview.map((p) => {
      if (p.id !== productId) return p;
      return {
        ...p,
        versions: p.versions.filter((v) => v.id !== versionId),
        _count: { ...p._count, versions: Math.max(0, (p._count?.versions ?? 0) - 1) } as any,
      };
    });
    set({ overview: updated });
    saveStoredOverview(updated);
  },

  deleteProject: (productId, projectId) => {
    const updated = get().overview.map((p) => {
      if (p.id !== productId) return p;
      return {
        ...p,
        projects: p.projects.filter((proj) => proj.id !== projectId),
        _count: { ...p._count, projects: Math.max(0, (p._count?.projects ?? 0) - 1) } as any,
      };
    });
    set({ overview: updated });
    saveStoredOverview(updated);
  },
}));

function saveStoredOverview(data: ProductOverview[]) {
  saveServerData('products-overview', data).catch(() => {});
}

async function loadStoredOverview(): Promise<ProductOverview[] | null> {
  try {
    return await loadServerData<ProductOverview[]>('products-overview');
  } catch {}
  return null;
}
