import React from 'react';

import PropTypes from 'prop-types';

import axios from 'axios';
import qs from "qs"; //post to php w/o file_get_contents('php://input');

import _ from 'lodash';

import { Button, Checkbox, Form, Input, Message, Label, Icon, Table, Dropdown, Menu, Loader, Modal, Header} from 'semantic-ui-react'


export default class List extends React.Component {
	
static propTypes = {	
appState: PropTypes.object.isRequired,
appStateUpdate: PropTypes.func.isRequired,
callURL: PropTypes.string.isRequired,
}

constructor(props) {
	super(props);
	
	this.devMode = props.appState.devMode;
	
	this.axiosConfig = {
		withCredentials: true,
		credentials: 'include',
		timeout: 20000,
		headers: {
			'Accept': 'application/json',
			'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
			'X-WP-Nonce' : props.appState.session.nonce, 
		}
	}
	
	this.serverCalled = false;
	
	this.tickets = [];
	this.selection = [];
	
	this.state =
			{
			representative: false,
			selection: [],
			action: '',
			page: 0,
			perPage: props.appState.config?.perPage || 10,
			total: 0,
			loaded: false,
			loading: true,
			error: '',
			timedOut: false,
			lastRequest: 'load',
			searchModalShow: false,
			searchInput: '',
			};
		
}

getErrorInfo(error) {
	const timedOut =
		error?.code === 'ECONNABORTED' ||
		String(error?.message || '').toLowerCase().includes('timeout');

	return {
		timedOut,
		message: timedOut
			? this.txt('Request timed out. Please retry.')
			: error?.response?.data?.info || error?.message || this.txt('Could not load conversations.'),
	};
}

retryLoad = () => {
	this.serverUpdate();
}

serverUpdate=(extra = {}) => {
	
	//ticket update interval
	const { props, state } = this;
	const self = this;

	if (props.appState.filterContact != state.filterContact)
	{
		//this.setState({filterContact: props.appState.filterContact});
		state.filterContact = props.appState.filterContact;
		state.filterContactName = props.appState.filterContactName;
	}

	const params = qs.stringify({
		contact_id: props.appState.contact_id,  confirm: props.appState.confirm, rep: props.appState.rep, page: state.page, perPage: state.perPage,
		filter_status: state.filterStatus,
		filter_contact: state.filterContact,
		filter_department: state.filterDepartment,
		filter_search: state.filterSearch,
		filter_tag: state.filterTag,
		filter_older: state.filterOlder,
		sort: state.filterSort,
		 ...extra} );
	
	if (this.devMode) console.log('VideoWhisper/Screens/List serverUpdate', props.callURL, params);

	this.setState({
		loading: true,
		error: '',
		timedOut: false,
		lastRequest: extra.action ? 'action' : 'load',
	});
	
axios.post(props.callURL, params, this.axiosConfig)
	.then(function (response) {
		self.serverProcess(response);
	})
	.catch(this.serverError.bind(this));
	
	this.serverCalled = true;
	this.setState({loading: true});
}

 serverProcess(response) {
	 
			if (this.devMode) console.log('VideoWhisper/Screens/List serverProcess:', response, this.state);
			
			const data = response.data;

			if (!data) {
				this.setState({
					loading: false,
					error: this.txt('Server returned no data. Please retry.'),
					timedOut: false,
				});
				return;
			}
		
			if (data.tickets)
			{
				this.tickets = data.tickets ;
				this.setState({loaded: true, loading: false, error: '', timedOut: false, page: data.page, perPage: data.perPage, total: data.total, new: data.new, pending: data.pending, info: data.info, representative: data.representative});
			}
			
			if (data.info && !data.tickets) this.setState({info: data.info, loading: false, error: '', timedOut: false});
		}
		
serverError(error) {	
			console.log('VideoWhisper/Screens/List serverError:', error);
			const errorInfo = this.getErrorInfo(error);
			this.setState({
				loading: false,
				error: errorInfo.message,
				timedOut: errorInfo.timedOut,
			});
		}


