import React, { useEffect, useState } from 'react';
import { __ } from '@wordpress/i18n';

const appData = window.manfietExpenseTrackerData || {};

const requestJson = (url, options = {}) => {
    const headers = {
        'Content-Type': 'application/json',
        ...(options.headers || {}),
    };

    if (appData.restNonce) {
        headers['X-WP-Nonce'] = appData.restNonce;
    }

    return fetch(url, {
        credentials: 'same-origin',
        ...options,
        headers,
    }).then(async (response) => {
        const data = await response.json().catch(() => ({}));
        if (!response.ok) {
            throw new Error(data.message || 'Request failed');
        }

        return data;
    });
};

const emptyAccount = () => ({
    id: null,
    account_type: 'bank',
    provider_name: '',
    account_number: '',
    holder_name: '',
    routing_number: '',
    branch_name: '',
    note: '',
    is_default: false,
});

const accountTypeOptions = [
    { value: 'bank', label: __('Bank', 'manfi-expense-tracker') },
    { value: 'bkash', label: __('bKash', 'manfi-expense-tracker') },
    { value: 'nagad', label: __('Nagad', 'manfi-expense-tracker') },
    { value: 'rocket', label: __('Rocket', 'manfi-expense-tracker') },
    { value: 'card', label: __('Card', 'manfi-expense-tracker') },
    { value: 'other', label: __('Other', 'manfi-expense-tracker') },
];

