from flask import (
    Blueprint, render_template, redirect,
    url_for, request, flash
)
from flask_login import login_required, current_user
from app import db
from .models import (
    Listing, SwapBatch, Offer,
    Ownership, OwnershipTransfer,
    PriceSubmission, UserRating
)
from .forms import (
    ListingForm, SwapBatchForm, OfferForm,
    OwnershipForm, TransferForm, TransferApproveForm,
    SubmissionForm
)

exchange_bp = Blueprint(
    'exchange', __name__,
    url_prefix='/exchange',
    template_folder='templates'
)

# ── Listings ─────────────────────────────────────────────────────────────────

@exchange_bp.route('/listings')
@login_required
def list_listings():
    # TODO: fetch listings where current_user is actor
    return render_template('listing_list.html')

@exchange_bp.route('/listings/new', methods=['GET','POST'])
@login_required
def new_listing():
    form = ListingForm()
    # TODO: populate form.plant_id, form.owner_actor_id, form.swap_batch_id
    if form.validate_on_submit():
        # TODO: create and commit Listing
        flash('Listing created', 'success')
        return redirect(url_for('exchange.list_listings'))
    return render_template('listing_form.html', form=form)

@exchange_bp.route('/listings/<int:listing_id>')
@login_required
def listing_detail(listing_id):
    # TODO: load Listing + avg price badge + offers + auction info
    return render_template('listing_detail.html')

@exchange_bp.route('/listings/<int:listing_id>/edit', methods=['GET','POST'])
@login_required
def edit_listing(listing_id):
    form = ListingForm()
    # TODO: load into form on GET, save on POST
    return render_template('listing_form.html', form=form)

@exchange_bp.route('/listings/<int:listing_id>/close', methods=['POST'])
@login_required
def close_listing(listing_id):
    # TODO: mark inactive or end auction
    flash('Listing closed', 'info')
    return redirect(url_for('exchange.listing_detail', listing_id=listing_id))


# ── Offers ───────────────────────────────────────────────────────────────────

@exchange_bp.route('/listings/<int:listing_id>/offers')
@login_required
def list_offers(listing_id):
    # TODO: fetch and display offers
    return render_template('offer_list.html')

@exchange_bp.route('/listings/<int:listing_id>/offers/new', methods=['GET','POST'])
@login_required
def new_offer(listing_id):
    form = OfferForm()
    if form.validate_on_submit():
        # TODO: save Offer
        flash('Offer submitted', 'success')
        return redirect(url_for('exchange.list_offers', listing_id=listing_id))
    return render_template('offer_form.html', form=form)

@exchange_bp.route('/listings/<int:listing_id>/offers/<int:offer_id>/respond', methods=['POST'])
@login_required
def respond_offer(listing_id, offer_id):
    # TODO: accept/reject
    flash('Offer updated', 'success')
    return redirect(url_for('exchange.list_offers', listing_id=listing_id))


# ── Ownership Snapshots ──────────────────────────────────────────────────────

@exchange_bp.route('/ownership/new', methods=['GET','POST'])
@login_required
def new_ownership():
    form = OwnershipForm()
    if form.validate_on_submit():
        # TODO: record Ownership
        flash('Ownership recorded', 'success')
        return redirect(url_for('exchange.list_listings'))
    return render_template('ownership_form.html', form=form)

@exchange_bp.route('/ownership/<int:listing_id>/history')
@login_required
def ownership_history(listing_id):
    # TODO: show history
    return render_template('ownership_history.html')


# ── Transfers & Loans ─────────────────────────────────────────────────────────

@exchange_bp.route('/transfers')
@login_required
def list_transfers():
    # TODO: show pending + past transfers
    return render_template('transfer_list.html')

@exchange_bp.route('/transfers/new', methods=['GET','POST'])
@login_required
def new_transfer():
    form = TransferForm()
    if form.validate_on_submit():
        # TODO: create OwnershipTransfer
        flash('Transfer requested', 'success')
        return redirect(url_for('exchange.list_transfers'))
    return render_template('transfer_form.html', form=form)

@exchange_bp.route('/transfers/<int:transfer_id>/approve', methods=['POST'])
@login_required
def approve_transfer(transfer_id):
    form = TransferApproveForm()
    if form.validate_on_submit():
        # TODO: update status & record decided_at
        flash('Transfer decision recorded', 'success')
    return redirect(url_for('exchange.list_transfers'))


# ── Price Submissions ────────────────────────────────────────────────────────

@exchange_bp.route('/submissions/new', methods=['GET','POST'])
@login_required
def new_submission():
    form = SubmissionForm(request.args if request.method=='GET' else None)
    if form.validate_on_submit():
        # TODO: create PriceSubmission
        flash('Price submitted', 'success')
        return redirect(url_for('exchange.list_submissions'))
    return render_template('submission_form.html', form=form)

@exchange_bp.route('/submissions')
@login_required
def list_submissions():
    # TODO: list/filter by taxon
    return render_template('submission_list.html')


# ── Swap Batches ──────────────────────────────────────────────────────────────

@exchange_bp.route('/swaps')
@login_required
def list_swaps():
    return render_template('swap_list.html')

@exchange_bp.route('/swaps/new', methods=['GET','POST'])
@login_required
def new_swap():
    form = SwapBatchForm()
    if form.validate_on_submit():
        # TODO: create SwapBatch
        flash('Swap batch created', 'success')
        return redirect(url_for('exchange.list_swaps'))
    return render_template('swap_form.html', form=form)

@exchange_bp.route('/swaps/<int:swap_id>')
@login_required
def swap_detail(swap_id):
    # TODO: list linked listings
    return render_template('swap_detail.html')
