import { VOCAB } from '@/lib/white-label/constants';

/**
 * ${VOCAB.factory} Template Library
 * Curated project templates that pre-populate the DF generation form
 */

export interface DFTemplate {
  id: string;
  name: string;
  category: TemplateCategory;
  description: string;
  icon: string; // emoji
  prompt: string;
  tags: string[];
  difficulty: 'starter' | 'intermediate' | 'advanced';
  estimatedArtifacts: number;
  suggestedLanguage?: string;
  suggestedDatabase?: string;
  expertSpec?: TemplateExpertSpec;
}

export interface TemplateExpertSpec {
  entities: Array<{
    name: string;
    description: string;
    fields: Array<{ name: string; type: string; required: boolean; description: string }>;
    relations: Array<{ name: string; type: string; target: string; description: string }>;
  }>;
  endpoints: Array<{
    path: string;
    method: string;
    description: string;
    businessLogic: string[];
  }>;
}

export type TemplateCategory =
  | 'saas'
  | 'ecommerce'
  | 'crm'
  | 'hr'
  | 'finance'
  | 'project-management'
  | 'devtools'
  | 'content';

export const TEMPLATE_CATEGORIES: { id: TemplateCategory; label: string; icon: string }[] = [
  { id: 'saas', label: 'SaaS', icon: '🚀' },
  { id: 'ecommerce', label: 'E-Commerce', icon: '🛒' },
  { id: 'crm', label: 'CRM', icon: '🤝' },
  { id: 'hr', label: 'HR & People', icon: '👥' },
  { id: 'finance', label: 'Finance', icon: '💰' },
  { id: 'project-management', label: 'Project Mgmt', icon: '📋' },
  { id: 'devtools', label: 'Dev Tools', icon: '🔧' },
  { id: 'content', label: 'Content', icon: '📝' },
];

