import { Router, Response, Request } from 'express';
import { GolfAcademy, CoachInquiry } from '../models/index.js';
import { authenticate, requireRole, AuthRequest } from '../middleware/auth.js';

const router = Router();

const defaultData = {
  heroTitle: { en: 'Level Up Your Game', zh: '提升您的球技' },
  heroSubtitle: {
    en: 'Golf Academy is Now Open! A new era of coaching with professionals.',
    zh: '高球學院現已開放！與專業教練一起開啟新時代。',
  },
  introContent: {
    en: 'Tired of the same old swing advice? Get ready for a revolution in your golf journey. We are thrilled to announce the launch of the Golf Academy, an exclusive program designed to transform your skills through diverse, expert guidance. From now on, you won\'t just have a coach—you\'ll have access to an entire team of experts. Each brings a unique perspective, cutting-edge techniques, and a wealth of experience to help you break through plateaus and master every aspect of your game.',
    zh: '厭倦了千篇一律的揮桿建議？準備好迎接您高爾夫旅程的革命吧。我們很高興宣布高爾夫學院的推出，這是一個專為通過多元化專家指導，提升您的技能而設計的獨家課程。從現在開始，您不僅擁有一位教練—您將獲得一整個專家團隊的指導。每位專家都帶來獨特的視角、尖端技術和豐富的經驗，幫助您突破瓶頸，掌握比賽的各個方面。',
  },
  benefits: [
    {
      title: { en: 'Diverse Pros', zh: '多元教練' },
      description: {
        en: 'Learn from the best. Be inspired by a rotating roster of top-tier coaches, each with their own specialized expertise.',
        zh: '向最優秀的教練學習。從頂級教練輪替陣容中汲取靈感，每位教練都有自己的專業技能。',
      },
    },
    {
      title: { en: 'Tailored Learning', zh: '量身定制' },
      description: {
        en: "Whether you're a beginner or a seasoned player, our coaches will tailor their approach to your specific goals and learning style.",
        zh: '無論您是初學者還是經驗豐富的球手，我們的教練都會根據您的目標和學習風格量身定制教學方案。',
      },
    },
    {
      title: { en: 'Unlock Your Potential', zh: '釋放潛能' },
      description: {
        en: 'Gain new insights, correct bad habits, and develop a consistent, powerful swing with fresh, professional eyes on your game.',
        zh: '獲得新的見解，糾正不良習慣，在專業教練的全新視角下，練出穩定而有力的揮桿。',
      },
    },
  ],
  ctaTitle: { en: 'Book your first free trial lesson', zh: '預約您的首次免費體驗課' },
  ctaDescription: {
    en: 'Unlock the coaching team and start your golf journey today.',
    zh: '解鎖教練團隊，今天開始您的高球之旅。',
  },
  ctaButtonText: { en: 'Book a Trial', zh: '預約體驗' },
  ctaButtonLink: '/contact',
  coaches: [],
  joinTitle: { en: 'Join Our Coaching Team', zh: '加入我們的教練團隊' },
  joinSubtitle: { en: 'Start your freelance coaching business', zh: '開始您的自由教練事業' },
};

// GET /api/golf-academy — public
router.get('/', async (req: Request, res: Response): Promise<void> => {
  try {
    let page = await GolfAcademy.findOne();
    if (!page) {
      page = new GolfAcademy(defaultData);
      await page.save();
    }
    res.json(page);
  } catch (error) {
    res.status(500).json({ error: 'Server error' });
  }
});

// PUT /api/golf-academy — admin only
router.put(
  '/',
  authenticate,
  requireRole('admin'),
  async (req: AuthRequest, res: Response): Promise<void> => {
    try {
      let page = await GolfAcademy.findOne();
      if (!page) {
        page = new GolfAcademy(req.body);
      } else {
        Object.assign(page, req.body);
      }
      await page.save();
      res.json(page);
    } catch (error) {
      res.status(500).json({ error: 'Server error' });
    }
  }
);

// POST /api/golf-academy/inquiries — public
router.post('/inquiries', async (req: Request, res: Response): Promise<void> => {
  try {
    const { firstName, lastName, email, message } = req.body;
    if (!firstName || !lastName || !email) {
      res.status(400).json({ error: 'First name, last name and email are required' });
      return;
    }
    const inquiry = new CoachInquiry({ firstName, lastName, email, message });
    await inquiry.save();
    res.status(201).json({ message: 'Inquiry submitted successfully' });
  } catch (error) {
    res.status(500).json({ error: 'Server error' });
  }
});

// GET /api/golf-academy/inquiries — admin only
router.get(
  '/inquiries',
  authenticate,
  requireRole('admin'),
  async (req: AuthRequest, res: Response): Promise<void> => {
    try {
      const { page = 1, limit = 20 } = req.query;
      const inquiries = await CoachInquiry.find()
        .sort({ createdAt: -1 })
        .skip((Number(page) - 1) * Number(limit))
        .limit(Number(limit));
      const total = await CoachInquiry.countDocuments();
      res.json({
        inquiries,
        pagination: {
          page: Number(page),
          limit: Number(limit),
          total,
          pages: Math.ceil(total / Number(limit)),
        },
      });
    } catch (error) {
      res.status(500).json({ error: 'Server error' });
    }
  }
);

export default router;
