"use client";

import { FC, useState } from "react";
import { UserSettings } from "../lib/db-types";
import { updateUserSettings } from "../lib/actions/userSettingsActions";
import { useFormState, useFormStatus } from "react-dom";
import { useLocale, useTranslations } from "next-intl";
import Link from "next/link";
import SettingsIcon from "@mui/icons-material/Settings";
import { formatIban } from "../lib/formatStrings";
import { InfoBox } from "./InfoBox";
import { NoteBox } from "./NoteBox";
import { LinkIcon } from "@heroicons/react/24/outline";

export type UserSettingsFormProps = {
    userSettings: UserSettings | null;
}

type FormFieldsProps = {
    userSettings: UserSettings | null;
    errors: any;
    message: string | null;
}

const FormFields: FC<FormFieldsProps> = ({ userSettings, errors, message }) => {
    const { pending } = useFormStatus();
    const t = useTranslations("user-settings-form");
    const locale = useLocale();

    // Track current form values for real-time validation
    const [formValues, setFormValues] = useState({
        enableIbanPayment: userSettings?.enableIbanPayment ?? false,
        ownerName: userSettings?.ownerName ?? "",
        ownerStreet: userSettings?.ownerStreet ?? "",
        ownerTown: userSettings?.ownerTown ?? "",
        ownerIBAN: formatIban(userSettings?.ownerIBAN) ?? "",
        currency: userSettings?.currency ?? "EUR",

        enableRevolutPayment: userSettings?.enableRevolutPayment ?? false,
        ownerRevolutProfileName: userSettings?.ownerRevolutProfileName ?? "",
    });

    // https://revolut.me/aderezic?currency=EUR&amount=70000

    const handleInputChange = (field: keyof typeof formValues, value: string | boolean) => {
        setFormValues(prev => ({ ...prev, [field]: value }));
    };

    return (
        <>
            <fieldset className="fieldset bg-base-200 border-base-300 rounded-box w-xs border p-4 pt-1 pb-2 mt-4">
                <legend className="fieldset-legend font-semibold uppercase text-base">{t("general-settings-legend")}</legend>

                <div className="form-control w-full">
                    <label className="label">
                        <span className="label-text">{t("currency-label")}</span>
                    </label>
                    <select
                        id="currency"
                        name="currency"
                        className="select select-bordered w-full"
                        defaultValue={formValues.currency}
                        onChange={(e) => handleInputChange("currency", e.target.value)}
                        disabled={pending}
                    >
                        <option value="EUR">EUR - Euro</option>
                        <option value="USD">USD - US Dollar</option>
                        <option value="GBP">GBP - British Pound</option>
                        <option value="CHF">CHF - Swiss Franc</option>
                        <option value="JPY">JPY - Japanese Yen</option>
                        <option value="CAD">CAD - Canadian Dollar</option>
                        <option value="AUD">AUD - Australian Dollar</option>
                        <option value="NZD">NZD - New Zealand Dollar</option>
                        <option value="CNY">CNY - Chinese Yuan</option>
                        <option value="HKD">HKD - Hong Kong Dollar</option>
                        <option value="SGD">SGD - Singapore Dollar</option>
                        <option value="SEK">SEK - Swedish Krona</option>
                        <option value="NOK">NOK - Norwegian Krone</option>
                        <option value="DKK">DKK - Danish Krone</option>
                        <option value="PLN">PLN - Polish Zloty</option>
                        <option value="CZK">CZK - Czech Koruna</option>
                        <option value="HUF">HUF - Hungarian Forint</option>
                        <option value="RON">RON - Romanian Leu</option>
                        <option value="BGN">BGN - Bulgarian Lev</option>
                        <option value="RSD">RSD - Serbian Dinar</option>
                        <option value="BAM">BAM - Bosnia-Herzegovina Mark</option>
                        <option value="MKD">MKD - Macedonian Denar</option>
                        <option value="ALL">ALL - Albanian Lek</option>
                        <option value="TRY">TRY - Turkish Lira</option>
                        <option value="RUB">RUB - Russian Ruble</option>
                        <option value="UAH">UAH - Ukrainian Hryvnia</option>
                        <option value="INR">INR - Indian Rupee</option>
                        <option value="BRL">BRL - Brazilian Real</option>
                        <option value="MXN">MXN - Mexican Peso</option>
                        <option value="ZAR">ZAR - South African Rand</option>
                        <option value="KRW">KRW - South Korean Won</option>
                        <option value="THB">THB - Thai Baht</option>
                        <option value="MYR">MYR - Malaysian Ringgit</option>
                        <option value="IDR">IDR - Indonesian Rupiah</option>
                        <option value="PHP">PHP - Philippine Peso</option>
                    </select>
                    <div id="currency-error" aria-live="polite" aria-atomic="true">
                        {errors?.currency &&
                            errors.currency.map((error: string) => (
                                <p className="mt-2 text-sm text-red-500" key={error}>
                                    {error}
                                </p>
                            ))}
                    </div>
                </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 text-base">{t("iban-payment-instructions--legend")}</legend>

                <InfoBox>{t("iban-payment-instructions--intro-message")}</InfoBox>

                <fieldset className="fieldset">
                    <label className="label cursor-pointer justify-start gap-3">
                        <input
                            type="checkbox"
                            name="enableIbanPayment"
                            className="toggle toggle-primary"
                            checked={formValues.enableIbanPayment}
                            onChange={(e) => handleInputChange("enableIbanPayment", e.target.checked)}
                        />
                        <legend className="fieldset-legend">{t("iban-payment-instructions--toggle-label")}</legend>
                    </label>
                </fieldset>

                { formValues.enableIbanPayment ? (
                <div className="animate-expand-fade-in origin-top">
                    <div className="divider mt-2 mb-2 font-bold uppercase">{t("iban-form-title")}</div>
                    <div className="form-control w-full">
                        <label className="label">
                            <span className="label-text">{t("iban-owner-name-label")}</span>
                        </label>
                        <input
                            id="ownerName"
                            name="ownerName"
                            type="text"
                            maxLength={25}
                            placeholder={t("iban-owner-name-placeholder")}
                            className="input input-bordered w-full placeholder:text-gray-600"
                            defaultValue={formValues.ownerName}
                            onChange={(e) => handleInputChange("ownerName", e.target.value)}
                            disabled={pending}
                        />
                        <div id="ownerName-error" aria-live="polite" aria-atomic="true">
                            {errors?.ownerName &&
                                errors.ownerName.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("iban-owner-street-label")} </span>
                        </label>
                        <input
                            id="ownerStreet"
                            name="ownerStreet"
                            type="text"
                            maxLength={25}
                            placeholder={t("iban-owner-street-placeholder")}
                            className="input input-bordered w-full placeholder:text-gray-600"
                            defaultValue={formValues.ownerStreet}
                            onChange={(e) => handleInputChange("ownerStreet", e.target.value)}
                            disabled={pending}
                        />
                        <div id="ownerStreet-error" aria-live="polite" aria-atomic="true">
                            {errors?.ownerStreet &&
                                errors.ownerStreet.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("iban-owner-town-label")}</span>
                        </label>
                        <input
                            id="ownerTown"
                            name="ownerTown"
                            type="text"
                            maxLength={27}
                            placeholder={t("iban-owner-town-placeholder")}
                            className="input input-bordered w-full placeholder:text-gray-600"
                            defaultValue={formValues.ownerTown}
                            onChange={(e) => handleInputChange("ownerTown", e.target.value)}
                            disabled={pending}
                        />
                        <div id="ownerTown-error" aria-live="polite" aria-atomic="true">
                            {errors?.ownerTown &&
                                errors.ownerTown.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("iban-owner-iban-label")}</span>
                        </label>
                        <input
                            id="ownerIBAN"
                            name="ownerIBAN"
                            type="text"
                            placeholder={t("iban-owner-iban-placeholder")}
                            className="input input-bordered w-full placeholder:text-gray-600"
                            defaultValue={formValues.ownerIBAN}
                            onChange={(e) => handleInputChange("ownerIBAN", e.target.value)}
                            disabled={pending}
                        />
                        <div id="ownerIBAN-error" aria-live="polite" aria-atomic="true">
                            {errors?.ownerIBAN &&
                                errors.ownerIBAN.map((error: string) => (
                                    <p className="mt-2 text-sm text-red-500" key={error}>
                                        {error}
                                    </p>
                                ))}
                        </div>
                    </div>

                    <NoteBox>{t("payment-additional-notes")}</NoteBox>
                </div>
                ) : // ELSE include hidden inputs to preserve existing values
                <>
                    <input
                        id="ownerName"
                        name="ownerName"
                        type="hidden"
                        value={formValues.ownerName}
                    />
                    <input
                        id="ownerStreet"
                        name="ownerStreet"
                        type="hidden"
                        value={formValues.ownerStreet}
                    />
                    <input
                        id="ownerTown"
                        name="ownerTown"
                        type="hidden"
                        defaultValue={formValues.ownerTown}
                    />
                    <input
                        id="ownerIBAN"
                        name="ownerIBAN"
                        type="hidden"
                        defaultValue={formValues.ownerIBAN}
                    />
                </>
            }
            </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 text-base">{t("revolut-payment-instructions--legend")}</legend>

                <InfoBox>{t("revolut-payment-instructions--intro-message")}</InfoBox>

                <fieldset className="fieldset">
                    <label className="label cursor-pointer justify-start gap-3">
                        <input
                            type="checkbox"
                            name="enableRevolutPayment"
                            className="toggle toggle-primary"
                            checked={formValues.enableRevolutPayment}
                            onChange={(e) => handleInputChange("enableRevolutPayment", e.target.checked)}
                        />
                        <legend className="fieldset-legend">{t("revolut-payment-instructions--toggle-label")}</legend>
                    </label>
                </fieldset>
                
                { formValues.enableRevolutPayment ? (
                <div className="animate-expand-fade-in origin-top">
                    <div className="divider mt-2 mb-2 font-bold uppercase max-w-[14em]">{t("revolut-form-title")}</div>
                    <div className="form-control w-full">
                        <label className="label">
                            <span className="label-text">{t("revolut-profile-label")}</span>
                        </label>
                        <input
                            id="ownerRevolutProfileName"
                            name="ownerRevolutProfileName"
                            type="text"
                            maxLength={25}
                            placeholder={t("revolut-profile-placeholder")}
                            className="input input-bordered w-full placeholder:text-gray-600"
                            defaultValue={formValues.ownerRevolutProfileName}
                            onChange={(e) => handleInputChange("ownerRevolutProfileName", e.target.value)}
                            disabled={pending}
                        />
                        <label className="label">
                            <span className="label-text-alt text-gray-500 max-w-[25rem]">{t("revolut-profile-tooltip")}</span>
                        </label>
                        <div id="ownerRevolutProfileName-error" aria-live="polite" aria-atomic="true">
                            {errors?.ownerRevolutProfileName &&
                                errors.ownerRevolutProfileName.map((error: string) => (
                                    <p className="mt-2 text-sm text-red-500" key={error}>
                                        {error}
                                    </p>
                                ))}
                        </div>
                         {
                            !errors?.ownerRevolutProfileName && formValues.ownerRevolutProfileName.length > 5 ? (
                            <p className="p-2 text-center">
                                    {t("revolut-profile--test-link-label")} {' '}
                                    <LinkIcon className="h-[1.2em] w-[1.2em] inline-block ml-1 mr-1"/>
                                    <Link
                                        href={`https://revolut.me/${formValues.ownerRevolutProfileName?.replace('@', '')}?amount=100&currency=${formValues.currency}`}
                                        target="_blank"
                                        className="underline"
                                    >
                                        {t("revolut-profile--test-link-text")}
                                    </Link>
                                </p>
                            ) : null
                         }
                    </div>
                    <NoteBox>{t("payment-additional-notes")}</NoteBox>
                </div>
                )
                : // ELSE include hidden input to preserve existing value
                <>
                    <input
                        id="ownerRevolutProfileName"
                        name="ownerRevolutProfileName"
                        type="hidden"
                        value={formValues.ownerRevolutProfileName}
                    />
                </>
            }
            </fieldset>

            <div id="general-error" aria-live="polite" aria-atomic="true">
                {message && (
                    <p className="mt-2 text-sm text-red-500">
                        {message}
                    </p>
                )}
            </div>

            <div className="pt-4">
                <button className="btn btn-primary w-[5.5em]" disabled={pending}>
                    {pending ? (
                        <span className="loading loading-spinner loading-sm"></span>
                    ) : (
                        t("save-button")
                    )}
                </button>
                <Link className={`btn btn-neutral w-[5.5em] ml-3 ${pending ? "btn-disabled" : ""}`} href={`/${locale}/home/account`}>
                    {t("cancel-button")}
                </Link>
            </div>
        </>
    );
};

