import React, { ReactElement, useEffect } from 'react';
import Head from 'next/head'
import { useAppDispatch, useAppSelector } from "../../stores/hooks";
import { useRouter } from "next/router";
import { fetch } from '../../stores/accounts/accountsSlice'
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 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 'No data';
  }

  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 'No date';
  }

  return dataFormatter.dateTimeFormatter(value);
};

const booleanLabel = (value) => dataFormatter.booleanFormatter(value);

const badgeClasses = (value) => {
  if (value === 'good' || value === 'active' || 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 === 'hold' || value === 'pending' || value === 'draft' || value === 'requested') {
    return 'border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-800 dark:bg-amber-950 dark:text-amber-100';
  }

  if (value === 'delinquent' || value === 'cancelled' || value === 'rejected') {
    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 AccountMeta = ({ 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 AccountsView = () => {
    const router = useRouter()
    const dispatch = useAppDispatch()
    const { accounts } = useAppSelector((state) => state.accounts)

    const { id } = router.query;

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

    const locations = relatedArray(accounts?.locations_account);
    const contacts = relatedArray(accounts?.contacts_account);
    const accountPriceLists = relatedArray(accounts?.account_price_lists_account);
    const carts = relatedArray(accounts?.carts_account);
    const orders = relatedArray(accounts?.orders_account);
    const quotes = relatedArray(accounts?.quotes_account);
    const sampleRequests = relatedArray(accounts?.sample_requests_account);
    const savedLists = relatedArray(accounts?.saved_lists_account);
    const accountName = accounts?.account_name || 'Buyer account';
    const defaultPriceList = accounts?.default_price_list?.price_list_name || 'No price list';
    const assignedRep = accounts?.assigned_sales_rep?.firstName || 'No rep assigned';

    return (
      <>
          <Head>
              <title>{getPageTitle(accountName)}</title>
          </Head>
          <SectionMain>
            <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="Buyer account" main>
                <BaseButton
                  color='info'
                  label='Edit account'
                  href={`/accounts/accounts-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={accounts?.credit_status} />
                      <StatusBadge value={accounts?.is_active ? 'active' : 'inactive'} />
                      <span className='inline-flex rounded-full border border-slate-200 bg-slate-50 px-3 py-1 text-xs font-semibold capitalize text-slate-700 dark:border-dark-700 dark:bg-dark-800 dark:text-slate-200'>
                        {readableValue(accounts?.account_type)}
                      </span>
                    </div>
                    <div className='text-xs font-bold uppercase tracking-[0.22em] text-emerald-700 dark:text-emerald-300'>
                      Foodservice buyer profile
                    </div>
                    <h1 className='mt-3 text-3xl font-semibold tracking-normal text-slate-950 dark:text-white'>
                      {accountName}
                    </h1>
                    <p className='mt-3 max-w-3xl text-base leading-7 text-slate-600 dark:text-slate-300'>
                      Purchasing account for contract pricing, location-specific delivery, buyer contacts, saved order guides, sample requests, quotes, and purchase orders.
                    </p>

                    <div className='mt-6 grid gap-4 sm:grid-cols-2 lg:grid-cols-4'>
                      <AccountMeta label='Account no.' value={accounts?.account_number || 'No data'} />
                      <AccountMeta label='Price list' value={defaultPriceList} />
                      <AccountMeta label='Credit limit' value={formatMoney(accounts?.credit_limit)} />
                      <AccountMeta label='Sales rep' value={assignedRep} />
                    </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='Locations' value={locations.length} />
                    <InfoCard label='Contacts' value={contacts.length} />
                    <InfoCard label='Orders' value={orders.length} />
                    <InfoCard label='Saved guides' value={savedLists.length} />
                  </div>
                </div>
              </div>

              <div className='grid gap-6 xl:grid-cols-[1fr_1fr]'>
                <SectionPanel title='Commercial terms' subtitle='Credit, tax, and account assignment details.'>
                  <div className='grid gap-4 sm:grid-cols-2'>
                    <InfoCard label='Credit status' value={<StatusBadge value={accounts?.credit_status} />} />
                    <InfoCard label='Credit limit' value={formatMoney(accounts?.credit_limit)} />
                    <InfoCard label='Tax exempt' value={booleanLabel(accounts?.is_tax_exempt)} />
                    <InfoCard label='Tax exempt no.' value={accounts?.tax_exempt_number || 'No data'} />
                  </div>
                </SectionPanel>

                <SectionPanel title='Account notes' subtitle='Internal context for sales, finance, and fulfillment teams.'>
                  <div className='min-h-40 rounded-xl border border-slate-200 bg-slate-50 p-4 text-sm leading-6 text-slate-700 dark:border-dark-700 dark:bg-dark-800 dark:text-slate-200'>
                    {accounts?.notes || 'No account notes yet.'}
                  </div>
                </SectionPanel>
              </div>

              <SectionPanel title='Delivery locations' subtitle='Buyer sites that can receive foodservice orders.'>
                {locations.length > 0 ? (
                  <div className='grid gap-4 lg:grid-cols-2'>
                    {locations.map((item: any) => (
                      <button
                        key={item.id}
                        type='button'
                        onClick={() => router.push(`/locations/locations-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='text-base font-semibold text-slate-950 dark:text-white'>{item.location_name}</div>
                            <div className='mt-1 text-sm capitalize text-slate-500 dark:text-slate-400'>{readableValue(item.location_type)}</div>
                          </div>
                          <StatusBadge value={item.is_active ? 'active' : 'inactive'} />
                        </div>
                        <div className='mt-4 text-sm leading-6 text-slate-600 dark:text-slate-300'>
                          {item.address_line_1}{item.address_line_2 ? `, ${item.address_line_2}` : ''}<br />
                          {[item.city, item.state, item.postal_code].filter(Boolean).join(', ')}
                        </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.delivery_instructions || 'No delivery instructions yet.'}
                        </div>
                      </button>
                    ))}
                  </div>
                ) : (
                  <EmptyState label='No delivery locations yet.' />
                )}
              </SectionPanel>

              <SectionPanel title='Buyer contacts' subtitle='People who can place orders, see invoices, or own the account relationship.'>
                {contacts.length > 0 ? (
                  <div className='grid gap-4 lg:grid-cols-2'>
                    {contacts.map((item: any) => (
                      <button
                        key={item.id}
                        type='button'
                        onClick={() => router.push(`/contacts/contacts-view/?id=${item.id}`)}
                        className='rounded-xl border border-slate-200 bg-white p-4 text-left transition hover:border-emerald-200 hover:bg-emerald-50 dark:border-dark-700 dark:bg-dark-900 dark:hover:border-emerald-800 dark:hover:bg-emerald-950'
                      >
                        <div className='flex items-start justify-between gap-4'>
                          <div>
                            <div className='text-base font-semibold text-slate-950 dark:text-white'>{item.contact_name}</div>
                            <div className='mt-1 text-sm text-slate-500 dark:text-slate-400'>{item.role_title || 'Buyer contact'}</div>
                          </div>
                          {item.is_primary && <StatusBadge value='primary' />}
                        </div>
                        <div className='mt-4 space-y-1 text-sm text-slate-600 dark:text-slate-300'>
                          <div>{item.email || 'No email'}</div>
                          <div>{item.phone || 'No phone'}</div>
                        </div>
                        <div className='mt-4 flex flex-wrap gap-2'>
                          <StatusBadge value={item.can_place_orders ? 'can order' : 'view only'} />
                          <StatusBadge value={item.can_see_invoices ? 'invoice access' : 'no invoices'} />
                        </div>
                      </button>
                    ))}
                  </div>
                ) : (
                  <EmptyState label='No buyer contacts yet.' />
                )}
              </SectionPanel>

              <div className='grid gap-6 xl:grid-cols-2'>
                <SectionPanel title='Price agreements' subtitle='Effective contract pricing windows for this account.'>
                  {accountPriceLists.length > 0 ? (
                    <div className='space-y-3'>
                      {accountPriceLists.map((item: any) => (
                        <button
                          key={item.id}
                          type='button'
                          onClick={() => router.push(`/account_price_lists/account_price_lists-view/?id=${item.id}`)}
                          className='flex w-full items-center justify-between gap-4 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>
                            <div className='font-semibold text-slate-950 dark:text-white'>{item.price_list?.price_list_name || defaultPriceList}</div>
                            <div className='mt-1 text-sm text-slate-500 dark:text-slate-400'>
                              {formatDate(item.effective_start)} - {formatDate(item.effective_end)}
                            </div>
                          </div>
                          {item.is_primary && <StatusBadge value='primary' />}
                        </button>
                      ))}
                    </div>
                  ) : (
                    <EmptyState label='No account price agreements yet.' />
                  )}
                </SectionPanel>

                <SectionPanel title='Saved order guides' subtitle='Reusable reorder lists for routine restaurant purchasing.'>
                  {savedLists.length > 0 ? (
                    <div className='space-y-3'>
                      {savedLists.map((item: any) => (
                        <button
                          key={item.id}
                          type='button'
                          onClick={() => router.push(`/saved_lists/saved_lists-view/?id=${item.id}`)}
                          className='w-full 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.list_name}</div>
                              <div className='mt-1 text-sm capitalize text-slate-500 dark:text-slate-400'>{readableValue(item.list_type)}</div>
                            </div>
                            <StatusBadge value='reorder guide' />
                          </div>
                          <div className='mt-3 text-sm text-slate-600 dark:text-slate-300'>{item.notes || 'No notes'}</div>
                        </button>
                      ))}
                    </div>
                  ) : (
                    <EmptyState label='No saved order guides yet.' />
                  )}
                </SectionPanel>
              </div>

              <SectionPanel title='Commercial activity' subtitle='Recent carts, purchase orders, quotes, and sample requests tied to this buyer account.'>
                <div className='grid gap-4 xl:grid-cols-4'>
                  <ActivityColumn
                    title='Open carts'
                    items={carts}
                    emptyLabel='No carts.'
                    route='carts'
                    primary='po_number'
                    secondary='cart_status'
                    dateField='requested_delivery_date'
                    router={router}
                  />
                  <ActivityColumn
                    title='Orders'
                    items={orders}
                    emptyLabel='No orders.'
                    route='orders'
                    primary='order_number'
                    secondary='order_status'
                    dateField='requested_delivery_date'
                    amountField='order_total'
                    router={router}
                  />
                  <ActivityColumn
                    title='Quotes'
                    items={quotes}
                    emptyLabel='No quotes.'
                    route='quotes'
                    primary='quote_number'
                    secondary='quote_status'
                    dateField='expires_at'
                    amountField='quote_total'
                    router={router}
                  />
                  <ActivityColumn
                    title='Samples'
                    items={sampleRequests}
                    emptyLabel='No samples.'
                    route='sample_requests'
                    primary='sample_request_number'
                    secondary='sample_status'
                    dateField='needed_by'
                    router={router}
                  />
                </div>
              </SectionPanel>

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

const ActivityColumn = ({ title, items, emptyLabel, route, primary, secondary, dateField, amountField, router }) => (
  <div className='rounded-xl border border-slate-200 bg-slate-50 p-4 dark:border-dark-700 dark:bg-dark-800'>
    <div className='mb-3 text-sm font-semibold text-slate-950 dark:text-white'>{title}</div>
    {items.length > 0 ? (
      <div className='space-y-3'>
        {items.slice(0, 4).map((item: any) => (
          <button
            key={item.id}
            type='button'
            onClick={() => router.push(`/${route}/${route}-view/?id=${item.id}`)}
            className='w-full rounded-lg border border-slate-200 bg-white p-3 text-left transition hover:border-emerald-200 hover:bg-emerald-50 dark:border-dark-700 dark:bg-dark-900 dark:hover:border-emerald-800 dark:hover:bg-emerald-950'
          >
            <div className='font-semibold text-slate-950 dark:text-white'>{item[primary] || 'No number'}</div>
            <div className='mt-2 flex flex-wrap items-center gap-2'>
              <StatusBadge value={item[secondary]} />
              {amountField && <span className='text-sm font-semibold text-slate-700 dark:text-slate-200'>{formatMoney(item[amountField])}</span>}
            </div>
            <div className='mt-2 text-xs text-slate-500 dark:text-slate-400'>{formatDate(item[dateField])}</div>
          </button>
        ))}
      </div>
    ) : (
      <EmptyState label={emptyLabel} />
    )}
  </div>
);

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

export default AccountsView;
