import './style.css'

import Autocomplete from '@mui/material/Autocomplete'
import CircularProgress from '@mui/material/CircularProgress'
import Paper from '@mui/material/Paper'
import Table from '@mui/material/Table'
import TableBody from '@mui/material/TableBody'
import TableCell from '@mui/material/TableCell'
import TableContainer from '@mui/material/TableContainer'
import TableHead from '@mui/material/TableHead'
import TablePagination from '@mui/material/TablePagination'
import TableRow from '@mui/material/TableRow'
import TextField from '@mui/material/TextField'
import axios from 'axios'
import _get from 'lodash/get'
import _identity from 'lodash/identity'
import React, { useEffect, useState } from 'react'

import { getOrders } from '../../api'
import { getCookieByName } from '../../utils'
import { LoginModal } from '../loginModal'
import MyTicketsRow from './row'
import tableConfig from './tableConfig'

interface MyTicketsTypes {
  handleDetailsInfo: (id: string | number) => void;
  onGetOrdersSuccess: (res: any) => void;
  onGetOrdersError: (err: any) => void;
  logo?: string;
  theme?: 'light' | 'dark';
  selectEventsLabel?: string;
  openLoginModal?: () => void;
  hideDetailsButton?: boolean;
  customNoOrderContent?: React.ReactNode;
  columns?: IColumnData[];
}

interface EventFilter {
  event_name: string;
  url_name: string;
}

export const MyTicketsContainer = ({
  handleDetailsInfo = _identity,
  onGetOrdersSuccess = _identity,
  onGetOrdersError = _identity,
  theme = 'dark',
  selectEventsLabel = 'Events',
  logo,
  hideDetailsButton = false,
  columns = [],
  openLoginModal,
  customNoOrderContent = null,
}: MyTicketsTypes) => {
  const [data, setData] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [limit, setLimit] = useState(10)
  const [filter, setFilter] = useState('')

  const isWindowDefined = typeof window !== 'undefined'
  const [isLogged, setIsLogged] = useState(
    isWindowDefined ? !!getCookieByName('X-TF-ECOMMERCE') : false
  )
  const [showModalLogin, setShowModalLogin] = useState(false)
  const [userExpired, setUserExpired] = useState(false)

  //just once
  useEffect(() => {
    fetchData(1, limit, filter)
  }, [isLogged])

  const fetchData = async (page: number, limit: number, eventSlug: string) => {
    try {
      setLoading(true)
      const response = await getOrders(page, limit, eventSlug)
      onGetOrdersSuccess(response)

      const data = _get(response, 'data.attributes')
      data.page -= 1

      setData(data)
    } catch (error) {
      if (axios.isAxiosError(error)) {
        if (_get(error, 'response.data.error') === 'invalid_token') {
          if (isWindowDefined) {
            window.localStorage.removeItem('user_data')
            setUserExpired(true)
            setShowModalLogin(true)
          }
        }
      }
      onGetOrdersError(error)
    } finally {
      setLoading(false)
    }
  }

  const handleChangePage = (_event: any, newPage: number) => {
    fetchData(newPage + 1, limit, filter)
  }

  const handleChangeRowsPerPage = (event: React.ChangeEvent<HTMLInputElement>) => {
    fetchData(1, +event.target.value, filter)
    setLimit(+event.target.value)
  }

  const onChange = (
    _event: React.SyntheticEvent<Element, Event>,
    eventFilter: EventFilter | null
  ) => {
    fetchData(1, limit, eventFilter?.url_name || '')
    setFilter(eventFilter?.url_name || '')
  }

  const noOrderContent = customNoOrderContent || (<div className="no_orders_section">
    <div className="nodata_title">
      You have no current ticket orders on this account
    </div>
    <div className="nodata_subtitle">
      Discover your next nite out <a href="/events">here</a>.
    </div>
  </div>)

  return (
    <div className={`my-ticket ${theme}`}>
      <>
        {showModalLogin || !isLogged ? (
          openLoginModal ? (
            openLoginModal()
          ) : (
            <LoginModal
              onClose={() => {
                setShowModalLogin(false)
              }}
              onLogin={() => {
                setShowModalLogin(false)
                setUserExpired(false)
                setIsLogged(true)
              }}
              userExpired={userExpired}
              logo={logo}
              showForgotPasswordButton
            />
          )
        ) : null}
      </>
      {data?.orders?.length ? (
        <>
          <h2>My Ticket Orders</h2>
          <Autocomplete
            disablePortal
            id="combo-box-demo"
            getOptionLabel={(option: EventFilter) => option.event_name}
            onChange={onChange}
            options={data.purchased_events}
            sx={{ width: 300 }}
            renderInput={params => <TextField {...params} label={selectEventsLabel} />}
          />
          {loading ? (
            <div className="loading">
              <CircularProgress />
            </div>
          ) : (
            <>
              <TableContainer component={Paper} className="my-ticket-table">
                <Table aria-label="collapsible table">
                  <TableHead>
                    <TableRow>
                      {tableConfig(columns).header.map(
                        (column: string, index: number) => (
                          <TableCell key={index}>{column}</TableCell>
                        )
                      )}
                      {!hideDetailsButton && <TableCell />}
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {data.orders?.map((row: RowItems) => (
                      <MyTicketsRow
                        key={row.id}
                        row={row}
                        handleDetailsInfo={handleDetailsInfo}
                        columns={columns}
                        hideDetailsButton={hideDetailsButton}
                      />
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
              <TablePagination
                rowsPerPageOptions={[10, 25, 100]}
                component="div"
                count={data.total_count}
                rowsPerPage={limit}
                page={data.page}
                onPageChange={handleChangePage}
                onRowsPerPageChange={handleChangeRowsPerPage}
              />
            </>
          )}
        </>
      ) : (
        !loading && (
          <>
            <h2>My Ticket Orders</h2>
            {noOrderContent}
          </>
        )
      )}
      <>
        {showModalLogin && (
          <LoginModal
            onClose={() => {
              setShowModalLogin(false)
            }}
            onLogin={() => {
              setShowModalLogin(false)
              setUserExpired(false)
              setIsLogged(true)
            }}
            userExpired={userExpired}
            showForgotPasswordButton
          />
        )}
      </>
    </div>
  )
}
