import * as icon from '@mdi/js';
import Head from 'next/head';
import Link from 'next/link';
import React, { ReactElement, useEffect, useMemo, useState } from 'react';
import axios from 'axios';

import CardBox from '../../components/CardBox';
import LayoutAuthenticated from '../../layouts/Authenticated';
import LoadingSpinner from '../../components/LoadingSpinner';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import { getPageTitle } from '../../config';
import { hasPermission } from '../../helpers/userPermissions';
import { useAppSelector } from '../../stores/hooks';

type UserSummary = {
  firstName?: string;
  lastName?: string;
  email?: string;
};

type AccountSummary = {
  account_name?: string;
  account_type?: string;
};

type LocationSummary = {
  location_name?: string;
  city?: string;
  state?: string;
};

type ProductSummary = {
  sku?: string;
  product_name?: string;
  brand?: string;
  pack_size?: string;
  temperature_zone?: string;
  category?: {
    category_name?: string;
  };
};

type SampleRequest = {
  id: string;
  sample_request_number: string;
  sample_quantity?: number;
  requested_at?: string;
  needed_by?: string;
  sample_status?: string;
  notes?: string;
  account?: AccountSummary;
  location?: LocationSummary;
  product?: ProductSummary;
  requested_by?: UserSummary;
};

const dateFormatter = new Intl.DateTimeFormat('en-US', {
  month: 'short',
  day: 'numeric',
});

const statusOptions = [
  { label: 'All', value: 'all' },
  { label: 'Requested', value: 'requested' },
  { label: 'Approved', value: 'approved' },
  { label: 'Shipped', value: 'shipped' },
  { label: 'Delivered', value: 'delivered' },
];

const sampleFlow = [
  'Requested by buyer',
  'Sales review',
  'Sample shipped',
  'Chef feedback',
  'Quote or PO follow-up',
];

const formatDate = (value?: string) => {
  if (!value) {
    return 'Not set';
  }

  return dateFormatter.format(new Date(value));
};

const formatUserName = (user?: UserSummary) => {
  if (!user) {
    return 'Unassigned';
  }

  const name = [user.firstName, user.lastName].filter(Boolean).join(' ');
  return name || user.email || 'Unassigned';
};

const humanizeStatus = (status?: string) => {
  if (!status) {
    return 'Unassigned';
  }

  return status
    .split('_')
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join(' ');
};

