import type { NextApiRequest, NextApiResponse } from 'next';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '../../auth/[...nextauth]';
import mysql from 'mysql2/promise';

interface OrderDetail {
  id: number;
  orderNumber: string;
  date: string;
  status: string;
  total: number;
  discountAmount: number;
  isGiftWrapped: boolean;
  giftWrappingPrice: number;
  items: Array<{
    id: number;
    productId?: number;
    name: string;
    brand: string;
    quantity: number;
    unitPrice: number;
    totalPrice: number;
    image?: string;
    volume?: string;
    productType?: string;
  }>;
  shipping: {
    method: string;
    price: number;
    pickupPoint?: any;
  };
  billing: {
    name: string;
    email: string;
    phone: string;
    street: string;
    city: string;
    zip: string;
    country: string;
  };
  shipping_address?: {
    name: string;
    street: string;
    city: string;
    zip: string;
    country: string;
  };
}

interface ErrorResponse {
  error: string;
}

const pool = mysql.createPool({
  host: process.env.DB_HOST || 'localhost',
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '',
  database: process.env.DB_NAME || 'perfume_shop',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
});

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<OrderDetail | ErrorResponse>
) {
  if (req.method !== 'GET') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  const session = await getServerSession(req, res, authOptions);

  if (!session?.user?.email) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  const { id } = req.query;

  if (!id || Array.isArray(id)) {
    return res.status(400).json({ error: 'Invalid order ID' });
  }

  let connection: any = null;

  try {
    connection = await pool.getConnection();

    // Najdi user ID podle emailu
    const [userRows]: any = await connection.query(
      'SELECT id FROM users WHERE email = ?',
      [session.user.email]
    );

    if (!userRows || userRows.length === 0) {
      connection.release();
      return res.status(404).json({ error: 'User not found' });
    }

    const userId = userRows[0].id;

    // Nacti objednávku - ověř, že patří přihlášenému uživateli
    const [orderRows]: any = await connection.query(
      `SELECT o.id, o.order_number, o.created_at, o.total_price, o.discount_amount, o.is_gift_wrapped, os.name as status_name
       FROM orders o
       LEFT JOIN order_statuses os ON o.status_id = os.id
       WHERE o.id = ? AND o.user_id = ?`,
      [id, userId]
    );

    if (!orderRows || orderRows.length === 0) {
      connection.release();
      return res.status(404).json({ error: 'Order not found' });
    }

    const order = orderRows[0];

    // Nacti položky objednávky s obrázky a variantami
    const [items]: any = await connection.query(
      `SELECT oi.id, oi.product_id, oi.product_name, oi.brand, oi.quantity, oi.unit_price, oi.total_price, pv.volume_ml, p.slug, p.type as product_type
       FROM order_items oi
       LEFT JOIN product_variants pv ON pv.id = oi.variant_id
       LEFT JOIN products p ON p.id = oi.product_id
       WHERE oi.order_id = ?`,
      [order.id]
    );

    // Pro každou položku nacti primární obrázek
    const itemsWithImages = await Promise.all(
      (items || []).map(async (item: any) => {
        let image = undefined;
        if (item.product_id) {
          try {
            const [imageRows]: any = await connection.query(
              `SELECT url FROM product_images WHERE product_id = ? AND is_primary = 1 LIMIT 1`,
              [item.product_id]
            );
            if (imageRows && imageRows.length > 0) {
              image = imageRows[0].url;
            }
          } catch (imgError) {
            console.error(`Error fetching image for product ${item.product_id}:`, imgError);
          }
        }
        return {
          id: item.id,
          productId: item.product_id,
          productSlug: item.slug,
          name: item.product_name,
          brand: item.brand,
          quantity: item.quantity,
          unitPrice: item.unit_price,
          totalPrice: item.total_price,
          image,
          volume: item.volume_ml || undefined,
          productType: item.product_type || 'perfume',
        };
      })
    );

    // Nacti dopravní informace
    const [shippingRows]: any = await connection.query(
      `SELECT method_name, price, method_data FROM order_shipping WHERE order_id = ?`,
      [order.id]
    );

    let shippingData: {
      method: string;
      price: number;
      pickupPoint?: any;
    } = {
      method: 'Neznámá',
      price: 0,
      pickupPoint: undefined,
    };

    if (shippingRows && shippingRows.length > 0) {
      const shipping = shippingRows[0];
      shippingData.method = shipping.method_name || 'Neznámá';
      shippingData.price = shipping.price || 0;
      if (shipping.method_data) {
        try {
          shippingData.pickupPoint = JSON.parse(shipping.method_data);
        } catch (e) {
        }
      }
    }

    // Nacti billing adresu
    const [addressRows]: any = await connection.query(
      `SELECT full_name, street, city, zip, country_code, phone, email FROM order_addresses 
       WHERE order_id = ? AND address_type = 'billing'
       LIMIT 1`,
      [order.id]
    );

    let billingData = {
      name: '',
      email: '',
      phone: '',
      street: '',
      city: '',
      zip: '',
      country: 'CZ',
    };

    if (addressRows && addressRows.length > 0) {
      const addr = addressRows[0];
      billingData = {
        name: addr.full_name,
        email: addr.email,
        phone: addr.phone,
        street: addr.street,
        city: addr.city,
        zip: addr.zip,
        country: addr.country_code || 'CZ',
      };
    }

    // Pokud je to pickup point, nacti i shipping adresu
    let shippingAddress = undefined;
    if (shippingData.pickupPoint?.pickupPoint) {
      shippingAddress = {
        name: shippingData.pickupPoint.pickupPoint.name,
        street: shippingData.pickupPoint.pickupPoint.street,
        city: shippingData.pickupPoint.pickupPoint.city,
        zip: shippingData.pickupPoint.pickupPoint.zip,
        country: 'CZ',
      };
    }

    connection.release();

    const orderDetail: OrderDetail = {
      id: order.id,
      orderNumber: order.order_number,
      date: new Date(order.created_at).toLocaleDateString('cs-CZ', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
      }),
      status: order.status_name || 'Neznámý',
      total: order.total_price,
      discountAmount: order.discount_amount || 0,
      isGiftWrapped: order.is_gift_wrapped === 1,
      giftWrappingPrice: order.is_gift_wrapped === 1 ? 99 : 0,
      items: itemsWithImages,
      shipping: shippingData,
      billing: billingData,
      shipping_address: shippingAddress,
    };

    return res.status(200).json(orderDetail);
  } catch (error) {
    if (connection) {
      try {
        connection.release();
      } catch (e) {
      }
    }
    return res.status(500).json({ error: 'Internal server error' });
  }
}
