import axios from 'axios';
import Head from 'next/head';
import React, { ReactElement, useState } from 'react';
import { uniqueId } from 'lodash';
import CardBoxModal from '../../components/CardBoxModal';
import DragDropFilePicker from '../../components/DragDropFilePicker';
import TableUsers from '../../components/Users/TableUsers';
import { getPageTitle } from '../../config';
import { hasPermission } from '../../helpers/userPermissions';
import LayoutAuthenticated from '../../layouts/Authenticated';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { setRefetch, uploadCsv } from '../../stores/users/usersSlice';

function Panel({
  children,
  className = '',
}: {
  children: React.ReactNode;
  className?: string;
}) {
  return (
    <section
      className={`rounded-none border border-[#19192d]/10 bg-white ${className}`}
    >
      {children}
    </section>
  );
}

function ActionButton({
  children,
  href,
  onClick,
  variant = 'primary',
}: {
  children: React.ReactNode;
  href?: string;
  onClick?: () => void;
  variant?: 'primary' | 'secondary';
}) {
  const className =
    variant === 'primary'
      ? 'rounded-none bg-[#147568] px-4 py-2 text-sm font-semibold text-white'
      : 'rounded-none border border-[#19192d]/10 bg-white px-4 py-2 text-sm font-semibold text-[#19192d]';

  if (href) {
    return (
      <a href={href} className={className}>
        {children}
      </a>
    );
  }

  return (
    <button type='button' className={className} onClick={onClick}>
      {children}
    </button>
  );
}

const UsersTablesPage = () => {
  const [filterItems, setFilterItems] = useState([]);
  const [csvFile, setCsvFile] = useState<File | null>(null);
  const [isModalActive, setIsModalActive] = useState(false);

  const { currentUser } = useAppSelector((state) => state.auth);
  const dispatch = useAppDispatch();

  const [filters] = useState([
    { label: 'First Name', title: 'firstName' },
    { label: 'Last Name', title: 'lastName' },
    { label: 'Phone Number', title: 'phoneNumber' },
    { label: 'E-Mail', title: 'email' },
    { label: 'App Role', title: 'app_role' },
    { label: 'Custom Permissions', title: 'custom_permissions' },
  ]);

  const hasCreatePermission =
    currentUser && hasPermission(currentUser, 'CREATE_USERS');

  const addFilter = () => {
    const newItem = {
      id: uniqueId(),
      fields: {
        filterValue: '',
        filterValueFrom: '',
        filterValueTo: '',
        selectedField: filters[0].title,
      },
    };
    setFilterItems([...filterItems, newItem]);
  };

  const getUsersCSV = async () => {
    const response = await axios({
      url: '/users?filetype=csv',
      method: 'GET',
      responseType: 'blob',
    });
    const type = String(response.headers['content-type'] || 'text/csv');
    const blob = new Blob([response.data], { type });
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = 'usersCSV.csv';
    link.click();
  };

  const onModalConfirm = async () => {
    if (!csvFile) {
      return;
    }

    await dispatch(uploadCsv(csvFile));
    dispatch(setRefetch(true));
    setCsvFile(null);
    setIsModalActive(false);
  };

  const onModalCancel = () => {
    setCsvFile(null);
    setIsModalActive(false);
  };

  return (
    <>
      <Head>
        <title>{getPageTitle('Users')}</title>
      </Head>

      <main className='mx-auto max-w-7xl px-6 py-6'>
        <div className='mb-4 rounded-none bg-[#19192d] p-7 text-white'>
          <div className='flex items-center gap-3 text-[#147568]'>
            <span className='text-lg'>●</span>
            <span className='text-xs font-semibold uppercase tracking-[0.22em]'>
              Team access
            </span>
          </div>
          <h1 className='mt-3 text-xl font-semibold'>Users</h1>
          <p className='mt-2 max-w-2xl text-sm leading-6 text-[#fffdf9]'>
            Manage workspace members, roles, and export or import user records.
          </p>
        </div>

        <Panel className='mb-4 p-6'>
          <div className='flex flex-wrap items-center gap-3'>
            {hasCreatePermission && (
              <ActionButton href='/users/users-new'>Add user</ActionButton>
            )}
            <ActionButton variant='secondary' onClick={addFilter}>
              Filter
            </ActionButton>
            <ActionButton variant='secondary' onClick={getUsersCSV}>
              Download CSV
            </ActionButton>
            {hasCreatePermission && (
              <ActionButton
                variant='secondary'
                onClick={() => setIsModalActive(true)}
              >
                Upload CSV
              </ActionButton>
            )}
            <div className='ms-auto' id='delete-rows-button'></div>
          </div>
        </Panel>

        <Panel className='overflow-hidden'>
          <TableUsers
            filterItems={filterItems}
            setFilterItems={setFilterItems}
            filters={filters}
            showGrid={false}
          />
        </Panel>
      </main>

      <CardBoxModal
        title='Upload CSV'
        buttonColor='info'
        buttonLabel='Confirm'
        isActive={isModalActive}
        onConfirm={onModalConfirm}
        onCancel={onModalCancel}
      >
        <DragDropFilePicker
          file={csvFile}
          setFile={setCsvFile}
          formats='.csv'
        />
      </CardBoxModal>
    </>
  );
};

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

export default UsersTablesPage;
