import React, { ReactElement, useEffect, useMemo, useState } from 'react';
import Head from 'next/head';
import axios from 'axios';
import { mdiCart } from '@mdi/js';

import LayoutAuthenticated from '../../layouts/Authenticated';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import CardBox from '../../components/CardBox';
import FormField from '../../components/FormField';
import BaseButton from '../../components/BaseButton';
import BaseButtons from '../../components/BaseButtons';
import BaseDivider from '../../components/BaseDivider';
import { getPageTitle } from '../../config';
import { useAppSelector } from '../../stores/hooks';

const formatCurrency = (value: number) =>
  new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(value || 0);

const QuickOrder = () => {
  const { currentUser } = useAppSelector((state) => state.auth);
  const [stores, setStores] = useState<any[]>([]);
  const [products, setProducts] = useState<any[]>([]);
  const [recentOrders, setRecentOrders] = useState<any[]>([]);
  const [selectedStore, setSelectedStore] = useState('');
  const [selectedProduct, setSelectedProduct] = useState('');
  const [quantity, setQuantity] = useState(1);
  const [deliveryFee, setDeliveryFee] = useState(3);
  const [serviceFee, setServiceFee] = useState(1);
  const [customerNote, setCustomerNote] = useState('');
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');
  const [successMessage, setSuccessMessage] = useState('');
  const [lastOrder, setLastOrder] = useState<any | null>(null);

  const filteredProducts = useMemo(() => {
    if (!selectedStore) return products;
    return products.filter((product) => product?.store?.id === selectedStore);
  }, [products, selectedStore]);

  const selectedProductData = useMemo(
    () => products.find((product) => product.id === selectedProduct),
    [products, selectedProduct]
  );

  const unitPrice = Number(selectedProductData?.price || 0);
  const safeQuantity = Math.max(1, Number(quantity) || 1);
  const subtotal = unitPrice * safeQuantity;
  const taxAmount = 0;
  const totalAmount = subtotal + Number(deliveryFee || 0) + Number(serviceFee || 0) + taxAmount;

  const fetchData = async () => {
    setLoading(true);
    setErrorMessage('');
    try {
      const [storesResponse, productsResponse, ordersResponse] = await Promise.all([
        axios.get('/stores'),
        axios.get('/products'),
        axios.get('/orders?limit=5&page=0'),
      ]);
      setStores(storesResponse.data?.rows || []);
      setProducts(productsResponse.data?.rows || []);
      setRecentOrders(ordersResponse.data?.rows || []);
    } catch (error) {
      console.error('Quick order load error:', error);
      setErrorMessage('Unable to load marketplace data. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  const handleSubmit = async () => {
    setErrorMessage('');
    setSuccessMessage('');

    if (!currentUser?.id) {
      setErrorMessage('Please sign in to place an order.');
      return;
    }
    if (!selectedStore) {
      setErrorMessage('Select a store before placing the order.');
      return;
    }
    if (!selectedProduct) {
      setErrorMessage('Select a product to continue.');
      return;
    }

    setSubmitting(true);

    try {
      const orderPayload = {
        order_number: `ORD-${Date.now().toString().slice(-6)}`,
        order_status: 'confirmed',
        fulfillment_type: 'delivery',
        subtotal_amount: subtotal,
        delivery_fee: deliveryFee,
        service_fee: serviceFee,
        discount_amount: 0,
        tax_amount: taxAmount,
        total_amount: totalAmount,
        customer_note: customerNote || null,
        placed_at: new Date().toISOString(),
        customer: currentUser.id,
        store: selectedStore,
      };

      const createdOrderResponse = await axios.post('/orders', { data: orderPayload });
      const createdOrder = createdOrderResponse.data;

      await axios.post('/order_items', {
        data: {
          order: createdOrder?.id,
          product: selectedProductData?.id,
          product_name_snapshot: selectedProductData?.product_name,
          unit_price: unitPrice,
          quantity: safeQuantity,
          line_total: subtotal,
          item_note: customerNote || null,
        },
      });

      setLastOrder(createdOrder);
      setSuccessMessage(`Order ${createdOrder?.order_number || ''} created successfully.`);
      await fetchData();
    } catch (error) {
      console.error('Quick order submit error:', error);
      setErrorMessage('Could not place the order. Please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <>
      <Head>
        <title>{getPageTitle('Quick order')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiCart} title="Quick order" main>
          <BaseButton href="/orders/orders-list" label="Orders list" color="info" />
        </SectionTitleLineWithButton>

        <div className="grid grid-cols-1 gap-6 xl:grid-cols-3">
          <CardBox className="xl:col-span-2">
            <div className="space-y-4">
              <div>
                <h2 className="text-xl font-semibold">Create a delivery order</h2>
                <p className="text-sm text-gray-500">
                  Select a store, add a product, and confirm fees to dispatch a delivery.
                </p>
              </div>

              {errorMessage && (
                <div className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-600">
                  {errorMessage}
                </div>
              )}
              {successMessage && (
                <div className="rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-700">
                  {successMessage}
                  {lastOrder?.id && (
                    <LinkToOrder orderId={lastOrder.id} />
                  )}
                </div>
              )}

              <FormField label="Store">
                <select value={selectedStore} onChange={(event) => setSelectedStore(event.target.value)}>
                  <option value="">Select a store</option>
                  {stores.map((store) => (
                    <option key={store.id} value={store.id}>
                      {store.store_name || 'Unnamed store'}
                    </option>
                  ))}
                </select>
              </FormField>

              {stores.length === 0 && !loading && (
                <div className="rounded-lg border border-dashed border-gray-300 px-4 py-3 text-sm text-gray-500">
                  No stores yet. Create your first store to enable ordering.
                  <div className="mt-2">
                    <BaseButton href="/stores/stores-new" label="Create store" color="info" />
                  </div>
                </div>
              )}

              <FormField label="Product">
                <select
                  value={selectedProduct}
                  onChange={(event) => setSelectedProduct(event.target.value)}
                  disabled={!filteredProducts.length}
                >
                  <option value="">Select a product</option>
                  {filteredProducts.map((product) => (
                    <option key={product.id} value={product.id}>
                      {product.product_name || 'Unnamed product'}
                    </option>
                  ))}
                </select>
              </FormField>

              {!filteredProducts.length && !loading && (
                <div className="rounded-lg border border-dashed border-gray-300 px-4 py-3 text-sm text-gray-500">
                  No products available for this store.
                  <div className="mt-2">
                    <BaseButton href="/products/products-new" label="Add product" color="info" />
                  </div>
                </div>
              )}

              <FormField label="Quantity">
                <input
                  type="number"
                  min="1"
                  value={safeQuantity}
                  onChange={(event) => setQuantity(Number(event.target.value))}
                />
              </FormField>

              <FormField label="Delivery fee">
                <input
                  type="number"
                  min="0"
                  step="0.5"
                  value={deliveryFee}
                  onChange={(event) => setDeliveryFee(Number(event.target.value))}
                />
              </FormField>

              <FormField label="Service fee">
                <input
                  type="number"
                  min="0"
                  step="0.5"
                  value={serviceFee}
                  onChange={(event) => setServiceFee(Number(event.target.value))}
                />
              </FormField>

              <FormField label="Customer note" hasTextareaHeight>
                <textarea
                  value={customerNote}
                  onChange={(event) => setCustomerNote(event.target.value)}
                  placeholder="Delivery notes, landmarks, preferred time"
                />
              </FormField>

              <BaseDivider />

              <BaseButtons type="justify-start" mb="mb-0">
                <BaseButton
                  label={submitting ? 'Placing order...' : 'Place order'}
                  color="success"
                  onClick={handleSubmit}
                  disabled={submitting || loading}
                />
                <BaseButton href="/orders/orders-new" label="Advanced order form" color="white" outline />
              </BaseButtons>
            </div>
          </CardBox>

          <div className="space-y-6">
            <CardBox>
              <div className="space-y-4">
                <h3 className="text-lg font-semibold">Order summary</h3>
                <div className="text-sm text-gray-500">
                  <p>Product: {selectedProductData?.product_name || 'Select a product'}</p>
                  <p>Store: {stores.find((store) => store.id === selectedStore)?.store_name || 'Select a store'}</p>
                </div>
                <div className="space-y-2 text-sm">
                  <SummaryRow label="Unit price" value={formatCurrency(unitPrice)} />
                  <SummaryRow label="Quantity" value={safeQuantity.toString()} />
                  <SummaryRow label="Subtotal" value={formatCurrency(subtotal)} />
                  <SummaryRow label="Delivery fee" value={formatCurrency(Number(deliveryFee || 0))} />
                  <SummaryRow label="Service fee" value={formatCurrency(Number(serviceFee || 0))} />
                  <SummaryRow label="Total" value={formatCurrency(totalAmount)} strong />
                </div>
              </div>
            </CardBox>

            <CardBox>
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <h3 className="text-lg font-semibold">Recent orders</h3>
                  <BaseButton href="/orders/orders-list" label="View all" color="white" outline small />
                </div>
                {recentOrders.length === 0 && !loading && (
                  <p className="text-sm text-gray-500">No orders yet. Create the first one.</p>
                )}
                <div className="space-y-3">
                  {recentOrders.map((order) => (
                    <div key={order.id} className="rounded-lg border border-gray-200 px-3 py-2">
                      <p className="text-sm font-semibold">{order.order_number || 'Order'}</p>
                      <p className="text-xs text-gray-500">
                        {order.store?.store_name || 'Store'} · {formatCurrency(Number(order.total_amount || 0))}
                      </p>
                      <div className="mt-2">
                        <BaseButton
                          href={`/orders/orders-view?id=${order.id}`}
                          label="View"
                          color="info"
                          small
                        />
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </CardBox>
          </div>
        </div>
      </SectionMain>
    </>
  );
};

const SummaryRow = ({ label, value, strong = false }: { label: string; value: string; strong?: boolean }) => (
  <div className="flex items-center justify-between">
    <span className="text-gray-500">{label}</span>
    <span className={strong ? 'font-semibold text-gray-900' : 'text-gray-700'}>{value}</span>
  </div>
);

const LinkToOrder = ({ orderId }: { orderId: string }) => (
  <div className="mt-2">
    <BaseButton href={`/orders/orders-view?id=${orderId}`} label="View order" color="success" small />
  </div>
);

QuickOrder.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};

export default QuickOrder;