const FinancialAccounts = ({ mode = 'dashboard' }) => {
    const restBase = appData.restBase || '/wp-json/manfi-expense-tracker/v1/';
    const isCreateMode = mode === 'create';
    const [accounts, setAccounts] = useState([]);
    const [form, setForm] = useState(emptyAccount());
    const [editingId, setEditingId] = useState(null);
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState('');
    const [message, setMessage] = useState('');

    const loadAccounts = () => {
        setLoading(true);
        return requestJson(`${restBase}financial-accounts`)
            .then((data) => {
                setAccounts(Array.isArray(data) ? data : []);
                setError('');
            })
            .catch((requestError) => {
                setError(requestError.message || __('Failed to load financial accounts.', 'manfi-expense-tracker'));
            })
            .finally(() => setLoading(false));
    };

    useEffect(() => {
        loadAccounts();
    }, [restBase]);

    const createPageUrl = `${window.location.pathname}?page=manfiet-financial-accounts-create`;
    const dashboardPageUrl = `${window.location.pathname}?page=manfiet-financial-accounts`;
    const accountIdParam = new URLSearchParams(window.location.search).get('account_id') || '';

    const updateField = (field, value) => {
        setForm((current) => ({ ...current, [field]: value }));
    };

    const resetForm = () => {
        setForm(emptyAccount());
        setEditingId(null);
        setMessage('');
        setError('');
    };

    const editAccount = (account) => {
        setEditingId(account.id);
        setForm({
            id: account.id,
            account_type: account.account_type || 'bank',
            provider_name: account.provider_name || '',
            account_number: account.account_number || '',
            holder_name: account.holder_name || '',
            routing_number: account.routing_number || '',
            branch_name: account.branch_name || '',
            note: account.note || '',
            is_default: Boolean(account.is_default),
        });
        setMessage(__('Editing financial account', 'manfi-expense-tracker'));
        setError('');
        window.scrollTo({ top: 0, behavior: 'smooth' });
    };

    useEffect(() => {
        if (!isCreateMode || !accountIdParam || loading || accounts.length === 0) {
            return;
        }

        const selectedAccount = accounts.find((account) => String(account.id) === String(accountIdParam));
        if (selectedAccount && editingId !== selectedAccount.id) {
            editAccount(selectedAccount);
        }
    }, [accountIdParam, accounts, editingId, isCreateMode, loading]);

    const deleteAccount = (accountId) => {
        if (!window.confirm(__('Delete this financial account?', 'manfi-expense-tracker'))) {
            return;
        }

        setSaving(true);
        setError('');
        requestJson(`${restBase}financial-accounts/${accountId}`, { method: 'DELETE' })
            .then(() => {
                setMessage(__('Financial account deleted.', 'manfi-expense-tracker'));
                loadAccounts();
                if (editingId === accountId) {
                    resetForm();
                }
            })
            .catch((requestError) => {
                setError(requestError.message || __('Failed to delete financial account.', 'manfi-expense-tracker'));
            })
            .finally(() => setSaving(false));
    };

    const submitAccount = (event) => {
        event.preventDefault();
        setSaving(true);
        setError('');
        setMessage('');

        const payload = {
            account_type: form.account_type,
            provider_name: form.provider_name,
            account_number: form.account_number,
            holder_name: form.holder_name,
            routing_number: form.routing_number,
            branch_name: form.branch_name,
            note: form.note,
            is_default: form.is_default,
        };

        const method = editingId ? 'PUT' : 'POST';
        const url = editingId ? `${restBase}financial-accounts/${editingId}` : `${restBase}financial-accounts`;

        requestJson(url, {
            method,
            body: JSON.stringify(payload),
        })
            .then(() => {
                setMessage(editingId ? __('Financial account updated.', 'manfi-expense-tracker') : __('Financial account created.', 'manfi-expense-tracker'));
                resetForm();
                loadAccounts();
            })
            .catch((requestError) => {
                setError(requestError.message || __('Failed to save financial account.', 'manfi-expense-tracker'));
            })
            .finally(() => setSaving(false));
    };

    return (
        <div className="manfiet-page-shell manfiet-page-shell-wide manfiet-financial-accounts-shell">
            <div className="manfiet-page-hero">
                <div className='left-section'>
                <h1 className="manfiet-page-title">{isCreateMode ? __('Create Financial Account', 'manfi-expense-tracker') : __('Financial Accounts', 'manfi-expense-tracker')}</h1>
                <p className="manfiet-page-subtitle">{isCreateMode ? __('Add a new payout account for invoices.', 'manfi-expense-tracker') : __('Store bank, bKash, Nagad, Rocket, card, and other payout accounts for reuse in invoices.', 'manfi-expense-tracker')}</p>
                </div>
                <div className="manfiet-form-row manfiet-form-row-end manfiet-mt-12">
                    {isCreateMode ? (
                        <button type="button" className="manfiet-button manfiet-button-secondary" onClick={() => { window.location.href = dashboardPageUrl; }}>
                            {__('Back to Financial Accounts', 'manfi-expense-tracker')}
                        </button>
                    ) : (
                        <button type="button" className="manfiet-button manfiet-button-primary" onClick={() => { window.location.href = createPageUrl; }}>
                            {__('Create Financial Account', 'manfi-expense-tracker')}
                        </button>
                    )}
                </div>
            </div>

            {isCreateMode && (
            <div className="manfiet-card manfiet-mb-16">
                <h3 className="manfiet-card-title">{editingId ? __('Edit Account', 'manfi-expense-tracker') : __('Add New Account', 'manfi-expense-tracker')}</h3>
                {error && <p className="manfiet-alert manfiet-alert-error">{error}</p>}
                {message && <p className="manfiet-alert manfiet-alert-success">{message}</p>}

                <form onSubmit={submitAccount} className="manfiet-form-stack">
                    <div className="manfiet-form-grid">
                        <div className="manfiet-field">
                            <label className="manfiet-label" htmlFor="manfiet-account-type">{__('Account Type', 'manfi-expense-tracker')}</label>
                            <select id="manfiet-account-type" className="manfiet-input" value={form.account_type} onChange={(e) => updateField('account_type', e.target.value)}>
                                {accountTypeOptions.map((option) => (
                                    <option key={option.value} value={option.value}>{option.label}</option>
                                ))}
                            </select>
                        </div>

                        {/* For mobile wallets (bKash, Nagad, Rocket) show only holder name and mobile number */}
                        {(form.account_type === 'bkash' || form.account_type === 'nagad' || form.account_type === 'rocket') ? (
                            <>
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-holder-name">{__('Holder Name', 'manfi-expense-tracker')}</label>
                                    <input id="manfiet-holder-name" className="manfiet-input" value={form.holder_name} onChange={(e) => updateField('holder_name', e.target.value)} placeholder={__('Account holder full name', 'manfi-expense-tracker')} />
                                </div>
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-account-number">{__('Mobile Number', 'manfi-expense-tracker')}</label>
                                    <input id="manfiet-account-number" className="manfiet-input" value={form.account_number} onChange={(e) => updateField('account_number', e.target.value)} placeholder={__('e.g. 01XXXXXXXXX', 'manfi-expense-tracker')} />
                                </div>
                            </>
                        ) : (
                            /* For banks, card, and other show full fields */
                            <>
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-provider-name">{__('Provider / Bank Name', 'manfi-expense-tracker')}</label>
                                    <input id="manfiet-provider-name" className="manfiet-input" value={form.provider_name} onChange={(e) => updateField('provider_name', e.target.value)} placeholder={__('Example: Prime Bank', 'manfi-expense-tracker')} />
                                </div>
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-account-number">{__('Account / Number', 'manfi-expense-tracker')}</label>
                                    <input id="manfiet-account-number" className="manfiet-input" value={form.account_number} onChange={(e) => updateField('account_number', e.target.value)} placeholder={__('Account number, wallet number, or card number', 'manfi-expense-tracker')} />
                                </div>
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-holder-name">{__('Holder Name', 'manfi-expense-tracker')}</label>
                                    <input id="manfiet-holder-name" className="manfiet-input" value={form.holder_name} onChange={(e) => updateField('holder_name', e.target.value)} />
                                </div>
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-routing-number">{__('Routing / Reference', 'manfi-expense-tracker')}</label>
                                    <input id="manfiet-routing-number" className="manfiet-input" value={form.routing_number} onChange={(e) => updateField('routing_number', e.target.value)} />
                                </div>
                                <div className="manfiet-field">
                                    <label className="manfiet-label" htmlFor="manfiet-branch-name">{__('Branch', 'manfi-expense-tracker')}</label>
                                    <input id="manfiet-branch-name" className="manfiet-input" value={form.branch_name} onChange={(e) => updateField('branch_name', e.target.value)} />
                                </div>
                            </>
                        )}
                    </div>

                    <div className="manfiet-field">
                        <label className="manfiet-label" htmlFor="manfiet-account-note">{__('Note', 'manfi-expense-tracker')}</label>
                        <textarea id="manfiet-account-note" className="manfiet-input" rows="3" value={form.note} onChange={(e) => updateField('note', e.target.value)} placeholder={__('Optional note for invoice display or internal use', 'manfi-expense-tracker')} />
                    </div>

                    <label className="manfiet-check-row">
                        <input type="checkbox" checked={form.is_default} onChange={(e) => updateField('is_default', e.target.checked)} />
                        <span>{__('Mark as default account', 'manfi-expense-tracker')}</span>
                    </label>

                    <div className="manfiet-form-row manfiet-form-row-end">
                        <button type="submit" className="manfiet-button manfiet-button-primary" disabled={saving}>{saving ? __('Saving...', 'manfi-expense-tracker') : (editingId ? __('Update Account', 'manfi-expense-tracker') : __('Save Account', 'manfi-expense-tracker'))}</button>
                        <button type="button" className="manfiet-button manfiet-button-secondary" onClick={resetForm}>{__('Reset', 'manfi-expense-tracker')}</button>
                    </div>
                </form>
            </div>
            )}

            {!isCreateMode && (
            <div className="manfiet-card">
                <div className="manfiet-card-head-row manfiet-mb-14">
                    <h3 className="manfiet-card-title manfiet-card-title-no-margin">{__('Saved Accounts', 'manfi-expense-tracker')}</h3>
                </div>
                {loading ? (
                    <p>{__('Loading accounts...', 'manfi-expense-tracker')}</p>
                ) : accounts.length === 0 ? (
                    <p className="manfiet-text-muted">{__('No financial accounts added yet.', 'manfi-expense-tracker')}</p>
                ) : (
                    <div className="manfiet-table-scroll">
                        <table className="manfiet-table">
                            <thead>
                                <tr>
                                    <th>{__('Type', 'manfi-expense-tracker')}</th>
                                    <th>{__('Provider', 'manfi-expense-tracker')}</th>
                                    <th>{__('Number', 'manfi-expense-tracker')}</th>
                                    <th>{__('Holder', 'manfi-expense-tracker')}</th>
                                    <th>{__('Default', 'manfi-expense-tracker')}</th>
                                    <th>{__('Actions', 'manfi-expense-tracker')}</th>
                                </tr>
                            </thead>
                            <tbody>
                                {accounts.map((account) => (
                                    <tr key={account.id}>
                                        <td>{account.account_type}</td>
                                        <td>{account.provider_name}</td>
                                        <td>{account.account_number}</td>
                                        <td>{account.holder_name || '-'}</td>
                                        <td>{account.is_default ? __('Yes', 'manfi-expense-tracker') : __('No', 'manfi-expense-tracker')}</td>
                                        <td>
                                            <button type="button" className="manfiet-button manfiet-button-info manfiet-button-sm" onClick={() => { window.location.href = `${createPageUrl}&account_id=${account.id}`; }}>{__('Edit', 'manfi-expense-tracker')}</button>
                                            <button type="button" className="manfiet-button manfiet-button-danger manfiet-button-sm manfiet-ml-8" onClick={() => deleteAccount(account.id)} disabled={saving}>{__('Delete', 'manfi-expense-tracker')}</button>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>
            )}
        </div>
    );
};

export default FinancialAccounts;