export const TEMPLATES: DFTemplate[] = [
  // ---- SaaS ----
  {
    id: 'saas-dashboard',
    name: 'SaaS Admin Dashboard',
    category: 'saas',
    description: 'Multi-tenant admin dashboard with user management, analytics, and billing overview. Includes role-based access control and activity logs.',
    icon: '📊',
    prompt: 'Build a SaaS admin dashboard with tenant management, user management with roles (admin, manager, viewer), analytics overview with key metrics (MRR, churn rate, active users), billing status, activity logs, and notification center. Include CRUD for tenants and users, search/filter, and audit trail.',
    tags: ['multi-tenant', 'analytics', 'RBAC', 'billing'],
    difficulty: 'advanced',
    estimatedArtifacts: 18,
    suggestedLanguage: 'typescript-react',
    suggestedDatabase: 'postgresql',
    expertSpec: {
      entities: [
        {
          name: 'Tenant',
          description: 'Organization/company entity',
          fields: [
            { name: 'id', type: 'String', required: true, description: 'Unique identifier' },
            { name: 'name', type: 'String', required: true, description: 'Company name' },
            { name: 'slug', type: 'String', required: true, description: 'URL slug' },
            { name: 'plan', type: 'String', required: true, description: 'Subscription plan' },
            { name: 'status', type: 'String', required: true, description: 'active/suspended/cancelled' },
          ],
          relations: [{ name: 'users', type: 'hasMany', target: 'User', description: 'Tenant users' }],
        },
        {
          name: 'User',
          description: 'Platform user with role',
          fields: [
            { name: 'id', type: 'String', required: true, description: 'Unique identifier' },
            { name: 'email', type: 'String', required: true, description: 'Email address' },
            { name: 'role', type: 'String', required: true, description: 'admin/manager/viewer' },
            { name: 'lastLoginAt', type: 'DateTime', required: false, description: 'Last login timestamp' },
          ],
          relations: [{ name: 'tenant', type: 'belongsTo', target: 'Tenant', description: 'Parent tenant' }],
        },
        {
          name: 'ActivityLog',
          description: 'Audit trail entries',
          fields: [
            { name: 'id', type: 'String', required: true, description: 'Unique identifier' },
            { name: 'action', type: 'String', required: true, description: 'Action performed' },
            { name: 'resource', type: 'String', required: true, description: 'Resource affected' },
            { name: 'metadata', type: 'Json', required: false, description: 'Additional context' },
          ],
          relations: [{ name: 'user', type: 'belongsTo', target: 'User', description: 'Who performed the action' }],
        },
      ],
      endpoints: [
        { path: '/api/tenants', method: 'GET', description: 'List tenants with filters', businessLogic: ['pagination', 'search', 'filter by status'] },
        { path: '/api/tenants', method: 'POST', description: 'Create tenant', businessLogic: ['validate plan', 'generate slug'] },
        { path: '/api/users', method: 'GET', description: 'List users', businessLogic: ['pagination', 'filter by role', 'filter by tenant'] },
        { path: '/api/analytics', method: 'GET', description: 'Dashboard metrics', businessLogic: ['aggregate MRR', 'calculate churn', 'active users count'] },
        { path: '/api/activity-log', method: 'GET', description: 'Audit trail', businessLogic: ['pagination', 'date range filter'] },
      ],
    },
  },
  {
    id: 'saas-onboarding',
    name: 'User Onboarding Flow',
    category: 'saas',
    description: 'Step-by-step onboarding wizard with progress tracking, profile setup, team invites, and integration configuration.',
    icon: '🎯',
    prompt: 'Create a multi-step onboarding wizard for a SaaS product. Steps: (1) Profile setup with avatar upload, (2) Team creation and member invites by email, (3) Integration configuration (Slack, GitHub, Jira), (4) First project setup. Include progress bar, skip/back navigation, and completion celebration.',
    tags: ['onboarding', 'wizard', 'integrations'],
    difficulty: 'intermediate',
    estimatedArtifacts: 12,
  },

  // ---- E-Commerce ----
  {
    id: 'ecommerce-backend',
    name: 'E-Commerce Backend',
    category: 'ecommerce',
    description: 'Complete product catalog, cart, and order management API with inventory tracking and customer accounts.',
    icon: '🏪',
    prompt: 'Build an e-commerce backend with: Product catalog (name, description, price, images, categories, variants), Shopping cart (add/remove/update items), Order management (create order from cart, status tracking: pending → confirmed → shipped → delivered), Customer accounts (addresses, order history), Inventory tracking with low-stock alerts. Include search, filtering by category/price, and pagination.',
    tags: ['products', 'orders', 'cart', 'inventory'],
    difficulty: 'advanced',
    estimatedArtifacts: 16,
    suggestedDatabase: 'postgresql',
  },
  {
    id: 'ecommerce-product-reviews',
    name: 'Product Review System',
    category: 'ecommerce',
    description: 'Review and rating system with moderation, helpful votes, and aggregate statistics.',
    icon: '⭐',
    prompt: 'Create a product review and rating system. Features: Submit reviews with 1-5 star rating, title, and body text. Mark reviews as helpful (upvote/downvote). Moderation queue for flagged reviews. Aggregate rating calculations per product. Verified purchase badge. Sort reviews by newest, highest rated, most helpful.',
    tags: ['reviews', 'ratings', 'moderation'],
    difficulty: 'intermediate',
    estimatedArtifacts: 10,
  },

  // ---- CRM ----
  {
    id: 'crm-lite',
    name: 'CRM Lite',
    category: 'crm',
    description: 'Lightweight CRM with contacts, companies, deals pipeline, and activity tracking.',
    icon: '📇',
    prompt: 'Build a lightweight CRM system with: Contacts (name, email, phone, company, tags, notes), Companies (name, industry, size, website), Deals pipeline with stages (Lead → Qualified → Proposal → Negotiation → Closed Won/Lost), Activity log (calls, emails, meetings, notes per contact), Dashboard with pipeline value, deal count by stage, recent activities. Include search, filters, and CSV import.',
    tags: ['contacts', 'deals', 'pipeline', 'activities'],
    difficulty: 'advanced',
    estimatedArtifacts: 15,
  },

  // ---- HR ----
  {
    id: 'hr-time-attendance',
    name: 'Time & Attendance',
    category: 'hr',
    description: 'Employee time tracking with clock in/out, PTO requests, and timesheet approvals.',
    icon: '⏰',
    prompt: 'Create a time and attendance module: Clock in/out with timestamps, Daily timesheet entries (hours, project, description), PTO request workflow (request → manager approval → approved/denied), Holiday calendar, Overtime calculation, Manager dashboard with team hours summary, export to CSV. Include employee profiles and department hierarchy.',
    tags: ['timesheets', 'PTO', 'overtime', 'approvals'],
    difficulty: 'intermediate',
    estimatedArtifacts: 14,
  },
  {
    id: 'hr-employee-directory',
    name: 'Employee Directory',
    category: 'hr',
    description: 'Searchable employee directory with org chart, profiles, and department management.',
    icon: '🏢',
    prompt: 'Build an employee directory with: Employee profiles (name, email, phone, title, department, manager, hire date, photo), Department management, Org chart visualization, Search by name/department/title, Bulk import from CSV. Include reporting relationships and team views.',
    tags: ['directory', 'org-chart', 'departments'],
    difficulty: 'starter',
    estimatedArtifacts: 8,
  },

  // ---- Finance ----
  {
    id: 'finance-expense-tracker',
    name: 'Expense Tracker',
    category: 'finance',
    description: 'Expense reporting with receipt uploads, categories, approval workflows, and budget tracking.',
    icon: '🧾',
    prompt: 'Build an expense tracking system: Submit expenses with amount, category, date, vendor, description, and receipt image. Approval workflow (submit → manager review → finance review → approved/rejected). Expense categories and budget limits per category. Monthly/quarterly expense reports with charts. Dashboard showing spend by category, pending approvals, and budget utilization.',
    tags: ['expenses', 'receipts', 'approvals', 'budgets'],
    difficulty: 'intermediate',
    estimatedArtifacts: 12,
  },
  {
    id: 'finance-invoice-manager',
    name: 'Invoice Manager',
    category: 'finance',
    description: 'Invoice creation, tracking, and payment status management with client profiles.',
    icon: '📄',
    prompt: 'Create an invoice management system: Create invoices with line items, tax calculations, and discounts. Client management with contact info and payment terms. Invoice statuses (draft → sent → viewed → paid → overdue). Payment recording and partial payments. Invoice PDF generation. Dashboard with outstanding amounts, overdue invoices, and monthly revenue.',
    tags: ['invoices', 'payments', 'clients'],
    difficulty: 'intermediate',
    estimatedArtifacts: 13,
  },

  // ---- Project Management ----
  {
    id: 'pm-kanban',
    name: 'Kanban Board',
    category: 'project-management',
    description: 'Drag-and-drop kanban board with columns, cards, labels, assignees, and due dates.',
    icon: '📌',
    prompt: 'Build a kanban board with: Customizable columns (To Do, In Progress, Review, Done), Cards with title, description, labels (color-coded), assignee, due date, and checklist. Drag-and-drop between columns. Card detail view with comments and activity log. Board-level filters by assignee, label, and due date.',
    tags: ['kanban', 'cards', 'labels', 'drag-and-drop'],
    difficulty: 'intermediate',
    estimatedArtifacts: 11,
  },
  {
    id: 'pm-sprint-planner',
    name: 'Sprint Planner',
    category: 'project-management',
    description: 'Agile sprint planning with backlog, sprint boards, velocity tracking, and burndown charts.',
    icon: '🏃',
    prompt: 'Create a sprint planning tool: Product backlog with user stories (title, description, story points, priority), Sprint creation with capacity planning, Sprint board with task status tracking, Velocity tracking across sprints, Burndown chart, Daily standup notes, Retrospective templates. Include team member workload view.',
    tags: ['sprints', 'agile', 'backlog', 'velocity'],
    difficulty: 'advanced',
    estimatedArtifacts: 16,
  },

  // ---- Dev Tools ----
  {
    id: 'devtools-api-monitor',
    name: 'API Health Monitor',
    category: 'devtools',
    description: 'API endpoint monitoring with uptime tracking, response time charts, and alert configuration.',
    icon: '🔍',
    prompt: 'Build an API health monitoring dashboard: Register API endpoints to monitor (URL, method, expected status, check interval). Health check history with response time and status. Uptime percentage calculation. Response time trend charts. Alert rules (response time > threshold, status change). Dashboard with overall health, recent incidents, and performance trends.',
    tags: ['monitoring', 'uptime', 'alerts', 'API'],
    difficulty: 'intermediate',
    estimatedArtifacts: 11,
  },
  {
    id: 'devtools-feature-flags',
    name: 'Feature Flag Manager',
    category: 'devtools',
    description: 'Feature flag management with environments, percentage rollouts, and user targeting.',
    icon: '🚩',
    prompt: 'Create a feature flag management system: Create flags with name, description, and type (boolean, percentage, user-segment). Environment support (development, staging, production). Percentage-based rollouts. User targeting by attributes. Flag evaluation API endpoint. Audit log of flag changes. Dashboard with active flags, recent changes, and environment overview.',
    tags: ['feature-flags', 'rollouts', 'targeting'],
    difficulty: 'intermediate',
    estimatedArtifacts: 10,
  },

  // ---- Content ----
  {
    id: 'content-blog-engine',
    name: 'Blog Engine',
    category: 'content',
    description: 'Full blog backend with posts, categories, tags, comments, and author management.',
    icon: '✍️',
    prompt: 'Build a blog engine backend: Posts with title, slug, body (markdown), excerpt, featured image, status (draft/published/archived), publish date. Categories and tags. Author profiles. Comments with moderation (pending/approved/spam). RSS feed generation. Search by title/content, filter by category/tag. Pagination and featured posts.',
    tags: ['blog', 'posts', 'comments', 'categories'],
    difficulty: 'starter',
    estimatedArtifacts: 12,
  },
  {
    id: 'content-knowledge-base',
    name: 'Knowledge Base',
    category: 'content',
    description: 'Self-service knowledge base with articles, categories, search, and feedback tracking.',
    icon: '📚',
    prompt: 'Create a knowledge base system: Articles with title, body (rich text), category, tags, and visibility (public/internal). Category hierarchy (parent/child). Full-text search. Article feedback (helpful yes/no + comment). Related articles suggestions. Most viewed and recently updated articles. Version history for articles.',
    tags: ['knowledge-base', 'articles', 'search', 'feedback'],
    difficulty: 'intermediate',
    estimatedArtifacts: 11,
  },
];

export function getTemplatesByCategory(category: TemplateCategory): DFTemplate[] {
  return TEMPLATES.filter(t => t.category === category);
}

export function getTemplateById(id: string): DFTemplate | undefined {
  return TEMPLATES.find(t => t.id === id);
}

export function searchTemplates(query: string): DFTemplate[] {
  const q = query.toLowerCase();
  return TEMPLATES.filter(
    t =>
      t.name.toLowerCase().includes(q) ||
      t.description.toLowerCase().includes(q) ||
      t.tags.some(tag => tag.toLowerCase().includes(q))
  );
}
