import { DataTable, type DataTableColumn } from '@admin/components/ui/data-table';
import { FormGroup } from '@admin/components/ui/forms/form-group';
import { formClassName, formHelpClassName } from '@admin/components/ui/field-styles';
import { useFormResponse } from '@admin/hooks/use-form-response';
import { useSingletonPermissions } from '@admin/hooks/use-singleton-permissions';
import { dashboardPersistentLayout } from '@admin/layouts/dashboard-page-layout';
import { cn } from '@admin/lib/utils';
import { Head, router, useForm } from '@inertiajs/react';
import { FormEvent } from 'react';

type CurrencyRow = {
    code: string;
    name: string;
    symbol: string;
    is_base: boolean;
    status: boolean;
};

type RateRow = {
    id: number;
    rate: string;
    source: string;
    captured_at: string | null;
};

type ExchangeRatesProps = {
    currencies: CurrencyRow[];
    latest: { rate: string; source: string; captured_at: string | null } | null;
    history: RateRow[];
    sample: { usd: string; room: string } | null;
};

const currencyColumns: DataTableColumn<CurrencyRow>[] = [
    { header: 'Code', key: 'code', className: 'w-24' },
    { header: 'Name', key: 'name' },
    { header: 'Base', key: 'is_base', className: 'w-24' },
    { header: 'Status', key: 'status', className: 'w-24' },
];

const historyColumns: DataTableColumn<RateRow>[] = [
    { header: '1 USD in TZS', key: 'rate' },
    { header: 'Source', key: 'source' },
    { header: 'Recorded', key: 'captured_at' },
];

function EditExchangeRates({ currencies, latest, history, sample }: ExchangeRatesProps) {
    const { canEdit } = useSingletonPermissions('exchange-rate');
    const { data, setData, post, processing, errors } = useForm({ rate: latest?.rate ?? '' });
    const action = useFormResponse({ loadingMessage: 'Saving rate...' });
    const refresh = useFormResponse({ loadingMessage: 'Refreshing rate...' });

    const handleSubmit = (event: FormEvent) => {
        event.preventDefault();

        post('/admin/api/exchange_rates', {
            onStart: action.onStart,
            onSuccess: action.onSuccess,
            onError: action.onError,
            preserveScroll: true,
        });
    };

    const handleRefresh = () => {
        router.post(
            '/admin/api/exchange_rates/refresh',
            {},
            {
                onStart: refresh.onStart,
                onSuccess: refresh.onSuccess,
                onError: refresh.onError,
                preserveScroll: true,
            },
        );
    };

    return (
        <>
            <Head title="Currencies" />

            <div className="grid grid-cols-12 gap-6">
                <div className="col-span-12">
                    <p className={cn('mb-4', formHelpClassName)}>
                        Tanzanian shillings are the base currency. Room rates are stored in shillings, and the dollar amount is calculated from the latest rate. A new rate is stored every six hours when the published rate changes. Invoices keep the rate from the day they were issued.
                    </p>

                    <DataTable data={currencies} columns={currencyColumns} title="Currencies" itemsPerPage={10} noDataText="No currencies" />

                    <div className="box mt-6">
                        <div className="box-header">
                            <h5 className="box-title">US dollar rate</h5>
                        </div>
                        <div className="box-body">
                            {latest && (
                                <p className={cn('mb-4', formHelpClassName)}>
                                    Current rate recorded {latest.captured_at} from {latest.source}.
                                    {sample ? ` ${sample.usd}. ${sample.room}.` : ''}
                                </p>
                            )}

                            {canEdit && (
                                <form className={formClassName} noValidate onSubmit={handleSubmit}>
                                    <FormGroup
                                        label="1 USD equals (TZS)"
                                        helpText="Saving adds a new rate. It does not change rates already stored on invoices."
                                        error={errors.rate}
                                        inputProps={{
                                            value: data.rate,
                                            inputMode: 'decimal',
                                            onChange: (event) => setData('rate', event.target.value),
                                            required: true,
                                        }}
                                    />
                                    <div className="flex flex-wrap gap-2">
                                        <button type="submit" className="ti-btn ti-btn-primary" disabled={processing}>
                                            Save rate
                                        </button>
                                        <button type="button" className="ti-btn ti-btn-outline-primary" onClick={handleRefresh}>
                                            Refresh from provider
                                        </button>
                                    </div>
                                </form>
                            )}
                        </div>
                    </div>

                    <div className="mt-6">
                        <DataTable data={history} columns={historyColumns} title="Rate history" itemsPerPage={12} noDataText="No rates recorded" />
                    </div>
                </div>
            </div>
        </>
    );
}

export default Object.assign(EditExchangeRates, {
    layout: dashboardPersistentLayout('Currencies', 'Tanzanian shilling and US dollar exchange rates'),
});
