"use client";

import { TrashIcon } from "@heroicons/react/24/outline";
import { FC, useState } from "react";
import { BillingLocation, YearMonth } from "../lib/db-types";
import { updateOrAddLocation } from "../lib/actions/locationActions";
import { useFormState } from "react-dom";
import Link from "next/link";
import { useLocale, useTranslations } from "next-intl";
import { InfoBox } from "./InfoBox";

export type LocationEditFormProps = {
    /** location which should be edited */
    location: BillingLocation,
    /** year adn month at a new billing location should be assigned */
    yearMonth?: undefined
} | {
    /** location which should be edited */
    location?: undefined,
    /** year adn month at a new billing location should be assigned */
    yearMonth: YearMonth
}

export const LocationEditForm: FC<LocationEditFormProps> = ({ location, yearMonth }) => {
    const initialState = { message: null, errors: {} };
    const handleAction = updateOrAddLocation.bind(null, location?._id, location?.yearMonth ?? yearMonth);
    const [state, dispatch] = useFormState(handleAction, initialState);
    const t = useTranslations("location-edit-form");
    const locale = useLocale();

    // Track whether to generate 2D code for tenant (use persisted value from database)
    const [generateTenantCode, setGenerateTenantCode] = useState(
        location?.generateTenantCode ?? false
    );

    // Track whether to automatically notify tenant (use persisted value from database)
    const [autoBillFwd, setautoBillFwd] = useState(
        location?.autoBillFwd ?? false
    );

    // Track whether to automatically send rent notification (use persisted value from database)
    const [rentDueNotification, setrentDueNotification] = useState(
        location?.rentDueNotification ?? false
    );

    // Track tenant field values for real-time validation
    const [tenantFields, setTenantFields] = useState({
        tenantName: location?.tenantName ?? "",
        tenantStreet: location?.tenantStreet ?? "",
        tenantTown: location?.tenantTown ?? "",
        tenantEmail: location?.tenantEmail ?? "",
    });

    const handleTenantFieldChange = (field: keyof typeof tenantFields, value: string) => {
        setTenantFields(prev => ({ ...prev, [field]: value }));
    };

    let { year, month } = location ? location.yearMonth : yearMonth;

    return (
        <div className="card card-compact card-bordered min-w-[20em] max-w-[90em] bg-base-100 shadow-s my-1">
            <div className="card-body">
                <form action={dispatch}>
                    {
                        location &&
                        <Link href={`/${locale}/location/${location._id}/delete`} className="absolute bottom-5 right-4 tooltip" data-tip={t("delete-tooltip")}>
                            <TrashIcon className="h-[1em] w-[1em] text-error text-2xl" />
                        </Link>
                    }
                    <fieldset className="fieldset mt-2 p-2">
                        <legend className="fieldset-legend font-semibold uppercase">{t("location-name-legend")}</legend>
                        <input id="locationName" name="locationName" type="text" placeholder={t("location-name-placeholder")} className="input input-bordered w-full placeholder:text-gray-600" defaultValue={location?.name ?? ""} />
                        <div id="status-error" aria-live="polite" aria-atomic="true">
                            {state.errors?.locationName &&
                                state.errors.locationName.map((error: string) => (
                                    <p className="mt-2 text-sm text-red-500" key={error}>
                                        {error}
                                    </p>
                                ))}
                        </div>
                    </fieldset>
                    <fieldset className="fieldset bg-base-200 border-base-300 rounded-box w-xs border p-4 pb-2 mt-4">
                        <legend className="fieldset-legend font-semibold uppercase">{t("tenant-2d-code-legend")}</legend>
                        <InfoBox className="p-1 mb-1">{t("tenant-2d-code-info")}</InfoBox>

                        <fieldset className="fieldset">
                            <label className="label cursor-pointer justify-start gap-3">
                                <input
                                    type="checkbox"
                                    name="generateTenantCode"
                                    className="toggle toggle-primary"
                                    checked={generateTenantCode}
                                    onChange={(e) => setGenerateTenantCode(e.target.checked)}
                                />
                                <legend className="fieldset-legend">{t("tenant-2d-code-toggle-label")}</legend>
                            </label>
                        </fieldset>

                        {generateTenantCode && (
                            <>
                                <div className="form-control w-full">
                                    <label className="label">
                                        <span className="label-text">{t("tenant-name-label")}</span>
                                    </label>
                                    <input
                                        id="tenantName"
                                        name="tenantName"
                                        type="text"
                                        maxLength={30}
                                        placeholder={t("tenant-name-placeholder")}
                                        className="input input-bordered w-full placeholder:text-gray-600"
                                        defaultValue={location?.tenantName ?? ""}
                                        onChange={(e) => handleTenantFieldChange("tenantName", e.target.value)}
                                    />
                                    <div id="tenantName-error" aria-live="polite" aria-atomic="true">
                                        {state.errors?.tenantName &&
                                            state.errors.tenantName.map((error: string) => (
                                                <p className="mt-2 text-sm text-red-500" key={error}>
                                                    {error}
                                                </p>
                                            ))}
                                    </div>
                                </div>

                                <div className="form-control w-full">
                                    <label className="label">
                                        <span className="label-text">{t("tenant-street-label")}</span>
                                    </label>
                                    <input
                                        id="tenantStreet"
                                        name="tenantStreet"
                                        type="text"
                                        maxLength={27}
                                        placeholder={t("tenant-street-placeholder")}
                                        className="input input-bordered w-full placeholder:text-gray-600"
                                        defaultValue={location?.tenantStreet ?? ""}
                                        onChange={(e) => handleTenantFieldChange("tenantStreet", e.target.value)}
                                    />
                                    <div id="tenantStreet-error" aria-live="polite" aria-atomic="true">
                                        {state.errors?.tenantStreet &&
                                            state.errors.tenantStreet.map((error: string) => (
                                                <p className="mt-2 text-sm text-red-500" key={error}>
                                                    {error}
                                                </p>
                                            ))}
                                    </div>
                                </div>

                                <div className="form-control w-full mb-4">
                                    <label className="label">
                                        <span className="label-text">{t("tenant-town-label")}</span>
                                    </label>
                                    <input
                                        id="tenantTown"
                                        name="tenantTown"
                                        type="text"
                                        maxLength={27}
                                        placeholder={t("tenant-town-placeholder")}
                                        className="input input-bordered w-full placeholder:text-gray-600"
                                        defaultValue={location?.tenantTown ?? ""}
                                        onChange={(e) => handleTenantFieldChange("tenantTown", e.target.value)}
                                    />
                                    <div id="tenantTown-error" aria-live="polite" aria-atomic="true">
                                        {state.errors?.tenantTown &&
                                            state.errors.tenantTown.map((error: string) => (
                                                <p className="mt-2 text-sm text-red-500" key={error}>
                                                    {error}
                                                </p>
                                            ))}
                                    </div>
                                </div>
                                <InfoBox className="p-1 mb-1">{t("tenant-2d-code-note")}</InfoBox>  
                            </>
                        )}
                </fieldset>


                    <fieldset className="fieldset bg-base-200 border-base-300 rounded-box w-xs border p-4 pb-2 mt-4">
                        <legend className="fieldset-legend font-semibold uppercase">{t("auto-utility-bill-forwarding-legend")}</legend>
                        <InfoBox className="p-1 mb-1">{t("auto-utility-bill-forwarding-info")}</InfoBox>

                        <fieldset className="fieldset">
                            <label className="label cursor-pointer justify-start gap-3">
                                <input
                                    disabled={true}
                                    type="checkbox"
                                    name="autoBillFwd"
                                    className="toggle toggle-primary"
                                    checked={autoBillFwd}
                                    onChange={(e) => setautoBillFwd(e.target.checked)}
                                />
                                <legend className="fieldset-legend">{t("auto-utility-bill-forwarding-toggle-label")}</legend>
                            </label>
                        </fieldset>

                        {autoBillFwd && (
                            <fieldset className="fieldset mt-2 p-2">
                                <legend className="fieldset-legend">{t("utility-bill-forwarding-strategy-label")}</legend>
                                <select defaultValue={location?.billFwdStrategy ?? "when-payed"} className="select input-bordered w-full" name="billFwdStrategy">
                                    <option value="when-payed">{t("utility-bill-forwarding-when-payed")}</option>
                                    <option value="when-attached">{t("utility-bill-forwarding-when-attached")}</option>
                                </select>
                            </fieldset>
                        )}
                    </fieldset>

                    <fieldset className="fieldset bg-base-200 border-base-300 rounded-box w-xs border p-4 pb-2 mt-4">
                        <legend className="fieldset-legend font-semibold uppercase">{t("auto-rent-notification-legend")}</legend>
                        <InfoBox className="p-1 mb-1">{t("auto-rent-notification-info")}</InfoBox>

                        <fieldset className="fieldset">
                            <label className="label cursor-pointer justify-start gap-3">
                                <input
                                    disabled={true}
                                    type="checkbox"
                                    name="rentDueNotification"
                                    className="toggle toggle-primary"
                                    checked={rentDueNotification}
                                    onChange={(e) => setrentDueNotification(e.target.checked)}
                                />
                                <legend className="fieldset-legend">{t("auto-rent-notification-toggle-label")}</legend>
                            </label>
                        </fieldset>

                        {rentDueNotification && (
                            <>
                                <fieldset className="fieldset mt-2 p-2">
                                    <legend className="fieldset-legend">{t("rent-due-day-label")}</legend>
                                    <select defaultValue={location?.rentDueDay ?? 1} className="select input-bordered w-full" name="rentDueDay">
                                        {Array.from({ length: 28 }, (_, i) => i + 1).map(day => (
                                            <option key={day} value={day}>{day}</option>
                                        ))}
                                    </select>
                                </fieldset>
                                <fieldset className="fieldset mt-2 p-2">
                                    <legend className="fieldset-legend">{t("rent-amount-label")}</legend>
                                    <input
                                        id="rentAmount"
                                        name="rentAmount"
                                        type="number"
                                        min="1"
                                        step="0.01"
                                        placeholder={t("rent-amount-placeholder")}
                                        className="input input-bordered w-full placeholder:text-gray-600 text-right"
                                        defaultValue={location?.rentAmount ?? ""}
                                    />
                                    <div id="rentAmount-error" aria-live="polite" aria-atomic="true">
                                        {state.errors?.rentAmount &&
                                            state.errors.rentAmount.map((error: string) => (
                                                <p className="mt-2 text-sm text-red-500" key={error}>
                                                    {error}
                                                </p>
                                            ))}
                                    </div>
                                </fieldset>
                            </>
                        )}
                    </fieldset>

                    {(autoBillFwd || rentDueNotification) && (
                        <fieldset className="fieldset bg-base-200 border-base-300 rounded-box w-xs border p-4 pb-2 mt-4">
                            <legend className="fieldset-legend font-semibold uppercase">{t("tenant-email-legend")}</legend>
                            <input
                                id="tenantEmail"
                                name="tenantEmail"
                                type="email"
                                placeholder={t("tenant-email-placeholder")}
                                className="input input-bordered w-full placeholder:text-gray-600"
                                defaultValue={location?.tenantEmail ?? ""}
                                onChange={(e) => handleTenantFieldChange("tenantEmail", e.target.value)}
                            />
                            <div id="tenantEmail-error" aria-live="polite" aria-atomic="true">
                                {state.errors?.tenantEmail &&
                                    state.errors.tenantEmail.map((error: string) => (
                                        <p className="mt-2 text-sm text-red-500" key={error}>
                                            {error}
                                        </p>
                                    ))}
                            </div>
                        </fieldset>
                    )}

                    <fieldset className="fieldset bg-base-200 border-base-300 rounded-box w-xs border p-4 pb-2 mt-4">
                        <legend className="fieldset-legend font-semibold uppercase">{t("scope-legend")}</legend>
                            {!location ? (
                                <fieldset className="fieldset">
                                    <label className="label cursor-pointer justify-start gap-3">
                                        <input
                                            type="checkbox"
                                            name="addToSubsequentMonths"
                                            className="toggle toggle-primary"
                                        />
                                        <legend className="fieldset-legend">{t("add-to-subsequent-months")}</legend>
                                    </label>
                                </fieldset>

                            ) : (
                                <>
                                    <InfoBox className="p-1 mb-1">{t("update-scope-info")}</InfoBox>
                                    <fieldset className="fieldset mt-2 p-2">
                                        <legend className="fieldset-legend">{t("update-scope-legend")}</legend>
                                        <select defaultValue="current" className="select input-bordered w-full" name="updateScope">
                                            <option value="current">{t("update-current-month")}</option>
                                            <option value="subsequent">{t("update-subsequent-months")}</option>
                                            <option value="all">{t("update-all-months")}</option>
                                        </select>
                                    </fieldset>
                                </>
                            )}
                    </fieldset>

                    <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>
                    <div className="pt-4">
                        <button className="btn btn-primary w-[5.5em]">{t("save-button")}</button>
                        <Link className="btn btn-neutral w-[5.5em] ml-3" href={`/?year=${year}&month=${month}`}>{t("cancel-button")}</Link>
                    </div>
                </form>
            </div>
        </div>
    )
}

export const LocationEditFormSkeleton: FC = () => {
    const t = useTranslations("location-edit-form");

    return (
        <div className="card card-compact card-bordered min-w-[20em] max-w-[90em] bg-base-100 shadow-s my-1">
            
            <div className="card-body">
                <fieldset className="fieldset mt-2 p-2">
                    <legend className="fieldset-legend font-semibold uppercase">{t("location-name-legend")}</legend>
                    <div id="locationName" className="input w-full skeleton"></div>
                </fieldset>
                <div className="pt-4">
                    <div className="btn w-[5.5em] skeleton"></div>
                    <div className="btn w-[5.5em] ml-3 skeleton"></div>
                </div>
            </div>
        </div>
    )
}
