import axios from 'axios';
import React, { ReactElement, useEffect, useState } from 'react';
import Head from 'next/head'
import { useAppDispatch, useAppSelector } from "../../stores/hooks";
import { useRouter } from "next/router";
import { fetch } from '../../stores/orders/ordersSlice'
import dataFormatter from '../../helpers/dataFormatter';
import LayoutAuthenticated from "../../layouts/Authenticated";
import { getPageTitle } from "../../config";
import SectionTitleLineWithButton from "../../components/SectionTitleLineWithButton";
import SectionMain from "../../components/SectionMain";
import BaseButton from "../../components/BaseButton";
import { mdiChartTimelineVariant } from "@mdi/js";


const orderSteps = ['submitted', 'approved', 'picking', 'shipped', 'delivered'];

const readableValue = (value) => {
  if (!value) {
    return 'Not set';
  }

  return String(value).replace(/_/g, ' ');
};

const relatedArray = (value) => {
  if (Array.isArray(value)) {
    return value;
  }

  return [];
};

const formatMoney = (value) => {
  if (value === null || value === undefined || value === '') {
    return '$0.00';
  }

  const amount = Number(value);
  if (Number.isNaN(amount)) {
    return value;
  }

  return amount.toLocaleString('en-US', {
    style: 'currency',
    currency: 'USD',
    maximumFractionDigits: 2,
  });
};

const formatDate = (value) => {
  if (!value) {
    return 'Not scheduled';
  }

  return dataFormatter.dateTimeFormatter(value);
};

const readIntegrationError = (error) => {
  if (axios.isAxiosError(error)) {
    if (typeof error.response?.data === 'string') {
      return error.response.data;
    }

    if (error.response?.data) {
      return JSON.stringify(error.response.data);
    }
  }

  return error?.message || 'Integration action failed.';
};

const badgeClasses = (value) => {
  if (value === 'delivered' || value === 'shipped' || value === 'approved' || value === 'submitted') {
    return 'border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-800 dark:bg-emerald-950 dark:text-emerald-100';
  }

  if (value === 'picking' || value === 'draft') {
    return 'border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-800 dark:bg-amber-950 dark:text-amber-100';
  }

  if (value === 'cancelled' || value === 'void') {
    return 'border-rose-200 bg-rose-50 text-rose-800 dark:border-rose-800 dark:bg-rose-950 dark:text-rose-100';
  }

  return 'border-slate-200 bg-slate-50 text-slate-700 dark:border-dark-700 dark:bg-dark-800 dark:text-slate-200';
};

const StatusBadge = ({ value }) => (
  <span className={`inline-flex rounded-full border px-3 py-1 text-xs font-semibold capitalize ${badgeClasses(value)}`}>
    {readableValue(value)}
  </span>
);

const InfoCard = ({ label, value }) => (
  <div className='rounded-xl border border-slate-200 bg-white p-4 dark:border-dark-700 dark:bg-dark-900'>
    <div className='text-xs font-bold uppercase tracking-[0.16em] text-slate-500 dark:text-slate-400'>{label}</div>
    <div className='mt-2 text-lg font-semibold text-slate-950 dark:text-white'>{value}</div>
  </div>
);

const SectionPanel = ({ title, subtitle, children }) => (
  <section className='rounded-2xl border border-slate-200 bg-white shadow-sm dark:border-dark-700 dark:bg-dark-900'>
    <div className='border-b border-slate-200 p-5 dark:border-dark-700'>
      <h2 className='text-lg font-semibold text-slate-950 dark:text-white'>{title}</h2>
      {subtitle && <p className='mt-1 text-sm text-slate-500 dark:text-slate-400'>{subtitle}</p>}
    </div>
    <div className='p-5'>{children}</div>
  </section>
);

const EmptyState = ({ label }) => (
  <div className='rounded-xl border border-dashed border-slate-300 bg-slate-50 p-6 text-center text-sm text-slate-500 dark:border-dark-700 dark:bg-dark-800 dark:text-slate-400'>
    {label}
  </div>
);

const DetailMeta = ({ label, value }) => (
  <div>
    <div className='text-xs font-bold uppercase tracking-[0.16em] text-slate-500 dark:text-slate-400'>{label}</div>
    <div className='mt-1 font-semibold text-slate-950 dark:text-white'>{value}</div>
  </div>
);

