"use client";

import { DocumentIcon, TrashIcon } from "@heroicons/react/24/outline";
import { Bill, BillingLocation } from "../lib/db-types";
import React, { FC } from "react";
import { useFormState } from "react-dom";
import { updateOrAddBill } from "../lib/actions/billActions";
import Link from "next/link";
import { formatYearMonth } from "../lib/format";
import { findDecodePdf417 } from "../lib/pdf/barcodeDecoder";

// Next.js does not encode an utf-8 file name correctly when sending a form with a file attachment
// This is a workaround for that
const updateOrAddBillMiddleware = (locationId: string, billId:string|undefined, billYear:number|undefined, billMonth:number|undefined, prevState:any, formData: FormData) => {
    // URL encode the file name of the attachment so it is correctly sent to the server
    const billAttachment = formData.get('billAttachment') as File;
    formData.set('billAttachment', billAttachment, encodeURIComponent(billAttachment.name));
    return updateOrAddBill(locationId, billId, billYear, billMonth, prevState, formData);
}

export interface BillEditFormProps {
    location: BillingLocation,
    bill?: Bill,
}

export const BillEditForm:FC<BillEditFormProps> = ({ location, bill }) => {

    const { _id: billID, name, paid, attachment, notes, payedAmount: initialPayedAmount, barcodeImage: initialBarcodeImage } = bill ?? { _id:undefined, name:"", paid:false, notes:"" };

    const { yearMonth:{year: billYear, month: billMonth}, _id: locationID } = location;

    const initialState = { message: null, errors: {} };
    
    const handleAction = updateOrAddBillMiddleware.bind(null, locationID, billID, billYear, billMonth);

    const [ state, dispatch ] = useFormState(handleAction, initialState);
    const [ isPaid, setIsPaid ] = React.useState<boolean>(paid);
    const [ payedAmount, setPayedAmount ] = React.useState<number>(initialPayedAmount ?? 0);
    const [ barcodeImage, setBarcodeImage ] = React.useState<string | undefined>(initialBarcodeImage);

    const billPaid_handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        setIsPaid(event.target.checked);
    }

    const billAttachment_handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        findDecodePdf417(event)
            .then(result => {
                if(result) {
                    const { 
                        barcodeImage,
                        billInfo
                    } = result;

                    setPayedAmount(billInfo.amount);
                    setBarcodeImage(barcodeImage);
                }
            });
    }

    return(
    <div className="card card-compact card-bordered bg-base-100 shadow-s">
        <div className="card-body">
            <h2 className="card-title">{`${formatYearMonth(location.yearMonth)} ${location.name}`}</h2>
            <form action={ dispatch }>
                {
                    // don't show the delete button if we are adding a new bill
                    bill ?
                    <Link href={`/bill/${locationID}-${billID}/delete/`}>
                        <TrashIcon className="h-[1em] w-[1em] absolute cursor-pointer text-error bottom-5 right-4 text-2xl" />
                    </Link> : null
                }

                <input id="billName" name="billName" type="text" placeholder="Bill name" className="input input-bordered w-full" defaultValue={name} required />
                <div id="status-error" aria-live="polite" aria-atomic="true">
                    {state.errors?.billName &&
                    state.errors.billName.map((error: string) => (
                        <p className="mt-2 text-sm text-red-500" key={error}>
                        {error}
                        </p>
                    ))}
                </div>
                {
                    // <textarea className="textarea textarea-bordered my-1 w-full max-w-sm block" placeholder="Opis" value="Pričuva, Voda, Smeće"></textarea>

                    attachment ? 
                    <Link href={`/attachment/${locationID}-${billID}/`} target="_blank" className='text-center w-full max-w-[20em] text-nowrap truncate inline-block mt-4'>
                        <DocumentIcon className="h-[1em] w-[1em] text-2xl inline-block mr-1" />
                        {decodeURIComponent(attachment.fileName)}
                    </Link>
                    : null
                }
                <input id="billAttachment" name="billAttachment" type="file" className="file-input file-input-bordered max-w-sm w-full file-input-xs my-2 block" onChange={billAttachment_handleChange} />
                <div id="status-error" aria-live="polite" aria-atomic="true">
                    {state.errors?.billAttachment &&
                    state.errors.billAttachment.map((error: string) => (
                        <p className="mt-2 text-sm text-red-500" key={error}>
                        {error}
                        </p>
                    ))}
                </div>

                <div className="form-control w-32 p-1">
                    <label className="cursor-pointer label p-0">
                        <span className="label-text flex-none w-[6.4em]">Paid</span> 
                        <span>
                            <input id="billPaid" name="billPaid" type="checkbox" className="toggle toggle-success" defaultChecked={paid} onChange={billPaid_handleChange} />
                        </span>
                    </label>
                </div>

                {
                    isPaid && <>
                        <div className="form-control p-1">
                            <label className="cursor-pointer label p-0 flex">
                                <span className="label-text flex-none w-[6.4em]">Amount</span> 
                                <input type="text" id="payedAmount" name="payedAmount" className="input input-bordered text-right w-full" placeholder="0.00" defaultValue={payedAmount/100}/>
                            </label>
                        </div>
                        <div id="status-error" aria-live="polite" aria-atomic="true">
                            {state.errors?.payedAmount &&
                            state.errors.payedAmount.map((error: string) => (
                                <p className="mt-2 text-sm text-red-500" key={error}>
                                {error}
                                </p>
                            ))}
                        </div>
                    </>
                }

                <input type="hidden" name="barcodeImage" value={barcodeImage} />
                {
                    barcodeImage ?
                    <div className="form-control w-[325px] p-1">
                        <label className="cursor-pointer label p-0">
                            <span>
                                <img src={barcodeImage} style={{ maxWidth:"325px" }} />
                            </span>
                        </label>
                    </div> : null
                }

                <textarea id="billNotes" name="billNotes" className="textarea textarea-bordered my-2 max-w-lg w-full block" placeholder="Note" defaultValue={notes ?? ''}></textarea>
                <div id="status-error" aria-live="polite" aria-atomic="true">
                    {state.errors?.billNotes &&
                    state.errors.billNotes.map((error: string) => (
                        <p className="mt-2 text-sm text-red-500" key={error}>
                        {error}
                        </p>
                    ))}
                </div>

                <div className="pt-4">
                    <button type="submit" className="btn btn-primary">Save</button>
                    <Link className="btn btn-neutral ml-3" href={`/?year=${billYear}&month=${billMonth}`}>Cancel</Link>
                </div>
                
                <div id="status-error" aria-live="polite" aria-atomic="true">
                    {state.message &&
                    <p className="mt-2 text-sm text-red-500">
                    {state.message}
                    </p>
                    }
                </div>
            </form>
        </div>
    </div>);
}