import React from 'react';
import axios from 'axios';
import { Button, Form, Header, Message, Segment, Table } from 'semantic-ui-react';

// Durable staff drafts use native administrator cookies, never contact PINs.
export default class StaffDrafts extends React.Component {
  state = { items: [], page: 1, pages: 1, state: 'draft', draft: null, editing: false,
    message: '', contact_id: '', contact_email: '', contact_name: '',
    conversation_id: '', department: '', busy: false, error: '', notice: '' };
  mounted = false;
  requestKey = '';
  txt = text => this.props.appState.config?.text?.[text] ?? text;
  identity = props => `${props.appState.session?.nonce || ''}:${props.appState.config?.siteAdmin ? 1 : 0}`;
  dirty = () => this.state.editing && this.state.message !== (this.state.draft?.message || '');
  beforeUnload = event => { if (this.dirty()) { event.preventDefault(); event.returnValue = ''; } };
  componentDidMount() {
    this.mounted = true;
    window.addEventListener('beforeunload', this.beforeUnload);
    if (this.props.appState.staffDraftConversation || this.props.appState.staffDraftMessage) this.newDraft();
    else this.load();
  }
  componentDidUpdate(previous) {
    if (this.identity(previous) !== this.identity(this.props)) {
      this.controller?.abort();
      this.setState({ draft: null, items: [], editing: false, message: '', busy: false,
        error: this.txt('Your session changed. Reopen the draft with your current administrator session.') });
    }
  }
  componentWillUnmount() {
    this.mounted = false;
    this.controller?.abort();
    window.removeEventListener('beforeunload', this.beforeUnload);
  }
  request = async (path = '', data) => {
    const identity = this.identity(this.props);
    if (!this.props.appState.config?.siteAdmin) throw new Error(this.txt('Administrator access is required.'));
    this.controller?.abort();
    this.controller = new AbortController();
    const response = await axios({ url: this.props.callURL + path, method: data ? 'POST' : 'GET',
      data, signal: this.controller.signal, withCredentials: true,
      headers: { 'X-WP-Nonce': this.props.appState.session?.nonce, 'Content-Type': 'application/json' } });
    if (!this.mounted || identity !== this.identity(this.props)) throw new axios.Cancel('Session changed');
    return response.data;
  };
  run = async operation => {
    if (this.state.busy) return;
    this.setState({ busy: true, error: '', notice: '' });
    try { await operation(); }
    catch (error) {
      if (this.mounted && !axios.isCancel(error)) this.setState({ error: error.response?.data?.message || error.message || this.txt('Could not complete the draft operation.') });
    } finally { if (this.mounted) this.setState({ busy: false }); }
  };
  leave = () => !this.dirty() || window.confirm(this.txt('Discard unsaved draft edits?'));
  load = (page = 1, state = this.state.state) => {
    if (!this.leave()) return;
    this.run(async () => {
      const result = await this.request(`?page=${page}&state=${state}`);
      this.setState({ ...result, state, editing: false, draft: null, message: '' });
    });
  };
  newDraft = () => {
    if (!this.leave()) return;
    this.requestKey = window.crypto.randomUUID ? window.crypto.randomUUID() : Array.from(window.crypto.getRandomValues(new Uint8Array(24)), n => n.toString(16).padStart(2, '0')).join('');
    this.setState({ editing: true, draft: null, message: this.props.appState.staffDraftMessage || '',
      conversation_id: this.props.appState.staffDraftConversation || '', contact_id: this.props.appState.staffDraftRecipient || '',
      contact_email: '', contact_name: '', department: '', error: '', notice: '' });
    this.props.appStateUpdate({ staffDraftMessage: '', staffDraftConversation: 0, staffDraftRecipient: 0 });
  };
  open = id => {
    if (!this.leave()) return;
    this.run(async () => { const draft = await this.request(`/${id}`); this.setState({ draft, editing: true, message: draft.message }); });
  };
  save = () => this.run(async () => {
    const { draft, message, contact_id, contact_email, contact_name, conversation_id, department } = this.state;
    const body = draft ? { message, expected_revision: draft.revision } : {
      message, request_key: this.requestKey, contact_id: Number(contact_id || 0),
      contact_email, contact_name, conversation_id: Number(conversation_id || 0), department: Number(department || 0) };
    const saved = await this.request(draft ? `/${draft.id}` : '', body);
    this.setState({ draft: saved, message: saved.message, notice: this.txt('Draft saved. No notification was sent.') });
  });
  send = () => {
    const { draft } = this.state;
    if (!draft || this.dirty() || !window.confirm(this.txt('Send this saved draft and notify the conversation recipients?'))) return;
    this.run(async () => {
      const sent = await this.request(`/${draft.id}/send`, { expected_revision: draft.revision });
      this.setState({ draft: sent, message: sent.message, notice: this.txt('Draft published. Review the notification receipt below.') });
    });
  };
  render() {
    const { busy, editing, draft, error, notice, items, page, pages } = this.state;
    const txt = this.txt;
    if (!this.props.appState.config?.siteAdmin) return <Message negative>{txt('Administrator access is required.')}</Message>;
    const sent = draft?.state === 'sent';
    return <Segment inverted={this.props.appState.config.darkMode} style={{ margin: '1em', overflow: 'auto', maxHeight: '90vh' }}>
      <Header as="h2" inverted={this.props.appState.config.darkMode}>{txt('Conversation Drafts')}</Header>
      <p>{txt('Private staff drafts send no message or notification until you explicitly send them. Pending conversations retain their current status while a draft is edited.')}</p>
      <Button type="button" disabled={busy} onClick={() => { if (this.leave()) this.props.appStateUpdate({ screen: this.props.appState.staffDraftReturn || 'ticket' }); }}>{txt('Back to support')}</Button>
      <Button type="button" disabled={busy} onClick={() => this.load(1, 'draft')}>{txt('Draft list')}</Button>
      <Button type="button" disabled={busy} onClick={() => this.load(1, 'sent')}>{txt('Sent receipts')}</Button>
      <Button type="button" disabled={busy} onClick={this.newDraft}>{txt('New draft')}</Button>
      {error && <Message negative role="alert">{error}</Message>}
      {notice && <Message positive role="status">{notice}</Message>}
      {editing ? <Form inverted={this.props.appState.config.darkMode} onSubmit={event => { event.preventDefault(); this.save(); }}>
        {draft ? <p>{draft.contact?.name} — {draft.contact?.contact}<br/>{txt('Existing conversation ID (optional)')}: {draft.tid || '—'}</p> : <>
          {[['contact_id', 'Recipient contact ID'], ['contact_email', 'Recipient email (when no contact ID)'], ['contact_name', 'Recipient name'], ['conversation_id', 'Existing conversation ID (optional)'], ['department', 'Department ID (optional)']].map(([key, label]) => <Form.Input key={key} id={`vws-staff-draft-${key}`} label={txt(label)} value={this.state[key]} disabled={busy} onChange={(_, { value }) => this.setState({ [key]: value })}/>)}
        </>}
        <Form.TextArea id="vws-staff-draft-message" label={txt('Draft message')} rows={12} value={this.state.message} disabled={busy || sent} onChange={(_, { value }) => this.setState({ message: value })}/>
        {!sent && <><Button primary type="submit" loading={busy} disabled={busy || !this.state.message.trim()}>{txt('Save draft')}</Button>
          <Button type="button" onClick={this.send} disabled={busy || !draft || this.dirty()}>{txt('Send saved draft')}</Button>
          <p>{txt('Save changes before sending. Send uses the saved revision shown when this page opened.')}</p>
          {draft && <Button type="button" disabled={busy} onClick={() => this.open(draft.id)}>{txt('Reload saved draft')}</Button>}</>}
        {sent && <Message>{txt('This draft was sent. Its receipt is retained; sending it again does not create another message or notification.')}<br/>{txt('Notification receipt')}: {draft.notification_state}</Message>}
      </Form> : <>
        <Table inverted={this.props.appState.config.darkMode} unstackable><Table.Header><Table.Row><Table.HeaderCell>{txt('Recipient')}</Table.HeaderCell><Table.HeaderCell>{txt('Message')}</Table.HeaderCell></Table.Row></Table.Header>
          <Table.Body>{items.map(item => <Table.Row key={item.id}><Table.Cell><Button basic disabled={busy} onClick={() => this.open(item.id)}>{item.contact?.name || item.id}</Button><br/>{item.contact?.contact}</Table.Cell><Table.Cell style={{ overflowWrap: 'anywhere' }}>{item.message.slice(0, 180)}</Table.Cell></Table.Row>)}</Table.Body></Table>
        {!items.length && <p>{txt('No drafts found.')}</p>}
        <Button disabled={busy || page <= 1} onClick={() => this.load(page - 1)}>{txt('Previous page')}</Button>
        <span>{page} / {pages}</span>
        <Button disabled={busy || page >= pages} onClick={() => this.load(page + 1)}>{txt('Next page')}</Button>
      </>}
    </Segment>;
  }
}
