import React from 'react';
import Link from 'next/link';
import CardBox from '../CardBox';
import ListActionsPopover from '../ListActionsPopover';
import { Pagination } from '../Pagination';
import LoadingSpinner from '../LoadingSpinner';
import { useAppSelector } from '../../stores/hooks';
import dataFormatter from '../../helpers/dataFormatter';
import { hasPermission } from '../../helpers/userPermissions';

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

const statusTone = (status?: string) => {
  switch (status) {
    case 'available':
      return 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-300';
    case 'occupied':
    case 'reserved':
      return 'bg-blue-100 text-blue-700 dark:bg-blue-500/10 dark:text-blue-300';
    case 'maintenance':
    case 'out_of_service':
      return 'bg-rose-100 text-rose-700 dark:bg-rose-500/10 dark:text-rose-300';
    default:
      return 'bg-gray-100 text-gray-700 dark:bg-slate-700 dark:text-slate-200';
  }
};

const CardUnits = ({ units, loading, onDelete, currentPage, numPages, onPageChange }: Props) => {
  const currentUser = useAppSelector((state) => state.auth.currentUser);
  const corners = useAppSelector((state) => state.style.corners);
  const bgColor = useAppSelector((state) => state.style.cardsColor);
  const hasUpdatePermission = hasPermission(currentUser, 'UPDATE_UNITS');
  const cardRadius = corners !== 'rounded-full' ? corners : 'rounded-3xl';

  return (
    <>
      <div className='p-4 space-y-4'>
        {loading && <LoadingSpinner />}

        {!loading &&
          units.map((item) => {
            const property = dataFormatter.propertiesOneListFormatter(item.property) || 'Unassigned property';
            const unitType = dataFormatter.unit_typesOneListFormatter(item.unit_type) || 'No unit type';
            const availabilityCount = Array.isArray(item.availability_blocks)
              ? item.availability_blocks.length
              : 0;

            return (
              <CardBox key={item.id} className='shadow-none'>
                <div
                  className={`border border-gray-200 dark:border-dark-700 ${cardRadius} ${bgColor} p-5`}
                >
                  <div className='flex flex-col gap-4 md:flex-row md:items-start'>
                    <div className='min-w-0 flex-1'>
                      <div className='flex flex-wrap items-center gap-3'>
                        <Link
                          href={`/units/units-view/?id=${item.id}`}
                          className='text-lg font-semibold leading-6 text-gray-900 dark:text-white'
                        >
                          {item.unit_number || 'Untitled unit'}
                        </Link>
                        <span
                          className={`inline-flex rounded-full px-2.5 py-1 text-xs font-semibold capitalize ${statusTone(
                            item.status,
                          )}`}
                        >
                          {item.status || 'unknown'}
                        </span>
                      </div>
                      <p className='mt-1 text-sm text-gray-500 dark:text-dark-600'>
                        {property} • {unitType}
                      </p>
                      {item.notes && (
                        <p className='mt-3 line-clamp-2 text-sm text-gray-600 dark:text-slate-300'>
                          {item.notes}
                        </p>
                      )}
                    </div>

                    <div className='self-start'>
                      <ListActionsPopover
                        onDelete={onDelete}
                        itemId={item.id}
                        pathEdit={`/units/units-edit/?id=${item.id}`}
                        pathView={`/units/units-view/?id=${item.id}`}
                        hasUpdatePermission={hasUpdatePermission}
                      />
                    </div>
                  </div>

                  <div className='mt-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-4'>
                    <div>
                      <p className='text-xs uppercase tracking-wide text-gray-500'>Floor</p>
                      <p className='mt-1 text-sm font-medium'>{item.floor || '—'}</p>
                    </div>
                    <div>
                      <p className='text-xs uppercase tracking-wide text-gray-500'>Max occupancy</p>
                      <p className='mt-1 text-sm font-medium'>
                        {item.max_occupancy_override ?? 'Default'}
                      </p>
                    </div>
                    <div>
                      <p className='text-xs uppercase tracking-wide text-gray-500'>Availability blocks</p>
                      <p className='mt-1 text-sm font-medium'>{availabilityCount}</p>
                    </div>
                    <div>
                      <p className='text-xs uppercase tracking-wide text-gray-500'>Type</p>
                      <p className='mt-1 text-sm font-medium'>{unitType}</p>
                    </div>
                  </div>
                </div>
              </CardBox>
            );
          })}

        {!loading && units.length === 0 && (
          <div className='flex h-40 items-center justify-center'>
            <p>No data to display</p>
          </div>
        )}
      </div>

      <div className='my-6 flex items-center justify-center'>
        <Pagination currentPage={currentPage} numPages={numPages} setCurrentPage={onPageChange} />
      </div>
    </>
  );
};

export default CardUnits