	txt = (text) => {
	//handle text translations from appState.config
	const { props } = this;
	if (!props.appState.config) return text;
	if (!props.appState.config.text) return text;
	
	if (text in props.appState.config.text) return props.appState.config.text[text];
	return text;
	}

sortTickets(column, direction)
{
	if (!column) return;
	
	this.tickets = ( direction === 'ascending' ? _.sortBy(this.tickets, [column]) : _.sortBy(this.tickets, [column]).reverse() );
	
	if (this.devMode) console.log('screens/List sortTickets', column, direction);

}

 handleSort = clickedColumn => () => {
	 	  
	  	const { column, direction } = this.state;

		 if (this.devMode)console.log('screens/List clickedColumn', clickedColumn, column, direction);
		 
 	  //first update data, the state to render
	  
	  //different column
	  if (column !== clickedColumn) {
		this.sortTickets(clickedColumn, 'descending' );
		this.setState({column: clickedColumn, direction: 'descending'}, () => this.sortTickets() );
		return
	  }
	  
	  //same column
	  if (column === clickedColumn) 
	  {	
		  this.sortTickets(column, direction === 'ascending' ? 'descending' : 'ascending' );
		  this.setState( {direction: direction === 'ascending' ? 'descending' : 'ascending' } );
	  }
	
  }
	
		
	
 ticketClick = ticket => (event, data) => 
	  {
		if (this.devMode) console.log('screens/List ticketClick',  ticket, data, event);
	  
	 // window.open(ticket.url, '_blank');
	 this.props.appStateUpdate({openTicket: ticket.id, openCode: ticket.code, openRep: ticket.rep}, {screen:true});
  	}

openNew = ticket => (event, data) => 
	  {
		if (this.devMode) console.log('screens/List openNew',  ticket, data, event);
	  
	  window.open(ticket.url, '_blank');
	 //this.props.appStateUpdate({openTicket: ticket.id, openCode: ticket.code, openRep: ticket.rep}, {screen:true});
  	}
	  
formUpdate = newState => (event) =>
{
	if (this.devMode) console.log('screens/List formUpdate',  newState, event);
	this.setState(newState, () => this.serverUpdate() );
}
  	
onFilter = (event, data) => {

	const name = data.name;
	const value = data.value;

	this.setState(
		{
		  [name]: value,
		},
		() => this.serverUpdate()
	  );

	  if (this.devMode) console.log('screens/List onFilter', name, value, data);
}

onSearchButton = () => {
	this.setState({ searchModalShow: true, searchInput: this.state.filterSearch || '' });
}

searchModalClose = () => {
	this.setState({ searchModalShow: false });
}

onSearchChange = (event, data) => {
	this.setState({ searchInput: data.value });
}

onSearchSubmit = (event) => {
	if (event) event.preventDefault();

	const value = this.state.searchInput.trim();
	if (value && value.length < 4) return; //4 chars min to search

	this.setState({ filterSearch: value, searchModalShow: false }, () => this.serverUpdate());
}

clearSearch = () => {
	this.setState({ filterSearch: '', searchInput: '', searchModalShow: false }, () => this.serverUpdate());
}

filterByTag = tag => () => {
	this.setState({ filterTag: tag }, () => this.serverUpdate());

	if (this.devMode) console.log('screens/List filterByTag', tag);
}

clearTagFilter = () => {
	this.setState({ filterTag: '' }, () => this.serverUpdate());
}

	  onCheckbox = (event, data) => {
		  
		  const checked = data.checked;
		  const value = data.value;
		  const name = data.name;
	  		 
		 if (checked) if ( !this.selection.includes(value) ) this.selection.push(value); //add
		 if (!checked) if ( this.selection.includes(value) ) this.selection = this.selection.filter(item => item !== value); //remove
		 
		  this.setState({ selection: this.selection }); // save in state
		  
		  if (this.devMode) console.log('VideoWhisper/screens/list onCheckbox', name, value, checked, this.selection, event);

	  }
	  