export const UserSettingsForm: FC<UserSettingsFormProps> = ({ userSettings }) => {
    const initialState = { message: null, errors: {} };
    const [state, dispatch] = useFormState(updateUserSettings, initialState);
    const t = useTranslations("user-settings-form");

    return (
        <div className="card card-compact card-bordered max-w-[90em] bg-base-100 shadow-s my-1">
            <div className="card-body">
                <h2 className="card-title"><SettingsIcon className="w-6 h-6" /> {t("title")}</h2>
                <form action={dispatch}>
                    <FormFields
                        userSettings={userSettings}
                        errors={state.errors}
                        message={state.message ?? null}
                    />
                </form>
            </div>
        </div>
    );
};

export const UserSettingsFormSkeleton: FC = () => {
    return (
        <div className="card card-compact card-bordered max-w-[90em] bg-base-100 shadow-s my-1">
            <div className="card-body">
                <div className="h-8 w-32 skeleton mb-4"></div>
                <div className="input w-full skeleton"></div>
                <div className="input w-full skeleton mt-4"></div>
                <div className="textarea w-full h-24 skeleton mt-4"></div>
                <div className="input w-full skeleton mt-4"></div>
                <div className="pt-4">
                    <div className="btn skeleton w-24"></div>
                </div>
            </div>
        </div>
    );
};