const productLabel = (item) => {
  if (item.product?.product_name) {
    return item.product.product_name;
  }

  if (item.product?.sku) {
    return item.product.sku;
  }

  if (item.productId) {
    return `Product ${String(item.productId).slice(-6)}`;
  }

  return 'Catalog item';
};

const OrdersView = () => {
    const router = useRouter()
    const dispatch = useAppDispatch()
    const { orders } = useAppSelector((state) => state.orders)
    const [activeIntegration, setActiveIntegration] = useState('');
    const [integrationResult, setIntegrationResult] = useState<any>(null);

    const { id } = router.query;

    useEffect(() => {
        dispatch(fetch({ id }));
    }, [dispatch, id]);

    const orderItems = relatedArray(orders?.order_items_order);
    const shipments = relatedArray(orders?.shipments_order);
    const orderNumber = orders?.order_number || 'Purchase order';
    const accountName = orders?.account?.account_name || 'No account';
    const buyerName = [orders?.buyer?.firstName, orders?.buyer?.lastName].filter(Boolean).join(' ') || 'No buyer';
    const location = orders?.location;
    const deliveryAddress = location ? [
      location.address_line_1,
      location.address_line_2,
      [location.city, location.state, location.postal_code].filter(Boolean).join(', '),
    ].filter(Boolean) : [];
    const statusIndex = orderSteps.indexOf(orders?.order_status);
    const orderTotalCents = Math.round(Number(orders?.order_total || 125) * 100);
    const dropoffAddress = deliveryAddress.join(', ') || '500 W Madison St, Chicago, IL 60661';

    const runOrderIntegration = async (integration) => {
      setActiveIntegration(integration);
      setIntegrationResult(null);

      try {
        if (integration === 'stripe') {
          const { data } = await axios.post('/integrations/stripe/checkout', {
            amountCents: orderTotalCents,
            currency: 'usd',
            orderLabel: `${orderNumber} - ${accountName}`,
            successUrl: window.location.href,
            cancelUrl: window.location.href,
          });
          setIntegrationResult({
            type: 'success',
            title: 'Stripe checkout created',
            message: data.url || data.sessionId,
          });
          return;
        }

        if (integration === 'quickbooks') {
          const { data } = await axios.post('/integrations/quickbooks/create-invoice', {
            orderId: typeof id === 'string' ? id : undefined,
            amount: Number(orders?.order_total || 125),
            description: orderNumber,
          });
          setIntegrationResult({
            type: 'success',
            title: 'QuickBooks invoice created',
            message: `Invoice ${data.invoiceId || data.docNumber} was created.`,
          });
          return;
        }

        if (integration === 'doordash') {
          const { data } = await axios.post('/integrations/delivery/create-quote', {
            provider: 'doordash',
            dropoffAddress,
            dropoffBusinessName: location?.location_name || accountName,
            orderValue: orderTotalCents,
          });
          setIntegrationResult({
            type: 'success',
            title: 'DoorDash quote created',
            message: data.quote?.external_delivery_id || 'Local delivery quote returned.',
          });
          return;
        }

        if (integration === 'shippo') {
          const { data } = await axios.post('/integrations/delivery/create-quote', {
            provider: 'shippo',
          });
          setIntegrationResult({
            type: 'success',
            title: 'Shippo rates created',
            message: `${data.rates?.length || 0} carrier rates returned.`,
          });
        }
      } catch (error) {
        setIntegrationResult({
          type: 'error',
          title: 'Integration needs configuration',
          message: readIntegrationError(error),
        });
      } finally {
        setActiveIntegration('');
      }
    };

    return (
      <>
          <Head>
              <title>{getPageTitle(orderNumber)}</title>
          </Head>
          <SectionMain>
            <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="Purchase order" main>
                <BaseButton
                  color='info'
                  label='Edit order'
                  href={`/orders/orders-edit/?id=${id}`}
                />
            </SectionTitleLineWithButton>

            <div className='space-y-6'>
              <div className='overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm dark:border-dark-700 dark:bg-dark-900'>
                <div className='grid lg:grid-cols-[1.4fr_1fr]'>
                  <div className='p-6 lg:p-8'>
                    <div className='mb-4 flex flex-wrap gap-2'>
                      <StatusBadge value={orders?.order_status} />
                      <StatusBadge value={orders?.payment_terms} />
                    </div>
                    <div className='text-xs font-bold uppercase tracking-[0.22em] text-emerald-700 dark:text-emerald-300'>
                      Buyer purchase order
                    </div>
                    <h1 className='mt-3 text-3xl font-semibold tracking-normal text-slate-950 dark:text-white'>
                      {orderNumber}
                    </h1>
                    <p className='mt-3 max-w-3xl text-base leading-7 text-slate-600 dark:text-slate-300'>
                      {accountName} placed PO {orders?.po_number || 'without a PO number'} for delivery to {location?.location_name || 'an assigned location'}.
                    </p>

                    <div className='mt-6 grid gap-4 sm:grid-cols-2 lg:grid-cols-4'>
                      <DetailMeta label='Account' value={accountName} />
                      <DetailMeta label='Buyer' value={buyerName} />
                      <DetailMeta label='Requested' value={formatDate(orders?.requested_delivery_date)} />
                      <DetailMeta label='Promised' value={formatDate(orders?.promised_delivery_date)} />
                    </div>
                  </div>

                  <div className='grid grid-cols-2 gap-3 border-t border-slate-200 bg-slate-50 p-6 dark:border-dark-700 dark:bg-dark-800 lg:border-l lg:border-t-0'>
                    <InfoCard label='Order total' value={formatMoney(orders?.order_total)} />
                    <InfoCard label='Line items' value={orderItems.length} />
                    <InfoCard label='Ordered at' value={formatDate(orders?.ordered_at)} />
                    <InfoCard label='Shipments' value={shipments.length} />
                  </div>
                </div>
              </div>

              <SectionPanel
                title='Connected order actions'
                subtitle='Create payment, accounting, and delivery records directly from this purchase order.'
              >
                  <div className='grid gap-3 md:grid-cols-2 xl:grid-cols-4'>
                    {[
                      {
                        key: 'stripe',
                        title: 'Stripe checkout',
                        body: 'Collect prepaid or card/ACH payment for this PO.',
                        button: 'Create checkout',
                      },
                      {
                        key: 'quickbooks',
                        title: 'QuickBooks invoice',
                        body: 'Create an accounting invoice after fulfillment review.',
                        button: 'Create invoice',
                      },
                      {
                        key: 'doordash',
                        title: 'DoorDash Drive',
                        body: 'Quote local delivery to the buyer receiving location.',
                        button: 'Get quote',
                      },
                      {
                        key: 'shippo',
                        title: 'Shippo rates',
                        body: 'Create a parcel shipment request and return carrier rates.',
                        button: 'Get rates',
                      },
                    ].map((item) => (
                      <div
                        key={item.key}
                        className='rounded-xl border border-slate-200 bg-slate-50 p-4 dark:border-dark-700 dark:bg-dark-800'
                      >
                        <div className='text-sm font-semibold text-slate-950 dark:text-white'>
                          {item.title}
                        </div>
                        <p className='mt-2 min-h-[48px] text-sm leading-6 text-slate-600 dark:text-slate-300'>
                          {item.body}
                        </p>
                        <button
                          type='button'
                          onClick={() => runOrderIntegration(item.key)}
                          className='mt-4 inline-flex h-10 items-center rounded-xl bg-slate-950 px-4 text-sm font-semibold text-white hover:bg-slate-800 dark:bg-white dark:text-slate-950'
                        >
                          {activeIntegration === item.key ? 'Running' : item.button}
                        </button>
                      </div>
                    ))}
                  </div>
                  {integrationResult && (
                    <div
                      className={`mt-4 rounded-xl border p-4 text-sm font-semibold ${
                        integrationResult.type === 'success'
                          ? 'border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
                          : 'border-amber-200 bg-amber-50 text-amber-900 dark:border-amber-800 dark:bg-amber-950 dark:text-amber-100'
                      }`}
                    >
                      <div>{integrationResult.title}</div>
                      <div className='mt-1 break-words font-normal'>{integrationResult.message}</div>
                    </div>
                  )}
              </SectionPanel>

              <SectionPanel title='Fulfillment status' subtitle='Operational progress from buyer submission to delivery confirmation.'>
                <div className='grid gap-3 md:grid-cols-5'>
                  {orderSteps.map((step, index) => {
                    const isComplete = statusIndex >= index;
                    const isCurrent = statusIndex === index;

                    return (
                      <div
                        key={step}
                        className={`rounded-xl border p-4 ${
                          isComplete
                            ? 'border-emerald-200 bg-emerald-50 dark:border-emerald-800 dark:bg-emerald-950'
                            : 'border-slate-200 bg-slate-50 dark:border-dark-700 dark:bg-dark-800'
                        }`}
                      >
                        <div className={`mb-3 flex h-8 w-8 items-center justify-center rounded-full text-sm font-bold ${
                          isComplete
                            ? 'bg-emerald-600 text-white'
                            : 'bg-white text-slate-500 dark:bg-dark-900 dark:text-slate-300'
                        }`}>
                          {index + 1}
                        </div>
                        <div className='font-semibold capitalize text-slate-950 dark:text-white'>{readableValue(step)}</div>
                        <div className='mt-1 text-xs text-slate-500 dark:text-slate-400'>
                          {isCurrent ? 'Current step' : isComplete ? 'Completed' : 'Pending'}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </SectionPanel>

              <div className='grid gap-6 xl:grid-cols-[1fr_1fr]'>
                <SectionPanel title='Delivery handoff' subtitle='Ship-to location and receiving instructions.'>
                  <div className='rounded-xl border border-slate-200 bg-slate-50 p-4 dark:border-dark-700 dark:bg-dark-800'>
                    <div className='flex items-start justify-between gap-4'>
                      <div>
                        <div className='text-base font-semibold text-slate-950 dark:text-white'>{location?.location_name || 'No location'}</div>
                        <div className='mt-1 text-sm capitalize text-slate-500 dark:text-slate-400'>{readableValue(location?.location_type)}</div>
                      </div>
                      {location?.is_active && <StatusBadge value='active' />}
                    </div>
                    <div className='mt-4 text-sm leading-6 text-slate-600 dark:text-slate-300'>
                      {deliveryAddress.length > 0 ? deliveryAddress.map((line) => <div key={line}>{line}</div>) : 'No address on file.'}
                    </div>
                    <div className='mt-4 rounded-lg bg-white p-3 text-sm text-slate-600 dark:bg-dark-900 dark:text-slate-300'>
                      {location?.delivery_instructions || 'No delivery instructions yet.'}
                    </div>
                  </div>
                </SectionPanel>

                <SectionPanel title='Order notes' subtitle='Buyer comments and internal fulfillment context.'>
                  <div className='grid gap-4 sm:grid-cols-2'>
                    <div className='rounded-xl border border-slate-200 bg-slate-50 p-4 dark:border-dark-700 dark:bg-dark-800'>
                      <div className='mb-2 text-xs font-bold uppercase tracking-[0.16em] text-slate-500 dark:text-slate-400'>Buyer notes</div>
                      <div className='text-sm leading-6 text-slate-700 dark:text-slate-200'>{orders?.buyer_notes || 'No buyer notes.'}</div>
                    </div>
                    <div className='rounded-xl border border-slate-200 bg-slate-50 p-4 dark:border-dark-700 dark:bg-dark-800'>
                      <div className='mb-2 text-xs font-bold uppercase tracking-[0.16em] text-slate-500 dark:text-slate-400'>Internal notes</div>
                      <div className='text-sm leading-6 text-slate-700 dark:text-slate-200'>{orders?.internal_notes || 'No internal notes.'}</div>
                    </div>
                  </div>
                </SectionPanel>
              </div>

              <SectionPanel title='Order lines' subtitle='Case quantities, contract prices, fulfillment status, and kitchen-facing notes.'>
                {orderItems.length > 0 ? (
                  <div className='grid gap-4 lg:grid-cols-2'>
                    {orderItems.map((item: any) => (
                      <button
                        key={item.id}
                        type='button'
                        className='rounded-xl border border-slate-200 bg-slate-50 p-4 text-left transition hover:border-emerald-200 hover:bg-emerald-50 dark:border-dark-700 dark:bg-dark-800 dark:hover:border-emerald-800 dark:hover:bg-emerald-950'
                        onClick={() => router.push(`/order_items/order_items-view/?id=${item.id}`)}
                      >
                        <div className='flex items-start justify-between gap-4'>
                          <div>
                            <div className='font-semibold text-slate-950 dark:text-white'>{productLabel(item)}</div>
                            <div className='mt-1 max-w-full break-all text-xs text-slate-500 dark:text-slate-400'>{item.product?.sku || item.productId}</div>
                          </div>
                          <StatusBadge value={item.fulfillment_status} />
                        </div>

                        <div className='mt-4 grid grid-cols-3 gap-3 text-sm'>
                          <div className='rounded-lg border border-slate-200 bg-white p-3 dark:border-dark-700 dark:bg-dark-900'>
                            <div className='text-xs font-bold uppercase tracking-[0.14em] text-slate-500 dark:text-slate-400'>Cases</div>
                            <div className='mt-1 font-semibold text-slate-950 dark:text-white'>{item.quantity_cases}</div>
                          </div>
                          <div className='rounded-lg border border-slate-200 bg-white p-3 dark:border-dark-700 dark:bg-dark-900'>
                            <div className='text-xs font-bold uppercase tracking-[0.14em] text-slate-500 dark:text-slate-400'>Case</div>
                            <div className='mt-1 font-semibold text-slate-950 dark:text-white'>{formatMoney(item.case_price)}</div>
                          </div>
                          <div className='rounded-lg border border-slate-200 bg-white p-3 dark:border-dark-700 dark:bg-dark-900'>
                            <div className='text-xs font-bold uppercase tracking-[0.14em] text-slate-500 dark:text-slate-400'>Total</div>
                            <div className='mt-1 font-semibold text-slate-950 dark:text-white'>{formatMoney(item.line_total)}</div>
                          </div>
                        </div>

                        <div className='mt-4 rounded-lg bg-white p-3 text-sm text-slate-600 dark:bg-dark-900 dark:text-slate-300'>
                          {item.line_notes || 'No line notes'}
                        </div>
                      </button>
                    ))}
                  </div>
                ) : (
                  <EmptyState label='No order lines yet.' />
                )}
              </SectionPanel>

              <div className='grid gap-6 xl:grid-cols-[1fr_420px]'>
                <SectionPanel title='Shipments' subtitle='Carrier tracking and delivery confirmation.'>
                  {shipments.length > 0 ? (
                    <div className='grid gap-4 lg:grid-cols-2'>
                      {shipments.map((item: any) => (
                        <button
                          key={item.id}
                          type='button'
                          onClick={() => router.push(`/shipments/shipments-view/?id=${item.id}`)}
                          className='rounded-xl border border-slate-200 bg-slate-50 p-4 text-left transition hover:border-emerald-200 hover:bg-emerald-50 dark:border-dark-700 dark:bg-dark-800 dark:hover:border-emerald-800 dark:hover:bg-emerald-950'
                        >
                          <div className='flex items-start justify-between gap-4'>
                            <div>
                              <div className='font-semibold text-slate-950 dark:text-white'>{item.shipment_number}</div>
                              <div className='mt-1 text-sm text-slate-500 dark:text-slate-400'>{item.carrier || 'No carrier'} · {item.tracking_number || 'No tracking'}</div>
                            </div>
                            <StatusBadge value={item.shipment_status} />
                          </div>
                          <div className='mt-4 grid gap-2 text-sm text-slate-600 dark:text-slate-300'>
                            <div>Shipped: {formatDate(item.shipped_at)}</div>
                            <div>Delivered: {formatDate(item.delivered_at)}</div>
                          </div>
                        </button>
                      ))}
                    </div>
                  ) : (
                    <EmptyState label='No shipments attached yet.' />
                  )}
                </SectionPanel>

                <SectionPanel title='Totals' subtitle='Financial summary for this purchase order.'>
                  <div className='space-y-3 text-sm'>
                    <TotalRow label='Subtotal' value={formatMoney(orders?.subtotal)} />
                    <TotalRow label='Tax' value={formatMoney(orders?.tax_total)} />
                    <TotalRow label='Shipping' value={formatMoney(orders?.shipping_total)} />
                    <div className='border-t border-slate-200 pt-3 dark:border-dark-700'>
                      <TotalRow label='Order total' value={formatMoney(orders?.order_total)} strong />
                    </div>
                  </div>
                </SectionPanel>
              </div>

              <div>
                <BaseButton
                    color='info'
                    label='Back to orders'
                    onClick={() => router.push('/orders/orders-list')}
                />
              </div>
            </div>
          </SectionMain>
      </>
    );
};

const TotalRow = ({ label, value, strong = false }) => (
  <div className='flex items-center justify-between gap-4'>
    <div className={strong ? 'text-base font-semibold text-slate-950 dark:text-white' : 'text-slate-600 dark:text-slate-300'}>
      {label}
    </div>
    <div className={strong ? 'text-xl font-semibold text-slate-950 dark:text-white' : 'font-semibold text-slate-950 dark:text-white'}>
      {value}
    </div>
  </div>
);

OrdersView.getLayout = function getLayout(page: ReactElement) {
    return (
      <LayoutAuthenticated
        
        permission={'READ_ORDERS'}
        
      >
          {page}
      </LayoutAuthenticated>
    )
}

export default OrdersView;
