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 CardBoxComponentEmpty from '../CardBoxComponentEmpty';
import { useAppSelector } from '../../stores/hooks';
import { hasPermission } from '../../helpers/userPermissions';

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

const CardProperties = ({
  properties,
  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_PROPERTIES');
  const cardRadius = corners !== 'rounded-full' ? corners : 'rounded-3xl';

  return (
    <>
      <div className='space-y-4 p-4'>
        {loading && (
          <LoadingSpinner
            label='Loading properties'
            detail='Preparing the current portfolio snapshot and live inventory.'
          />
        )}

        {!loading &&
          properties.map((item) => {
            const location = [item.city, item.country].filter(Boolean).join(', ') || item.address || 'Location not set';
            const unitsCount = Array.isArray(item.units) ? item.units.length : 0;
            const unitTypesCount = Array.isArray(item.unit_types) ? item.unit_types.length : 0;
            const amenitiesCount = Array.isArray(item.amenities) ? item.amenities.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={`/properties/properties-view/?id=${item.id}`}
                          className='text-lg font-semibold leading-6 text-gray-900 dark:text-white'
                        >
                          {item.name || item.code || 'Untitled property'}
                        </Link>
                        <span
                          className={`inline-flex rounded-full px-2.5 py-1 text-xs font-semibold ${
                            item.is_active
                              ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-300'
                              : 'bg-gray-100 text-gray-700 dark:bg-slate-700 dark:text-slate-200'
                          }`}
                        >
                          {item.is_active ? 'Active' : 'Inactive'}
                        </span>
                      </div>
                      <p className='mt-1 text-sm text-gray-500 dark:text-dark-600'>{location}</p>
                      {item.description && (
                        <p className='mt-3 line-clamp-2 text-sm text-gray-600 dark:text-slate-300'>
                          {item.description}
                        </p>
                      )}
                    </div>

                    <div className='self-start'>
                      <ListActionsPopover
                        onDelete={onDelete}
                        itemId={item.id}
                        pathEdit={`/properties/properties-edit/?id=${item.id}`}
                        pathView={`/properties/properties-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'>Code</p>
                      <p className='mt-1 text-sm font-medium'>{item.code || '—'}</p>
                    </div>
                    <div>
                      <p className='text-xs uppercase tracking-wide text-gray-500'>Timezone</p>
                      <p className='mt-1 text-sm font-medium'>{item.timezone || '—'}</p>
                    </div>
                    <div>
                      <p className='text-xs uppercase tracking-wide text-gray-500'>Units</p>
                      <p className='mt-1 text-sm font-medium'>{unitsCount}</p>
                    </div>
                    <div>
                      <p className='text-xs uppercase tracking-wide text-gray-500'>Unit types / amenities</p>
                      <p className='mt-1 text-sm font-medium'>
                        {unitTypesCount} / {amenitiesCount}
                      </p>
                    </div>
                  </div>
                </div>
              </CardBox>
            );
          })}

        {!loading && properties.length === 0 && (
          <CardBoxComponentEmpty
            title='No properties match this view'
            description='Try clearing filters or add a property to bring the portfolio into view.'
          />
        )}
      </div>

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

export default CardProperties
