import {LitElement, html, map, unsafeHTML, until} from './lit-all.min.js';
import {markdown} from './markdown.js';
import * as tfrpc from '/static/tfrpc.js';
import * as emojis from './emojis.js';

class BookPageElement extends LitElement {
	static get properties() {
		return {
			book: {type: Object},
			edit_review: {type: Object},
		};
	}

	add_review() {
		this.edit_review = {};
	}

	async submit_review() {
		let whoami = await tfrpc.rpc.getActiveIdentity();
		let message = {
			type: 'bookclubUpdate',
			updates: this.book.id,
			rating: this.edit_review.rating,
			ratingMax: this.edit_review.ratingMax,
			ratingType: this.edit_review.ratingType,
			review: this.edit_review.review,
			shelves: (this.edit_review.shelves ?? '')
				.split(',')
				.map((x) => x.trim())
				.filter((x) => x),
		};
		console.log(message);
		await tfrpc.rpc.appendMessage(whoami, message);
	}

	render_shelf(shelf) {
		return html` <div class="w3-tag w3-padding w3-gray">${shelf}</div> `;
	}

	change(event) {
		this.edit_review[event.srcElement.id] = event.srcElement.value;
		this.edit_review = Object.assign({}, this.edit_review);
	}

	render_edit_review() {
		let self = this;
		return html`
			<p>
				<div class="w3-row" style="box-sizing: border-box">
					<div class="w3-third w3-padding">
						<label for="rating">Rating (ie, 3)</label>
						<input id="rating" type="number" class="w3-input" @change=${this.change} value=${this.edit_review?.rating}></input>
					</div>
					<div class="w3-third w3-padding">
						<label for="rating">Max Rating (ie, 5)</label>
						<input id="ratingMax" type="number" class="w3-input" @change=${this.change} value=${this.edit_review?.ratingMax}></input>
					</div>
					<div class="w3-third w3-padding">
						<label for="rating">Rating Type (ie, ⭐)</label>
						<input id="ratingType" type="text" class="w3-input" @change=${this.change} value=${this.edit_review?.ratingType}></input>
					</div>
				</div>
				<div class="w3-padding">
					<label for="review">Review</label>
					<textarea id="review" class="w3-input" placeholder="Enter a review" @change=${this.change}>${this.edit_review?.review}</textarea>
					<label for="shelves">Shelves</label>
					<input id="shelves" type="text" class="w3-input" placeholder="want to read, currently reading, already read" @change=${this.change} value=${this.edit_review?.shelves}></input>
				</div>
				<p>
					<button class="w3-button w3-gray" @click=${this.submit_review}>Submit</button>
					<button class="w3-button w3-gray" @click=${() => (self.edit_review = undefined)}>Discard</button>
				</p>
			</p>
		`;
	}

	render_review(review) {
		let self = this;
		let rating = review.content.rating ?? 0;
		if (typeof rating === 'string' && rating.startsWith('[')) {
			try {
				rating = JSON.parse(rating)[0];
			} catch {}
		}
		let shelves = review.content.shelve ?? '';
		shelves = shelves.startsWith('[') ? JSON.parse(shelves) : shelves;
		shelves = shelves instanceof Array ? shelves : [shelves];
		return html`
			<div class="w3-card-4" style="clear: both">
				<header class="w3-gray w3-container">
					<h2>
						<a href=${'/~core/ssb/#' + encodeURIComponent(review.id)}>%</a>
						<a href=${'/~core/ssb/#' + encodeURIComponent(review.author)}
							>${review.author_name ?? review.author}</a
						>
					</h2>
				</header>
				${rating !== undefined && rating !== ''
					? html` <div class="w3-content">
							<progress
								value=${rating}
								max=${review.content.ratingMax ?? 5}
							></progress>
							${rating} / ${review.content.ratingMax}
							${until(
								emojis.from_name(review.content.ratingType),
								review.content.ratingType
							)}
						</div>`
					: undefined}
				<div class="w3-content">${review.content.review}</div>
				<footer>
					${map(
						shelves.filter((x) => x),
						self.render_shelf
					)}
				</footer>
			</div>
		`;
	}

	render() {
		return html`
			<link rel="stylesheet" href="w3.css"></link>
			<div class="w3-margin">
				<a class="w3-button w3-gray" target="_top" href="#">Back</a>
				<a class="w3-button w3-gray" target="_top" href=${'#!' + encodeURIComponent(this.book.id)}>Edit</a>
				<header class="w3-container">
					<h1>${markdown(this.book.title)}</h1>
				</header>
				<div class="w3-container">
					${
						this.book.image
							? html`
									<img
										src="/${this.book.image?.link}/view"
										class="w3-left w3-margin-right w3-margin-bottom"
										style="max-height: 2in; max-width: 2in"
									/>
								`
							: undefined
					}
					<h2>${map(this.book.authors, (author) => markdown(author))}</h2>
					<p>${markdown(this.book.description)}</p>
					${
						this.edit_review !== undefined
							? this.render_edit_review()
							: html`<p>
									<button class="w3-button w3-gray" @click=${this.add_review}>
										Add Review
									</button>
								</p>`
					}
					${map(this.book.reviews, this.render_review.bind(this))}
				</div>
			</div>`;
	}
}

customElements.define('bc-book-page', BookPageElement);
