import { Avatar, Box, Button, Typography, styled } from '@mui/material'
import { useMutation, useQuery } from 'react-query'
import { toast } from 'react-toastify'
import { useImmer } from 'use-immer'
import { PageContent } from '../PageContent'
import PageHeader from '../PageHeader'
import useConfirm from '../PopupConfirm/useConfirm'
import Spinner from '../Spinner'
import UserProfileRelation from './UserProfileRelation'
import {
  defaultFilterObj,
  fetchApplicationUsers,
  fetchProfiles,
  removeUserApplicationProfile,
} from './services'

import { ValidateAccess } from '../../permissions'
import { Permission } from '../../shared-state'
import ActionButton from '../ActionButton'
import FilterButton from '../FilterComponents/FilterButton'
import SearchBar from '../FilterComponents/SearchBar'
import { DialogButton, DrawerButton } from '../ModalButtons'
import Table from '../Tables/BasicTable/Table'
import DepartmentFilter from './DepartmentFilter'
interface ApplicationProfileProps {
  application:
    | 'exams'
    | 'square'
    | 'payments'
    | 'enroll_x'
    | 'hostels'
    | 'hrms'
    | 'commute_x'
    | 'admin'
    | 'dashboards'
  title: string
  permissions?: {
    add: string
    edit: string
    view: string
    delete: string
  }
}

function ApplicationProfile({
  application,
  title,
  permissions,
}: ApplicationProfileProps) {
  const { isConfirmed } = useConfirm()
  const [state, setState] = useImmer(defaultFilterObj)

  const { data, isLoading, refetch } = useQuery(
    [
      'application-users',
      ...Object.keys(state.filters).map((key) => state.filters[key]),
    ],
    () => fetchApplicationUsers({ application, ...state.filters }),
  )

  const { data: profiles, isLoading: profilesLoading } = useQuery(
    'profiles',
    () => fetchProfiles({ application }),
  )

  const { mutate, isLoading: removingUserProfile } = useMutation(
    removeUserApplicationProfile,
    {
      onSuccess: () => {
        refetch()
        toast.success('User profile removed from application')
      },
    },
  )

  const handleRemove = async (data) => {
    const confirmed = await isConfirmed(
      'Are you sure you want to remove the user profile?',
    )
    if (!confirmed) return
    mutate({ userId: data.id, application: application })
  }

  const columns = [
    {
      title: 'User',
      key: 'user',
      dataIndex: 'user',
      render: (_, row) => <UserComponent userData={row} />,
    },

    {
      title: 'Assigned Profiles',
      key: '',
      dataIndex: '',
      render: (_, row) => <ProfileList profiles={row.profiles} />,
    },
    {
      title: 'Actions',
      key: 'actions',
      dataIndex: 'actions',
      render: (_, row) => (
        <Box sx={{ display: 'flex', gap: '10px' }}>
          <ValidateAccess
            accessKey={
              permissions
                ? Permission[permissions.edit]
                : Permission.CAN_DASHBOARD_VIEW
            }
          >
            <DialogButton
              title={'Edit user profile'}
              anchor={({ open }) => (
                <Button
                  variant="text"
                  onClick={open}
                  sx={{ padding: '0px', margin: '0px' }}
                >
                  Edit
                </Button>
              )}
              content={({ close }) => (
                <UserProfileRelation
                  data={row}
                  close={close}
                  application={application}
                  profiles={profiles?.profiles}
                />
              )}
            />
          </ValidateAccess>

          <ValidateAccess
            accessKey={
              permissions
                ? Permission[permissions.delete]
                : Permission.CAN_DASHBOARD_VIEW
            }
          >
            <Button
              variant="text"
              onClick={() => handleRemove(row)}
              sx={{ padding: '0px', margin: '0px' }}
            >
              Remove
            </Button>
          </ValidateAccess>
        </Box>
      ),
    },
  ]
  const handleLimitChange = (value: number) => {
    setState((s) => {
      s.filters.limit = value
      s.filters.offset = 0
    })
  }

  const handlePagination = (value: number) => {
    setState((s) => {
      s.filters.offset = value * s.filters.limit - s.filters.limit
    })
  }

  if (profilesLoading) return <Spinner />
  return (
    <>
      <PageHeader
        title={title}
        actions={[
          <ValidateAccess
            key={1}
            accessKey={
              permissions
                ? Permission[permissions.add]
                : Permission.CAN_DASHBOARD_VIEW
            }
          >
            <DialogButton
              title={'Add User Profile Relation'}
              anchor={({ open }) => (
                <ActionButton
                  onClick={open}
                  className="test"
                  sx={{ inset: 'auto' }}
                >
                  Add User Profile Relation
                </ActionButton>
              )}
              content={({ close }) => (
                <UserProfileRelation
                  data={null}
                  close={close}
                  application={application}
                  profiles={profiles?.profiles}
                />
              )}
            />
          </ValidateAccess>,
        ]}
      />

      <PageContent sx={{ marginTop: '25px' }}>
        <StyledTableContainer>
          <Box
            sx={{
              display: 'flex',
              gap: '10px',
              alignItems: 'center',
              marginBottom: '10px',
            }}
          >
            <Box>
              <SearchBar
                onSearch={(value) =>
                  setState((s) => {
                    s.filters.search = value
                  })
                }
                textFieldProps={{
                  className: 'test2',
                  placeholder: 'Search by Name',
                  title: 'Search by Name',
                  sx: { width: '300px' },
                  size: 'medium',
                }}
              />
            </Box>
            <DrawerButton
              anchor={({ open }) => (
                <FilterButton
                  onClick={open}
                  filtersApplied={state.filtersApplied}
                />
              )}
              content={({ close }) => (
                <DepartmentFilter
                  close={close}
                  setAppliedFilters={setState}
                  appliedFilters={state}
                />
              )}
              title="People Filters"
            />
          </Box>
          <Table
            columns={columns}
            dataSource={data?.result ?? []}
            loading={isLoading || removingUserProfile}
            pagination={{
              limit: state.filters.limit,
              onChangeLimit: handleLimitChange,
              onChange: handlePagination,
              totalCount: data?.count,
              page: state.filters.offset / state.filters.limit,
            }}
          />
        </StyledTableContainer>
      </PageContent>
    </>
  )
}
export default ApplicationProfile