	  onAction = (event, data) => {
		  const value = data.value;
		  
		  if (this.devMode) console.log('VideoWhisper/screens/list onAction', value, data, event);
		  
		  if (value != 'cancel') this.serverUpdate( { action: value, selection: this.selection } );
		  
		  this.selection = [];
		  this.setState({ action: '', selection: this.selection });
	  }
	  
	  toggleSelection = (event, data) => {
		  if (this.selection.length) this.selection = [];
		  else this.selection = this.tickets.map( (ticket) => { return ticket.id} ) ;
		  
		  this.setState({ selection: this.selection }); // save in state
	  }
	  
		render ()
			{
				const {state, props, txt} = this;
				const { column, direction } = this.state;
				
				//access:load
				if (!this.serverCalled) this.serverUpdate();
		
				var content = [];
				var form = [];
				
				var ticketsList = [];
 
 			 if (state.loaded && this.tickets) 
				{
					ticketsList = this.tickets.map((ticket) => {

						//show tags (from tag:value, tag as key and timestamp as value in php array, as Labels with Date/Time from unix timestamp tooltip)
						let tagCode = '';
						if (ticket.tags) {
							tagCode = Object.keys(ticket.tags).map((tag) => {
								return <Label as='a' size="tiny" key={tag} data-tooltip={txt('Filter by tag') + ': ' + tag + ' (' + new Date(ticket.tags[tag] * 1000).toLocaleString() + ')'} onClick={this.filterByTag(tag)}>{tag}</Label>;
							});
						}
						
							return (
							<Table.Row key={'ticket' + ticket.id}>	
								<Table.Cell collapsing><Checkbox name={'t' + ticket.id} value={ticket.id} checked={state.selection.includes(ticket.id) ? true : false} onChange={this.onCheckbox} aria-label={txt('Select conversation') + ' ' + ticket.id} /></Table.Cell>
								<Table.Cell><Icon name='box' />{ticket.department_name}<br/><Icon name='users' /><small>{ticket.contact_list}</small><br/>{tagCode}</Table.Cell>
								<Table.Cell onClick={this.ticketClick(ticket)} data-tooltip={txt('View Conversation')}><Icon name={ticket.first_rep?'user md':'user'} />{ticket.first_contact + ': ' + ticket.first_message}<br />{ticket.first_id !== ticket.last_id ? (
    <div>
      <Icon name={ticket.last_rep ? 'user md' : 'user'} />
      {ticket.last_contact}: {ticket.last_message}
    </div>
  ) : ''}</Table.Cell>
								<Table.Cell onClick={this.openNew(ticket)} data-tooltip={txt('Open URL')}><Icon name='time' />{ticket.updated_label}<br/><Icon name='comment' />{ticket.message_count} <Icon name='calendar plus' /><small>{ticket.created_label}</small></Table.Cell>
								<Table.Cell><Icon name={ticket.status_icon} />{ticket.status_label}<br/><small><Icon name="user"/>{ticket.message_count_client} <Icon name="user md"/>{ticket.message_count_rep}</small></Table.Cell>
							</Table.Row>
						  );
					})
				}else ticketsList = (
					<Table.Row key="No_Tickets">
						<Table.Cell colSpan="5" warning>
							{state.loading ? txt('Loading conversations...') : (state.loaded ? txt('No conversations, yet.') : txt('Could not load conversations.'))}
							{state.loading ? (
								<Loader active inline size="small" />
							) : (
								<div key="ReloadSection">
									<Button
										type="button"
										color="grey"
										size="small"
										onClick={this.retryLoad}
										inverted={props.appState.config.darkMode}>
										{txt('Reload')} <Icon name="redo" />
									</Button>
									{state.error ? <div>{state.error}</div> : ''}
								</div>
							)}
						</Table.Cell>
					</Table.Row>
				  );


			   content.push(
					   <Table celled selectable striped sortable key="Tickets" className={props.appState.config.className} inverted={props.appState.config.darkMode} size='small'>
					   <Table.Header>
						 <Table.Row>
				 <Table.HeaderCell collapsing scope="col"><Button key="toggleAll" size="tiny" icon compact inverted={props.appState.config.darkMode} onClick={this.toggleSelection} aria-label={txt('Toggle all conversations')}><Icon name='check square' aria-hidden="true" /></Button></Table.HeaderCell>
				   <Table.HeaderCell scope="col" sorted={column === 'first_contact' ? direction : null } onClick={this.handleSort('first_contact')}><Icon name='users' aria-hidden="true" />{txt('Group')}</Table.HeaderCell>
				   <Table.HeaderCell scope="col"><Icon name='comments' aria-hidden="true" />{txt('Contents')}</Table.HeaderCell>
				   <Table.HeaderCell scope="col" sorted={column === 'updated' ? direction : null } onClick={this.handleSort('updated')}><Icon name='time' aria-hidden="true" />{txt('Updates')}</Table.HeaderCell>
			   <Table.HeaderCell scope="col" sorted={column === 'status' ? direction : null } onClick={this.handleSort('status')}><Icon name='eye' aria-hidden="true" />{txt('Status')}</Table.HeaderCell>               
						 </Table.Row>
					   </Table.Header>
					   <Table.Body>
						   {ticketsList}
					   </Table.Body>
					   </Table>
			   ) 
			   if (this.selection.length)
			   {
				   
				   var actionOptions = [
					 { key: 'cancel', text: txt('Nevermind'), value: 'cancel', icon: 'window close' },  
					 { key: 'closed', text: txt('Close'), value: 'closed', icon: 'lock' },
				   ];
				   
				   if (state.representative) actionOptions = [ ...actionOptions,
					   { key: 'open', text: txt('Open'), value: 'open', icon: 'star'},
					   { key: 'public', text: txt('Make Public'), value: 'public', icon: 'bullhorn'},
					   { key: 'locked', text: txt('Lock'), value: 'locked', icon: 'ban' },
					   { key: 'delete', text: txt('Delete'), value: 'delete', icon: 'trash' },
				   ];
				
				  form.push( <Form.Group key='ActionMenu'><Label><Icon name='arrow up' />{this.selection.length}</Label><Dropdown className="v-select" name='action' text={txt('Select Action')} options={actionOptions} selection value={state.action} onChange={this.onAction} /></Form.Group>);

			   }

			   if (state.loading) form.push(<Message key="loading"><Icon loading name="spinner" />{txt('Loading conversations...')}</Message>);
			   if (state.error) form.push(
				<Message negative key="requestError">
					<Message.Header>{state.timedOut ? txt('Connection timed out') : txt('Could not load conversations')}</Message.Header>
					<p>{state.error}</p>
					<Button type="button" size="small" onClick={this.retryLoad}>
						<Icon name="redo" /> {txt('Retry')}
					</Button>
				</Message>
			   );
				if (state.info) form.push( <Message key="info">{state.info}</Message> );
				
				if (state.total) form.push( <Label key="countersPage" data-tooltip={txt('Listed')}><Icon name='comments' /> {state.page * state.perPage}..{ state.page * state.perPage + this.tickets.length } / {state.total}</Label> );

				if (state.page) {
					form.push(  <Button key="previousPage" size="tiny" compact inverted={props.appState.config.darkMode} onClick={this.formUpdate({page: state.page - 1 })} data-tooltip={txt('Previous Page')}>
						<Icon name='left arrow' /> <Icon name='file text' /> {state.page}
					  </Button> );
				  }
			
				 form.push( <Label key="currentPage" data-tooltip= { txt('Page') + ' ' + (state.page + 1)}><Icon name='file text'/> {state.page + 1}</Label> );

				var endset = (state.page + 1) * state.perPage;
				if (endset < state.total) form.push(  <Button key="nextPage" size="tiny" compact inverted={props.appState.config.darkMode} onClick={this.formUpdate({page: state.page + 1})} data-tooltip={txt('Next Page')}>
					<Icon name='file text' /> {state.page + 2} <Icon name='right arrow' />
				  </Button> );

				  if (state.new) form.push(  <Button key="newConversations" color="orange" size="tiny" compact inverted={props.appState.config.darkMode} onClick={() => this.setState(
					{  'filterStatus': 0, 'filterDepartment': 0, 'filterOlder': 0 }, () => this.serverUpdate()
				  )} data-tooltip={txt('New Conversations')}>
				  <Icon name='star' /> {state.new}
				</Button> );

				if (state.pending && props.appState.config.registerConversation) form.push(  <Button key="pendingConversations"  size="tiny" compact inverted={props.appState.config.darkMode} onClick={() => this.setState(
					{  'filterStatus': 5, 'filterDepartment': 0, 'filterOlder': 0 }, () => this.serverUpdate()
				)} data-tooltip={txt('Pending Conversations')}>
				<Icon name='hourglass' /> {state.pending}
				</Button> );

				if (state.total) form.push(  <Button key="allConversations" size="tiny" compact inverted={props.appState.config.darkMode} onClick={() => this.setState(
					{  'filterStatus': -1, 'filterDepartment': 0, 'filterSort': 'status', 'filterOlder': 0 }, () => this.serverUpdate()
				)} data-tooltip={txt('All Conversations')}>
				<Icon name='list' />
				</Button> );


let filterStatusOptions = [
	{ key: 'all', text: txt('All'), value: -1, icon: 'list' },
	{ key: 'new', text: txt('New'), value: 0, icon: 'star' },
	{ key: 'pending', text: txt('Pending'), value: 5, icon: 'hourglass start' },
	{ key: 'answered', text: txt('Answered'), value: 1, icon: 'check' },
	{ key: 'pending-answered', text: txt('Pending Answered'), value: 6, icon: 'hourglass half' },
	{ key: 'closed', text: txt('Closed'), value: 2, icon: 'lock' },
	{ key: 'public', text: txt('Public'), value: 3, icon: 'announcement' },
	{ key: 'locked', text: txt('Locked'), value: 4, icon: 'ban' },
];

let filterSortOptions = [
	{ key: 'status', text: txt('Status'), value: 'status', icon: 'eye' },
	{ key: 'created', text: txt('Created'), value: 'created', icon: 'calendar plus' },
	{ key: 'updated', text: txt('Updated'), value: 'updated', icon: 'time' },
];	

let filterOlderOptions = [
	{ key: 'any', text: txt('Any'), value: 0 },
	{ key: '3', text: txt('3 Days'), value: 3 },
	{ key: '7', text: txt('1 Week'), value: 7 },
	{ key: '14', text: txt('2 Weeks'), value: 14 },
	{ key: '30', text: txt('1 Month'), value: 30 },
	{ key: '60', text: txt('2 Months'), value: 60 },
	{ key: '90', text: txt('3 Months'), value: 90 },
];
form.push( <span key='filters' size="tiny">
	<Button
		key="searchButton"
		size="small"
		compact
		icon
		type="button"
		color={state.filterSearch ? 'olive' : 'grey'}
		data-tooltip={txt('Search Conversations')}
		aria-label={txt('Search Conversations')}
		onClick={this.onSearchButton}
		inverted={props.appState.config.darkMode}>
		<Icon name="search" />
	</Button>

	<Dropdown className="v-select" name='filterStatus' placeholder={txt('Filter by Status')} aria-label={txt('Filter by Status')} selection
	options={filterStatusOptions} value={state.filterStatus} onChange={this.onFilter} />

<Dropdown className="v-select" name='filterSort' placeholder={txt('Sort by')} aria-label={txt('Sort by')} selection
 	options={filterSortOptions} value={state.filterSort} onChange={this.onFilter} />

<Dropdown className="v-select" name='filterDepartment' placeholder={txt('Department')} aria-label={txt('Filter by Department')} selection
 	options={[{ key: 'all', text: txt('All'), value: 0 }, ...props.appState.config.departments]} value={state.filterDepartment} onChange={this.onFilter} />

<Dropdown className="v-select" name='filterOlder' placeholder={txt('Older than')} aria-label={txt('Filter older than')} selection
 	options={filterOlderOptions} value={state.filterOlder} onChange={this.onFilter} />

	{state.filterContact ? 
	 <Button
	 size="small"
	 key={"filterContact" } 
	 compact
	 icon
	 type="button"
	 color="olive"
	 data-tooltip={txt("Remove Contact Filter")}
	 onClick={
	   () =>
		 {
		 props.appStateUpdate({filterContact: 0});
		 this.setState({filterContact: 0}, () => this.serverUpdate() );
		 }
	 }
	 inverted={props.appState.config.darkMode}
	 >
	 {state.filterContactName}
	 <Icon name="remove" />
	 </Button>
	: ''}

	{state.filterSearch ?
	 <Button
	 size="small"
	 key={"filterSearch"}
	 compact
	 icon
	 type="button"
	 color="olive"
	 data-tooltip={txt("Remove Search Filter")}
	 onClick={this.clearSearch}
	 inverted={props.appState.config.darkMode}
	 >
	 <Icon name="search" /> {state.filterSearch}
	 <Icon name="remove" />
	 </Button>
	: ''}

	{state.filterTag ?
	 <Button
	 size="small"
	 key={"filterTag"}
	 compact
	 icon
	 type="button"
	 color="olive"
	 data-tooltip={txt("Remove Tag Filter")}
	 onClick={this.clearTagFilter}
	 inverted={props.appState.config.darkMode}
	 >
	 <Icon name="tag" /> {state.filterTag}
	 <Icon name="remove" />
	 </Button>
	: ''}

	</span>);

	let searchModalCode = (
		<Modal key="searchModal" closeIcon
			open={state.searchModalShow}
			onClose={this.searchModalClose}
			size='tiny' basic={props.appState.config.darkMode}>
			<Header icon='search' content={txt('Search Conversations')} />
			<Modal.Content>
				<Form onSubmit={this.onSearchSubmit}>
					<Form.Field>
						<label>{txt('Search by contact name, email or conversation tag')}</label>
						<Input
							name="searchInput"
							icon="search"
							placeholder={txt('Type at least 4 characters...')}
							value={state.searchInput}
							onChange={this.onSearchChange}
							autoFocus
						/>
					</Form.Field>
					{state.searchInput && state.searchInput.trim().length < 4 ? (
						<Message size="small">{txt('Type at least 4 characters to search.')}</Message>
					) : ''}
					<Button type="submit" disabled={state.searchInput.trim().length > 0 && state.searchInput.trim().length < 4} primary>
						<Icon name="search" /> {txt('Search')}
					</Button>
					{state.filterSearch ? (
						<Button type="button" basic onClick={this.clearSearch}>
							<Icon name="remove" /> {txt('Clear')}
						</Button>
					) : ''}
				</Form>
			</Modal.Content>
		</Modal>
	);

				return (
					<div key='list' className="layoutList" style={{ backgroundColor: props.appState.config.backgroundColor }}>
						<Form className="layContent" key='content' style={{ backgroundColor: props.appState.config.backgroundColor }}>
						{content}
						</Form>
						<Form className="layInputs" key='form' onSubmit={this.onSubmit} autoComplete="off" style={{ backgroundColor: props.appState.config.backgroundColor }}>
							{form}
						</Form>
						{searchModalCode}
					</div>
				)
				
			}
		}
