import React from 'react';
import ImageField from '../ImageField';
import ListActionsPopover from '../ListActionsPopover';
import { useAppSelector } from '../../stores/hooks';
import dataFormatter from '../../helpers/dataFormatter';
import { Pagination } from '../Pagination';
import { saveFile } from '../../helpers/fileSaver';
import LoadingSpinner from "../LoadingSpinner";
import Link from 'next/link';

import { hasPermission } from "../../helpers/userPermissions";


type Props = {
  products: any[];
  loading: boolean;
  onDelete: (id: string) => void;
  currentPage: number;
  numPages: number;
  onPageChange: (page: number) => void;
};

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

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

const temperatureClasses = (value) => {
  if (value === 'refrigerated') {
    return 'border-sky-200 bg-sky-50 text-sky-800 dark:border-sky-800 dark:bg-sky-950 dark:text-sky-100';
  }

  if (value === 'frozen') {
    return 'border-cyan-200 bg-cyan-50 text-cyan-800 dark:border-cyan-800 dark:bg-cyan-950 dark:text-cyan-100';
  }

  return 'border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-800 dark:bg-emerald-950 dark:text-emerald-100';
};

const statusClasses = (value) => {
  if (value === 'active') {
    return 'border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-800 dark:bg-emerald-950 dark:text-emerald-100';
  }

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

  if (value === 'out_of_stock') {
    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 fallbackProductImages = [
  'https://images.unsplash.com/photo-1452195100486-9cc805987862?auto=format&fit=crop&w=900&q=80',
  'https://images.unsplash.com/photo-1501443762994-82bd5dace89a?auto=format&fit=crop&w=900&q=80',
  'https://images.unsplash.com/photo-1544025162-d76694265947?auto=format&fit=crop&w=900&q=80',
  'https://images.unsplash.com/photo-1486297678162-eb2a19b0a32d?auto=format&fit=crop&w=900&q=80',
  'https://images.unsplash.com/photo-1512621776951-a57141f2eefd?auto=format&fit=crop&w=900&q=80',
  'https://images.unsplash.com/photo-1542838132-92c53300491e?auto=format&fit=crop&w=900&q=80',
];

const CardProducts = ({
  products,
  loading,
  onDelete,
  currentPage,
  numPages,
  onPageChange,
}: Props) => {
    const currentUser = useAppSelector((state) => state.auth.currentUser);
    const hasUpdatePermission = hasPermission(currentUser, 'UPDATE_PRODUCTS')
    

  return (
    <div className='p-4 md:p-6'>
      {loading && <LoadingSpinner />}
      <ul
        role='list'
        className='grid grid-cols-1 gap-5 lg:grid-cols-2 2xl:grid-cols-3'
      >
        {!loading && products.map((item, index) => {
          const category = dataFormatter.product_categoriesOneListFormatter(item.category) || 'Uncategorized';
          const specSheetLinks = dataFormatter.filesFormatter(item.spec_sheet);
          const sampleEligible = item.is_sample_eligible === true || item.is_sample_eligible === 'true';
          const hasProductImage = Array.isArray(item.images) ? item.images.length > 0 : Boolean(item.images);
          const fallbackImage = fallbackProductImages[index % fallbackProductImages.length];

          return (
          <li
            key={item.id}
            className='overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm transition hover:-translate-y-0.5 hover:border-emerald-200 hover:shadow-md dark:border-dark-700 dark:bg-dark-900'
          >
            <div className='relative border-b border-slate-200 bg-slate-100 dark:border-dark-700 dark:bg-dark-800'>
              <Link href={`/products/products-view/?id=${item.id}`} className='block'>
                {hasProductImage ? (
                  <ImageField
                    name={'Product image'}
                    image={item.images}
                    className='h-48 w-full overflow-hidden'
                    imageClassName='h-full w-full bg-white object-cover'
                  />
                ) : (
                  <div
                    role='img'
                    aria-label={item.product_name}
                    className='h-48 w-full bg-cover bg-center bg-white'
                    style={{ backgroundImage: `url(${fallbackImage})` }}
                  />
                )}
              </Link>
              <div className='absolute left-4 top-4 rounded-full border border-white/70 bg-white/95 px-3 py-1 text-xs font-bold uppercase tracking-[0.16em] text-slate-700 shadow-sm dark:border-dark-700 dark:bg-dark-900/95 dark:text-slate-200'>
                {item.sku}
              </div>
              <div className='absolute right-3 top-3'>
                <ListActionsPopover
                  onDelete={onDelete}
                  itemId={item.id}
                  pathEdit={`/products/products-edit/?id=${item.id}`}
                  pathView={`/products/products-view/?id=${item.id}`}
                  hasUpdatePermission={hasUpdatePermission}
                />
              </div>
            </div>

            <div className='p-5'>
              <div className='mb-3 flex flex-wrap items-center gap-2'>
                <span className={`rounded-full border px-3 py-1 text-xs font-semibold capitalize ${statusClasses(item.product_status)}`}>
                  {readableValue(item.product_status)}
                </span>
                <span className={`rounded-full border px-3 py-1 text-xs font-semibold capitalize ${temperatureClasses(item.temperature_zone)}`}>
                  {readableValue(item.temperature_zone)}
                </span>
                {sampleEligible && (
                  <span className='rounded-full border border-amber-200 bg-amber-50 px-3 py-1 text-xs font-semibold text-amber-800 dark:border-amber-800 dark:bg-amber-950 dark:text-amber-100'>
                    Sample-ready
                  </span>
                )}
              </div>

              <div className='mb-2 text-xs font-bold uppercase tracking-[0.18em] text-emerald-700 dark:text-emerald-300'>
                {category}
              </div>
              <Link href={`/products/products-view/?id=${item.id}`} className='block'>
                <h2 className='text-xl font-semibold leading-7 text-slate-950 hover:text-emerald-700 dark:text-white dark:hover:text-emerald-300'>
                  {item.product_name}
                </h2>
              </Link>
              <div className='mt-1 text-sm font-medium text-slate-500 dark:text-slate-400'>
                {item.brand}
              </div>
              <p className='mt-3 min-h-[3.5rem] text-sm leading-6 text-slate-600 line-clamp-3 dark:text-slate-300'>
                {item.short_description || item.long_description || 'No product description yet.'}
              </p>

              <div className='mt-5 grid grid-cols-2 gap-3 text-sm'>
                <div className='rounded-xl border border-slate-200 bg-slate-50 p-3 dark:border-dark-700 dark:bg-dark-800'>
                  <div className='text-xs font-bold uppercase tracking-[0.14em] text-slate-500 dark:text-slate-400'>Pack</div>
                  <div className='mt-1 font-semibold text-slate-950 dark:text-white'>{item.pack_size || 'Not set'}</div>
                </div>
                <div className='rounded-xl border border-slate-200 bg-slate-50 p-3 dark:border-dark-700 dark:bg-dark-800'>
                  <div className='text-xs font-bold uppercase tracking-[0.14em] text-slate-500 dark:text-slate-400'>MOQ</div>
                  <div className='mt-1 font-semibold text-slate-950 dark:text-white'>{item.moq_cases || 0} cases</div>
                </div>
                <div className='rounded-xl border border-slate-200 bg-slate-50 p-3 dark:border-dark-700 dark:bg-dark-800'>
                  <div className='text-xs font-bold uppercase tracking-[0.14em] text-slate-500 dark:text-slate-400'>Units</div>
                  <div className='mt-1 font-semibold text-slate-950 dark:text-white'>{item.units_per_case || 0} / case</div>
                </div>
                <div className='rounded-xl border border-slate-200 bg-slate-50 p-3 dark:border-dark-700 dark:bg-dark-800'>
                  <div className='text-xs font-bold uppercase tracking-[0.14em] text-slate-500 dark:text-slate-400'>Case wt.</div>
                  <div className='mt-1 font-semibold text-slate-950 dark:text-white'>{item.case_weight_lbs || 0} lbs</div>
                </div>
              </div>

              <div className='mt-5 space-y-3 border-t border-slate-200 pt-4 text-sm dark:border-dark-700'>
                <div>
                  <div className='mb-1 font-semibold text-slate-700 dark:text-slate-200'>Allergens</div>
                  <div className='text-slate-600 dark:text-slate-300'>{item.allergens || 'None listed'}</div>
                </div>
                <div>
                  <div className='mb-1 font-semibold text-slate-700 dark:text-slate-200'>Certifications</div>
                  <div className='text-slate-600 dark:text-slate-300'>{item.certifications || 'None listed'}</div>
                </div>
              </div>

              <div className='mt-5 flex flex-wrap items-center gap-3'>
                <Link
                  href={`/products/products-view/?id=${item.id}`}
                  className='rounded-lg bg-slate-950 px-4 py-2 text-sm font-semibold text-white transition hover:bg-emerald-700 dark:bg-white dark:text-slate-950 dark:hover:bg-emerald-100'
                >
                  Open SKU
                </Link>
                {hasUpdatePermission && (
                  <Link
                    href={`/products/products-edit/?id=${item.id}`}
                    className='rounded-lg border border-slate-300 px-4 py-2 text-sm font-semibold text-slate-700 transition hover:border-emerald-300 hover:text-emerald-700 dark:border-dark-700 dark:text-slate-200 dark:hover:border-emerald-700 dark:hover:text-emerald-300'
                  >
                    Edit
                  </Link>
                )}
                {specSheetLinks.length > 0 && (
                  <button
                    type='button'
                    className='text-sm font-semibold text-slate-600 underline-offset-4 hover:text-emerald-700 hover:underline dark:text-slate-300 dark:hover:text-emerald-300'
                    onClick={(e) => saveFile(e, specSheetLinks[0].publicUrl, specSheetLinks[0].name)}
                  >
                    Spec sheet
                  </button>
                )}
              </div>
            </div>
          </li>
        )})}
        {!loading && products.length === 0 && (
          <div className='col-span-full flex min-h-64 items-center justify-center rounded-2xl border border-dashed border-slate-300 bg-white p-8 text-center dark:border-dark-700 dark:bg-dark-900'>
            <div>
              <div className='text-lg font-semibold text-slate-950 dark:text-white'>No catalog items yet</div>
              <p className='mt-2 max-w-md text-sm text-slate-500 dark:text-slate-400'>
                Add SKUs or import a CSV to start building the distributor catalog buyers will reorder from.
              </p>
            </div>
          </div>
        )}
      </ul>
      <div className='flex items-center justify-center my-6'>
        <Pagination
          currentPage={currentPage}
          numPages={numPages}
          setCurrentPage={onPageChange}
        />
      </div>
    </div>
  );
};

export default CardProducts;