export const UserComponent = ({ userData }) => {
  return (
    <>
      <Box
        sx={{
          width: '100%',
          display: 'flex',
          gap: '10px',
          alignItems: 'center',
          justifyContent: 'flex-start',
        }}
      >
        <Avatar alt={userData?.fullName} />
        <Typography variant="subtitle1">{userData?.fullName}</Typography>
      </Box>
    </>
  )
}

export const ProfileList = ({ profiles = [] }) => {
  return (
    <>
      <Box
        sx={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'flex-start',
        }}
      >
        {profiles.map((profile, index) => (
          <Typography key={index}>{profile.name}</Typography>
        ))}
      </Box>
    </>
  )
}
export const StyledTableContainer = styled(Box)(({ theme }) => ({
  width: '70%',
  margin: 'auto',
  '& .MuiTableHead-root': {
    border: '1px solid white',
    borderBottom: theme.borders.grayLight,
    borderWidth: '2px',

    backgroundColor: 'white',
    '& th': {
      textAlign: 'left',
      padding: '5px',
    },
    '& .MuiBox-root': {
      color: '#121212b3',
      fontSize: '164x',
    },
  },
  '& tbody': {
    border: '1px solid white',
    borderBottom: theme.borders.grayLight,
    borderWidth: '2px',
    '& tr': {
      border: '1px solid white',
    },
  },
  '& td': {
    textAlign: 'center',
    border: '1px solid white',
    padding: '15px 0px',
  },
}))

export const StyledDropDownContainer = styled(Box)(() => ({
  width: '200px',
  '& .MuiTypography-root': {
    display: 'none',
  },
  '& .MuiInputBase-root': {
    backgroundColor: '#f5f6f8',
  },
}))