const getStatusClass = (status?: string) => {
  if (['approved', 'delivered'].includes(status || '')) {
    return 'border-emerald-200 bg-emerald-50 text-emerald-800';
  }

  if (status === 'shipped') {
    return 'border-blue-200 bg-blue-50 text-blue-800';
  }

  if (status === 'requested') {
    return 'border-amber-200 bg-amber-50 text-amber-800';
  }

  if (['declined', 'cancelled'].includes(status || '')) {
    return 'border-rose-200 bg-rose-50 text-rose-800';
  }

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

const StatusPill = ({ status }: { status?: string }) => (
  <span
    className={`inline-flex rounded-full border px-2.5 py-1 text-xs font-bold ${getStatusClass(
      status,
    )}`}
  >
    {humanizeStatus(status)}
  </span>
);

const SampleRequestsListPage = () => {
  const { currentUser } = useAppSelector((state) => state.auth);
  const [sampleRequests, setSampleRequests] = useState<SampleRequest[]>([]);
  const [selectedStatus, setSelectedStatus] = useState('all');
  const [isLoading, setIsLoading] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');

  const hasCreatePermission =
    !!currentUser && hasPermission(currentUser, 'CREATE_SAMPLE_REQUESTS');

  const loadSampleRequests = async () => {
    setIsLoading(true);
    setErrorMessage('');

    try {
      const { data } = await axios.get('/sample_requests', {
        params: { page: 0, limit: 30 },
      });
      setSampleRequests(data.rows || []);
    } catch (error) {
      console.error('Failed to load sample requests', error);
      setErrorMessage('Unable to load sample requests.');
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    if (!currentUser) {
      return;
    }

    void loadSampleRequests();
  }, [currentUser?.id]);

  const filteredRequests = useMemo(() => {
    if (selectedStatus === 'all') {
      return sampleRequests;
    }

    return sampleRequests.filter(
      (item) => item.sample_status === selectedStatus,
    );
  }, [sampleRequests, selectedStatus]);

  const requestedCount = sampleRequests.filter(
    (item) => item.sample_status === 'requested',
  ).length;
  const approvedCount = sampleRequests.filter(
    (item) => item.sample_status === 'approved',
  ).length;
  const deliveredCount = sampleRequests.filter(
    (item) => item.sample_status === 'delivered',
  ).length;
  const activeCount = sampleRequests.filter(
    (item) => !['delivered', 'declined', 'cancelled'].includes(item.sample_status || ''),
  ).length;

  return (
    <>
      <Head>
        <title>{getPageTitle('Sample requests')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={icon.mdiPackageVariant}
          title='Sample requests'
          main
        >
          <div className='flex flex-wrap gap-2'>
            {hasCreatePermission && (
              <Link
                href='/sample_requests/sample_requests-new'
                className='inline-flex h-10 items-center rounded-xl bg-slate-950 px-4 text-sm font-semibold text-white hover:bg-slate-800'
              >
                New sample
              </Link>
            )}
            <Link
              href='/sample_requests/sample_requests-table'
              className='inline-flex h-10 items-center rounded-xl border border-slate-200 bg-white px-4 text-sm font-semibold text-slate-700 hover:bg-slate-50'
            >
              Table view
            </Link>
          </div>
        </SectionTitleLineWithButton>

        <CardBox className='mb-6 border border-slate-200 bg-white shadow-sm'>
          <div className='grid gap-6 lg:grid-cols-[minmax(0,1fr)_360px]'>
            <div>
              <p className='text-xs font-semibold uppercase tracking-[0.22em] text-amber-700'>
                Chef evaluation queue
              </p>
              <h1 className='mt-3 text-3xl font-semibold text-slate-950'>
                Track samples from buyer request to menu decision
              </h1>
              <p className='mt-3 max-w-3xl text-sm leading-7 text-slate-600'>
                Foodservice suppliers use samples to move chefs from curiosity
                to a quote, LTO, banquet menu, or recurring PO. This queue keeps
                product, buyer, ship-to, timing, and tasting notes together.
              </p>
            </div>
            <div className='grid gap-3 sm:grid-cols-2 lg:grid-cols-1'>
              <div className='rounded-xl border border-amber-200 bg-amber-50 p-4'>
                <p className='text-xs font-semibold uppercase tracking-[0.16em] text-amber-700'>
                  Active samples
                </p>
                <p className='mt-2 text-2xl font-semibold text-slate-950'>
                  {activeCount}
                </p>
              </div>
              <div className='rounded-xl border border-emerald-200 bg-emerald-50 p-4'>
                <p className='text-xs font-semibold uppercase tracking-[0.16em] text-emerald-700'>
                  Ready for follow-up
                </p>
                <p className='mt-2 text-2xl font-semibold text-slate-950'>
                  {approvedCount + deliveredCount}
                </p>
              </div>
            </div>
          </div>

          <div className='mt-5 grid gap-3 sm:grid-cols-2 lg:grid-cols-4'>
            <div className='rounded-xl bg-slate-50 p-4'>
              <p className='text-xs font-semibold uppercase tracking-[0.16em] text-slate-400'>
                Total requests
              </p>
              <p className='mt-2 text-2xl font-semibold text-slate-950'>
                {sampleRequests.length}
              </p>
            </div>
            <div className='rounded-xl bg-amber-50 p-4'>
              <p className='text-xs font-semibold uppercase tracking-[0.16em] text-amber-700'>
                Requested
              </p>
              <p className='mt-2 text-2xl font-semibold text-slate-950'>
                {requestedCount}
              </p>
            </div>
            <div className='rounded-xl bg-emerald-50 p-4'>
              <p className='text-xs font-semibold uppercase tracking-[0.16em] text-emerald-700'>
                Approved
              </p>
              <p className='mt-2 text-2xl font-semibold text-slate-950'>
                {approvedCount}
              </p>
            </div>
            <div className='rounded-xl bg-blue-50 p-4'>
              <p className='text-xs font-semibold uppercase tracking-[0.16em] text-blue-700'>
                Delivered
              </p>
              <p className='mt-2 text-2xl font-semibold text-slate-950'>
                {deliveredCount}
              </p>
            </div>
          </div>
        </CardBox>

        {errorMessage && (
          <div className='mb-5 rounded-2xl border border-rose-200 bg-rose-50 p-4 text-sm font-semibold text-rose-800'>
            {errorMessage}
          </div>
        )}

        <div className='mb-5 flex flex-wrap gap-2'>
          {statusOptions.map((option) => (
            <button
              key={option.value}
              type='button'
              onClick={() => setSelectedStatus(option.value)}
              className={`rounded-full border px-4 py-2 text-sm font-semibold transition ${
                selectedStatus === option.value
                  ? 'border-emerald-500 bg-emerald-500 text-white'
                  : 'border-slate-200 bg-white text-slate-700 hover:bg-slate-50'
              }`}
            >
              {option.label}
            </button>
          ))}
        </div>

        <div className='grid items-start gap-6 xl:grid-cols-[minmax(0,1fr)_340px]'>
          <div className='grid gap-4 lg:grid-cols-2'>
            {isLoading && (
              <div className='col-span-full flex h-40 items-center justify-center rounded-2xl border border-slate-200 bg-white'>
                <LoadingSpinner />
              </div>
            )}

            {!isLoading &&
              filteredRequests.map((item) => (
                <Link
                  key={item.id}
                  href={`/sample_requests/sample_requests-view/?id=${item.id}`}
                  className='group block h-full overflow-hidden rounded-2xl border border-slate-200 bg-white p-5 shadow-sm transition hover:-translate-y-0.5 hover:border-amber-200 hover:shadow-md'
                >
                  <div className='flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between'>
                    <div className='min-w-0'>
                      <p className='text-xs font-semibold uppercase tracking-[0.18em] text-amber-700'>
                        {item.sample_request_number}
                      </p>
                      <h2 className='mt-2 truncate text-xl font-semibold text-slate-950'>
                        {item.product?.product_name || 'Sample product'}
                      </h2>
                      <p className='mt-1 text-sm text-slate-500'>
                        {item.product?.sku || 'No SKU'} -{' '}
                        {item.product?.pack_size || 'Pack pending'}
                      </p>
                    </div>
                    <StatusPill status={item.sample_status} />
                  </div>

                  <div className='mt-5 grid gap-3 rounded-xl bg-slate-50 p-4 text-sm text-slate-600 sm:grid-cols-2'>
                    <div>
                      <p className='text-xs uppercase tracking-[0.14em] text-slate-400'>
                        Buyer account
                      </p>
                      <p className='mt-1 font-semibold text-slate-950'>
                        {item.account?.account_name || 'Unassigned'}
                      </p>
                    </div>
                    <div>
                      <p className='text-xs uppercase tracking-[0.14em] text-slate-400'>
                        Needed by
                      </p>
                      <p className='mt-1 font-semibold text-slate-950'>
                        {formatDate(item.needed_by)}
                      </p>
                    </div>
                    <div>
                      <p className='text-xs uppercase tracking-[0.14em] text-slate-400'>
                        Ship-to
                      </p>
                      <p className='mt-1 font-semibold text-slate-950'>
                        {item.location?.location_name || 'Not selected'}
                      </p>
                    </div>
                    <div>
                      <p className='text-xs uppercase tracking-[0.14em] text-slate-400'>
                        Quantity
                      </p>
                      <p className='mt-1 font-semibold text-slate-950'>
                        {item.sample_quantity || 0} unit(s)
                      </p>
                    </div>
                  </div>

                  <p className='mt-4 line-clamp-2 text-sm leading-6 text-slate-600'>
                    {item.notes || 'No tasting notes yet.'}
                  </p>

                  <div className='mt-5 flex flex-col items-start gap-2 border-t border-slate-100 pt-4 text-sm sm:flex-row sm:items-center sm:justify-between sm:gap-3'>
                    <span className='font-semibold text-slate-500'>
                      Requested by {formatUserName(item.requested_by)}
                    </span>
                    <span className='font-bold text-emerald-700 group-hover:text-emerald-800'>
                      Review
                    </span>
                  </div>
                </Link>
              ))}

            {!isLoading && !filteredRequests.length && (
              <div className='col-span-full rounded-2xl border border-dashed border-slate-300 bg-white p-8 text-center text-sm text-slate-500'>
                No sample requests match this status.
              </div>
            )}
          </div>

          <aside className='rounded-2xl border border-slate-200 bg-slate-950 p-5 text-white shadow-sm'>
            <p className='text-xs font-semibold uppercase tracking-[0.22em] text-emerald-300'>
              Workflow
            </p>
            <h3 className='mt-3 text-2xl font-semibold'>
              Sample-to-order path
            </h3>
            <div className='mt-5 space-y-3'>
              {sampleFlow.map((step, index) => (
                <div
                  key={step}
                  className='flex items-center gap-3 rounded-xl border border-white/10 bg-white/5 p-3'
                >
                  <span className='flex h-8 w-8 items-center justify-center rounded-full bg-emerald-400 text-sm font-bold text-slate-950'>
                    {index + 1}
                  </span>
                  <span className='text-sm font-semibold text-slate-100'>
                    {step}
                  </span>
                </div>
              ))}
            </div>
            <div className='mt-5 rounded-xl border border-white/10 bg-white/5 p-4 text-sm leading-6 text-slate-300'>
              A strong sample workflow gives sales and operations one place to
              see what was requested, why it matters, and when the buyer needs a
              decision.
            </div>
          </aside>
        </div>
      </SectionMain>
    </>
  );
};

SampleRequestsListPage.getLayout = function getLayout(page: ReactElement) {
  return (
    <LayoutAuthenticated permission='READ_SAMPLE_REQUESTS'>
      {page}
    </LayoutAuthenticated>
  );
};

export default SampleRequestsListPage;
