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 emptyClient = () => ({
    id: null,
    client_name: '',
    contact_person: '',
    phones: [''],
    emails: [''],
    address: '',
});

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

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

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

    const createPageUrl = `${window.location.pathname}?page=manfiet-clients-create`;
    const dashboardPageUrl = `${window.location.pathname}?page=manfiet-clients`;
    const clientIdParam = new URLSearchParams(window.location.search).get('client_id') || '';

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

    const updatePhoneField = (index, value) => {
        setForm((current) => {
            const phones = [...current.phones];
            phones[index] = value;
            return { ...current, phones };
        });
    };

    const addPhoneField = () => {
        setForm((current) => ({
            ...current,
            phones: [...current.phones, ''],
        }));
    };

    const removePhoneField = (index) => {
        setForm((current) => ({
            ...current,
            phones: current.phones.length > 1 ? current.phones.filter((_, i) => i !== index) : [''],
        }));
    };

    const updateEmailField = (index, value) => {
        setForm((current) => {
            const emails = [...current.emails];
            emails[index] = value;
            return { ...current, emails };
        });
    };

    const addEmailField = () => {
        setForm((current) => ({
            ...current,
            emails: [...current.emails, ''],
        }));
    };

    const removeEmailField = (index) => {
        setForm((current) => ({
            ...current,
            emails: current.emails.length > 1 ? current.emails.filter((_, i) => i !== index) : [''],
        }));
    };

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

    const editClient = (client) => {
        setEditingId(client.id);
        const phones = Array.isArray(client.phones) && client.phones.length > 0
            ? client.phones
            : (client.phone ? [client.phone] : ['']);

        let emails = [];
        if (Array.isArray(client.emails) && client.emails.length > 0) {
            emails = client.emails;
        } else {
            if (client.email) emails.push(client.email);
            if (client.email2) emails.push(client.email2);
        }
        if (emails.length === 0) emails = [''];

        setForm({
            id: client.id,
            client_name: client.client_name || '',
            contact_person: client.contact_person || '',
            phones: phones,
            emails: emails,
            address: client.address || '',
        });
        setMessage(__('Editing client', 'manfi-expense-tracker'));
        setError('');
        window.scrollTo({ top: 0, behavior: 'smooth' });
    };

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

        const selectedClient = clients.find((client) => String(client.id) === String(clientIdParam));
        if (selectedClient && editingId !== selectedClient.id) {
            editClient(selectedClient);
        }
    }, [clientIdParam, clients, editingId, isCreateMode, loading]);

    const deleteClient = (clientId) => {
        if (!window.confirm(__('Delete this client?', 'manfi-expense-tracker'))) {
            return;
        }

        setSaving(true);
        setError('');
        requestJson(`${restBase}clients/${clientId}`, { method: 'DELETE' })
            .then(() => {
                setMessage(__('Client deleted.', 'manfi-expense-tracker'));
                loadClients();
                if (editingId === clientId) {
                    resetForm();
                }
            })
            .catch((requestError) => {
                setError(requestError.message || __('Failed to delete client.', 'manfi-expense-tracker'));
            })
            .finally(() => setSaving(false));
    };

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

        if (!form.client_name.trim()) {
            setError(__('Client/Company name is required.', 'manfi-expense-tracker'));
            setSaving(false);
            return;
        }

        const cleanPhones = form.phones.map((p) => p.trim()).filter(Boolean);
        const cleanEmails = form.emails.map((e) => e.trim()).filter(Boolean);

        const payload = {
            client_name: form.client_name.trim(),
            contact_person: form.contact_person.trim(),
            phones: cleanPhones,
            emails: cleanEmails,
            phone: cleanPhones[0] || '',
            email: cleanEmails[0] || '',
            email2: cleanEmails[1] || '',
            address: form.address.trim(),
        };

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

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

    return (
        <div className="manfiet-page-shell manfiet-page-shell-wide manfiet-clients-shell">
            <div className="manfiet-page-hero">
                <div className='left-section'>
                    <h1 className="manfiet-page-title">{isCreateMode ? __('Create Client', 'manfi-expense-tracker') : __('Clients', 'manfi-expense-tracker')}</h1>
                    <p className="manfiet-page-subtitle">{isCreateMode ? __('Add a client record for reuse in invoices.', 'manfi-expense-tracker') : __('Store your customer or client information 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 Clients', 'manfi-expense-tracker')}
                        </button>
                    ) : (
                        <button type="button" className="manfiet-button manfiet-button-primary" onClick={() => { window.location.href = createPageUrl; }}>
                            {__('Create Client', 'manfi-expense-tracker')}
                        </button>
                    )}
                </div>
            </div>

            {isCreateMode && (
            <div className="manfiet-card manfiet-mb-16">
                <h3 className="manfiet-card-title">{editingId ? __('Edit Client', 'manfi-expense-tracker') : __('Add New Client', '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={submitClient} className="manfiet-form-stack">
                    <div className="manfiet-form-grid">
                        <div className="manfiet-field">
                            <label className="manfiet-label" htmlFor="manfiet-client-name">
                                {__('Client / Company Name', 'manfi-expense-tracker')} <span className="manfiet-required">*</span>
                            </label>
                            <input
                                id="manfiet-client-name"
                                className="manfiet-input"
                                value={form.client_name}
                                onChange={(e) => updateField('client_name', e.target.value)}
                                placeholder={__('e.g. Acme Corporation', 'manfi-expense-tracker')}
                                required
                            />
                        </div>

                        <div className="manfiet-field">
                            <label className="manfiet-label" htmlFor="manfiet-contact-person">
                                {__('Contact Person Name', 'manfi-expense-tracker')}
                            </label>
                            <input
                                id="manfiet-contact-person"
                                className="manfiet-input"
                                value={form.contact_person}
                                onChange={(e) => updateField('contact_person', e.target.value)}
                                placeholder={__('e.g. John Doe', 'manfi-expense-tracker')}
                            />
                        </div>
                    </div>

                    {/* Cloneable Phone Numbers */}
                    <div className="manfiet-card manfiet-card-inset manfiet-mb-14">
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                            <label className="manfiet-label" style={{ margin: 0, fontWeight: '600' }}>
                                {__('Phone Number(s)', 'manfi-expense-tracker')}
                            </label>
                            <button
                                type="button"
                                className="manfiet-button manfiet-button-secondary manfiet-button-sm"
                                onClick={addPhoneField}
                            >
                                + {__('Add Phone', 'manfi-expense-tracker')}
                            </button>
                        </div>
                        <div className="manfiet-form-stack">
                            {form.phones.map((phoneVal, pIndex) => (
                                <div key={`phone-${pIndex}`} style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                                    <input
                                        className="manfiet-input"
                                        style={{ flex: 1 }}
                                        value={phoneVal}
                                        onChange={(e) => updatePhoneField(pIndex, e.target.value)}
                                        placeholder={__('e.g. +1 555-0199', 'manfi-expense-tracker')}
                                    />
                                    {form.phones.length > 1 && (
                                        <button
                                            type="button"
                                            className="manfiet-button manfiet-button-danger manfiet-button-sm"
                                            onClick={() => removePhoneField(pIndex)}
                                        >
                                            {__('Remove', 'manfi-expense-tracker')}
                                        </button>
                                    )}
                                </div>
                            ))}
                        </div>
                    </div>

                    {/* Cloneable Email Addresses */}
                    <div className="manfiet-card manfiet-card-inset manfiet-mb-14">
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                            <label className="manfiet-label" style={{ margin: 0, fontWeight: '600' }}>
                                {__('Email Address(es)', 'manfi-expense-tracker')}
                            </label>
                            <button
                                type="button"
                                className="manfiet-button manfiet-button-secondary manfiet-button-sm"
                                onClick={addEmailField}
                            >
                                + {__('Add Email', 'manfi-expense-tracker')}
                            </button>
                        </div>
                        <div className="manfiet-form-stack">
                            {form.emails.map((emailVal, eIndex) => (
                                <div key={`email-${eIndex}`} style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                                    <input
                                        className="manfiet-input"
                                        type="email"
                                        style={{ flex: 1 }}
                                        value={emailVal}
                                        onChange={(e) => updateEmailField(eIndex, e.target.value)}
                                        placeholder={__('client@example.com', 'manfi-expense-tracker')}
                                    />
                                    {form.emails.length > 1 && (
                                        <button
                                            type="button"
                                            className="manfiet-button manfiet-button-danger manfiet-button-sm"
                                            onClick={() => removeEmailField(eIndex)}
                                        >
                                            {__('Remove', 'manfi-expense-tracker')}
                                        </button>
                                    )}
                                </div>
                            ))}
                        </div>
                    </div>

                    <div className="manfiet-field">
                        <label className="manfiet-label" htmlFor="manfiet-address">{__('Address', 'manfi-expense-tracker')}</label>
                        <textarea
                            id="manfiet-address"
                            className="manfiet-input"
                            rows="3"
                            value={form.address}
                            onChange={(e) => updateField('address', e.target.value)}
                            placeholder={__('Street address, city, state, postal code', 'manfi-expense-tracker')}
                        />
                    </div>

                    <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 Client', 'manfi-expense-tracker') : __('Save Client', '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 Clients', 'manfi-expense-tracker')}</h3>
                </div>
                {loading ? (
                    <p>{__('Loading clients...', 'manfi-expense-tracker')}</p>
                ) : clients.length === 0 ? (
                    <p className="manfiet-text-muted">{__('No clients added yet.', 'manfi-expense-tracker')}</p>
                ) : (
                    <div className="manfiet-table-scroll">
                        <table className="manfiet-table">
                            <thead>
                                <tr>
                                    <th>{__('Company / Client', 'manfi-expense-tracker')}</th>
                                    <th>{__('Contact Person', 'manfi-expense-tracker')}</th>
                                    <th>{__('Phone(s)', 'manfi-expense-tracker')}</th>
                                    <th>{__('Email(s)', 'manfi-expense-tracker')}</th>
                                    <th>{__('Address', 'manfi-expense-tracker')}</th>
                                    <th>{__('Actions', 'manfi-expense-tracker')}</th>
                                </tr>
                            </thead>
                            <tbody>
                                {clients.map((client) => {
                                    const displayPhones = Array.isArray(client.phones) && client.phones.length > 0
                                        ? client.phones.join(', ')
                                        : (client.phone || '-');
                                    const displayEmails = Array.isArray(client.emails) && client.emails.length > 0
                                        ? client.emails.join(', ')
                                        : array_filter_join([client.email, client.email2]);

                                    return (
                                        <tr key={client.id}>
                                            <td><strong>{client.client_name}</strong></td>
                                            <td>{client.contact_person || '-'}</td>
                                            <td>{displayPhones}</td>
                                            <td>{displayEmails}</td>
                                            <td>{client.address ? client.address.substring(0, 40) + (client.address.length > 40 ? '...' : '') : '-'}</td>
                                            <td>
                                                <button type="button" className="manfiet-button manfiet-button-info manfiet-button-sm" onClick={() => { window.location.href = `${createPageUrl}&client_id=${client.id}`; }}>
                                                    {__('Edit', 'manfi-expense-tracker')}
                                                </button>
                                                <button type="button" className="manfiet-button manfiet-button-danger manfiet-button-sm manfiet-ml-8" onClick={() => deleteClient(client.id)} disabled={saving}>
                                                    {__('Delete', 'manfi-expense-tracker')}
                                                </button>
                                            </td>
                                        </tr>
                                    );
                                })}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>
            )}
        </div>
    );
};

const array_filter_join = (arr) => {
    const valid = (arr || []).filter(Boolean);
    return valid.length > 0 ? valid.join(', ') : '-';
};

export default ClientsManager;
