'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import * as XLSX from 'xlsx';
import { api, apiPaths } from '@/lib/api';
import { getCart, clearCart, CartItem } from '@/lib/cart';
import { isLoggedIn } from '@/lib/auth';
import { useI18n } from '@/lib/i18n/context';
import { numberLocale } from '@/lib/i18n/utils';

type OrderResult = {
  order_id: number;
  order_number: string;
  total: number;
  cards_count: number;
  codes: string[];
};

export default function CheckoutPage() {
  const router = useRouter();
  const { t, isRtl, locale } = useI18n();
  const nLocale = numberLocale(locale);
  const [cartItems, setCartItems] = useState<CartItem[]>([]);
  const [walletBalance, setWalletBalance] = useState<number>(0);
  /** نسبة الضريبة من الإعدادات (مثل 15) — تُجلب من `/general/footer` ليتوافق مع لوحة الإدارة */
  const [taxPercent, setTaxPercent] = useState<number>(15);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [orderResult, setOrderResult] = useState<OrderResult | null>(null);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
    const cart = getCart();
    setCartItems(cart);

    if (!isLoggedIn()) {
      router.push('/login');
      return;
    }

    api.get<{ balance: number }>(apiPaths.user.wallet).then((res) => {
      if (res.key === 'success' && res.data) {
        setWalletBalance((res.data as { balance?: number }).balance ?? 0);
      }
    });

    api
      .get<{ tax_rate_percent?: number }>(apiPaths.general.footer)
      .then((res) => {
        if (res.key !== 'success' || !res.data) return;
        const raw = (res.data as { tax_rate_percent?: number }).tax_rate_percent;
        if (typeof raw === 'number' && Number.isFinite(raw) && raw >= 0 && raw <= 100) {
          setTaxPercent(raw);
        }
      })
      .catch(() => {});
  }, [router]);

  const taxRate = taxPercent / 100;
  const subtotal = cartItems.reduce((sum, i) => sum + i.unit_price * i.quantity, 0);
  const taxAmount = Math.round(subtotal * taxRate * 100) / 100;
  const total = subtotal + taxAmount;

  const handleConfirmOrder = async () => {
    if (cartItems.length === 0) {
      setError(t('checkout.errorEmptyCart'));
      return;
    }

    if (walletBalance < total) {
      setError(
        t('checkout.errorInsufficient', {
          current: String(walletBalance),
          required: total.toFixed(2),
          currency: t('common.sar'),
        })
      );
      return;
    }

    setError('');
    setLoading(true);

    const res = await api.post<OrderResult>(apiPaths.orders.create, {
      items: cartItems.map((i) => ({
        product_id: i.product_id,
        quantity: i.quantity,
      })),
    });

    setLoading(false);

    if (res.key === 'success' && res.data) {
      clearCart();
      setOrderResult(res.data as unknown as OrderResult);
    } else {
      setError(res.msg || t('checkout.errorOrderFailed'));
    }
  };

  const handleExportExcel = () => {
    if (!orderResult) return;
    const now = new Date();
    const dateTime = now.toLocaleString(nLocale);

    const excelData = orderResult.codes.map((code) => ({
      [t('checkout.excelOrderNumber')]: orderResult.order_number,
      [t('checkout.excelCode')]: code,
      [t('checkout.excelDateTime')]: dateTime,
    }));

    const worksheet = XLSX.utils.json_to_sheet(excelData);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, t('checkout.excelSheetName'));
    XLSX.writeFile(workbook, `${t('checkout.excelFilePrefix')}${orderResult.order_number}.xlsx`);
  };

  if (!mounted) return null;

  const copyMargin = isRtl ? 'mr-2' : 'ml-2';

  return (
    <div dir={isRtl ? 'rtl' : 'ltr'} className="flex flex-col flex-1 bg-gradient-to-br from-blue-50 via-white to-gray-50">
      {orderResult && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl p-8 max-w-lg w-full">
            <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <i className="ri-check-line text-3xl text-green-600"></i>
            </div>
            <h3 className="text-2xl font-bold text-gray-900 mb-2 text-center">{t('checkout.successTitle')}</h3>
            <p className="text-gray-600 mb-2 text-center">
              {t('checkout.orderNumber')} <strong>{orderResult.order_number}</strong>
            </p>
            <p className="text-gray-600 mb-6 text-center">
              {t('checkout.codesGenerated', { count: String(orderResult.cards_count) })}
            </p>

            {orderResult.codes.length > 0 && (
              <div className="bg-gray-50 rounded-lg p-4 mb-6 max-h-40 overflow-y-auto">
                {orderResult.codes.map((code, i) => (
                  <div key={i} className="flex items-center justify-between py-1 border-b border-gray-100 last:border-0">
                    <span className="font-mono text-sm text-gray-800">{code}</span>
                    <button
                      type="button"
                      onClick={() => navigator.clipboard.writeText(code)}
                      className={`text-blue-600 hover:text-blue-800 text-xs ${copyMargin} cursor-pointer`}
                    >
                      {t('checkout.copy')}
                    </button>
                  </div>
                ))}
              </div>
            )}

            <div className="space-y-3">
              <button
                type="button"
                onClick={handleExportExcel}
                className="w-full bg-green-600 text-white py-3 rounded-lg hover:bg-green-700 transition-colors cursor-pointer whitespace-nowrap font-semibold flex items-center justify-center gap-2"
              >
                <i className="ri-file-excel-2-line text-xl"></i>
                {t('checkout.exportExcel')}
              </button>
              <button
                type="button"
                onClick={() => router.push(`/orders/${orderResult.order_id}`)}
                className="w-full bg-blue-600 text-white py-3 rounded-lg hover:bg-blue-700 transition-colors cursor-pointer whitespace-nowrap font-semibold"
              >
                {t('checkout.viewOrderDetails')}
              </button>
              <button
                type="button"
                onClick={() => router.push('/orders')}
                className="w-full bg-gray-100 text-gray-700 py-3 rounded-lg hover:bg-gray-200 transition-colors cursor-pointer whitespace-nowrap font-semibold"
              >
                {t('checkout.backToOrders')}
              </button>
            </div>
          </div>
        </div>
      )}

      <main className="max-w-4xl mx-auto px-6 py-12 flex-1 w-full">
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">{t('checkout.title')}</h1>
          <p className="text-gray-600">{t('checkout.subtitle')}</p>
        </div>

        {error && (
          <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg text-red-700 flex items-center gap-2">
            <i className="ri-error-warning-line text-xl"></i>
            <span>{error}</span>
          </div>
        )}

        {cartItems.length === 0 ? (
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-12 text-center">
            <i className="ri-shopping-cart-line text-5xl text-gray-300 mb-4 block"></i>
            <h2 className="text-xl font-bold text-gray-900 mb-4">{t('checkout.cartEmpty')}</h2>
            <Link
              href="/store"
              className="inline-block bg-blue-600 text-white px-8 py-3 rounded-lg hover:bg-blue-700 transition-colors"
            >
              {t('checkout.browseStore')}
            </Link>
          </div>
        ) : (
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <div className="lg:col-span-2 space-y-6">
              <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
                <h2 className="text-xl font-bold text-gray-900 mb-6">{t('checkout.orderDetails')}</h2>
                <div className="space-y-4">
                  {cartItems.map((item) => (
                    <div key={item.product_id} className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                      <div className="flex-1">
                        <h3 className="font-semibold text-gray-900 mb-1">{item.product_name}</h3>
                        <div className="flex items-center gap-4 text-sm text-gray-600">
                          <span>
                            {t('checkout.unitPrice')} {item.unit_price} {t('common.sar')}
                          </span>
                          <span>
                            {t('checkout.quantity')} {item.quantity}
                          </span>
                        </div>
                      </div>
                      <p className="text-lg font-bold text-gray-900">
                        {item.unit_price * item.quantity} {t('common.sar')}
                      </p>
                    </div>
                  ))}
                </div>
              </div>

              <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
                <h2 className="text-xl font-bold text-gray-900 mb-4">{t('checkout.paymentMethod')}</h2>
                <div className="p-4 rounded-lg border-2 border-blue-600 bg-blue-50 flex items-center gap-4">
                  <i className="ri-wallet-3-line text-2xl text-blue-600"></i>
                  <div>
                    <span className="font-semibold text-gray-900">{t('checkout.walletPayment')}</span>
                    <p className="text-sm text-gray-600 mt-1">
                      {t('checkout.availableBalance')}{' '}
                      <strong className="text-blue-600">
                        {walletBalance} {t('common.sar')}
                      </strong>
                    </p>
                  </div>
                </div>
                {walletBalance < total && (
                  <div className="mt-3 p-3 bg-yellow-50 border border-yellow-200 rounded-lg text-yellow-800 text-sm flex items-center gap-2 flex-wrap">
                    <i className="ri-error-warning-line"></i>
                    {t('checkout.insufficient')}
                    <Link href="/profile/wallet" className="text-blue-600 underline">
                      {t('checkout.topUpWallet')}
                    </Link>
                  </div>
                )}
              </div>
            </div>

            <div className="lg:col-span-1">
              <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 sticky top-24">
                <h2 className="text-xl font-bold text-gray-900 mb-6">{t('checkout.invoiceSummary')}</h2>
                <div className="space-y-4 mb-6">
                  <div className="flex items-center justify-between text-gray-700">
                    <span>{t('checkout.productsCost')}</span>
                    <span className="font-semibold">
                      {subtotal} {t('common.sar')}
                    </span>
                  </div>
                  <div className="flex items-center justify-between text-gray-700">
                    <span>{t('checkout.vat', { percent: String(taxPercent) })}</span>
                    <span className="font-semibold">
                      {taxAmount.toFixed(2)} {t('common.sar')}
                    </span>
                  </div>
                  <div className="border-t border-gray-200 pt-4">
                    <div className="flex items-center justify-between">
                      <span className="text-lg font-bold text-gray-900">{t('checkout.invoiceTotal')}</span>
                      <span className="text-2xl font-bold text-blue-600">
                        {total.toFixed(2)} {t('common.sar')}
                      </span>
                    </div>
                  </div>
                </div>
                <div className="space-y-3">
                  <button
                    type="button"
                    onClick={handleConfirmOrder}
                    disabled={loading || walletBalance < total}
                    className="w-full bg-blue-600 text-white py-3 rounded-lg hover:bg-blue-700 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors cursor-pointer whitespace-nowrap font-semibold flex items-center justify-center gap-2"
                  >
                    {loading ? (
                      <>
                        <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                        {t('checkout.processing')}
                      </>
                    ) : (
                      t('checkout.confirmOrder')
                    )}
                  </button>
                  <button
                    type="button"
                    onClick={() => router.push('/cart')}
                    className="w-full bg-gray-100 text-gray-700 py-3 rounded-lg hover:bg-gray-200 transition-colors cursor-pointer whitespace-nowrap font-semibold"
                  >
                    {t('checkout.backToCart')}
                  </button>
                </div>
              </div>
            </div>
          </div>
        )}
      </main>
    </div>
  );
}
