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 parseList = (val) => {
    if (!val) return [''];
    if (Array.isArray(val)) return val.length ? val : [''];
    const parts = String(val).split(/[\r\n,]+/).map((s) => s.trim()).filter(Boolean);
    return parts.length ? parts : [''];
};

const emptyVendor = () => ({
    id: null,
    company_name: '',
    phones: [''],
    emails: [''],
    websites: [''],
    address: '',
    logos: [''],
    tagline: '',
});

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

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

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

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

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

    // Repeatable Phones handlers
    const addPhone = () => setForm((curr) => ({ ...curr, phones: [...curr.phones, ''] }));
    const updatePhone = (index, value) => setForm((curr) => ({ ...curr, phones: curr.phones.map((p, i) => (i === index ? value : p)) }));
    const removePhone = (index) => setForm((curr) => ({ ...curr, phones: curr.phones.filter((_, i) => i !== index) }));

    // Repeatable Emails handlers
    const addEmail = () => setForm((curr) => ({ ...curr, emails: [...curr.emails, ''] }));
    const updateEmail = (index, value) => setForm((curr) => ({ ...curr, emails: curr.emails.map((e, i) => (i === index ? value : e)) }));
    const removeEmail = (index) => setForm((curr) => ({ ...curr, emails: curr.emails.filter((_, i) => i !== index) }));

    // Repeatable Websites handlers
    const addWebsite = () => setForm((curr) => ({ ...curr, websites: [...curr.websites, ''] }));
    const updateWebsite = (index, value) => setForm((curr) => ({ ...curr, websites: curr.websites.map((w, i) => (i === index ? value : w)) }));
    const removeWebsite = (index) => setForm((curr) => ({ ...curr, websites: curr.websites.filter((_, i) => i !== index) }));

    // Repeatable Logos handlers
    const addLogo = () => setForm((curr) => ({ ...curr, logos: [...curr.logos, ''] }));
    const updateLogo = (index, value) => setForm((curr) => ({ ...curr, logos: curr.logos.map((l, i) => (i === index ? value : l)) }));
    const removeLogo = (index) => setForm((curr) => ({ ...curr, logos: curr.logos.filter((_, i) => i !== index) }));

    const handleUploadLogoSlot = (index, event) => {
        const file = event.target.files?.[0];
        if (!file) return;

        setUploadingLogoIdx(index);
        const formData = new FormData();
        formData.append('file', file);

        fetch('/wp-json/wp/v2/media', {
            method: 'POST',
            body: formData,
            headers: appData.restNonce ? { 'X-WP-Nonce': appData.restNonce } : {},
            credentials: 'same-origin',
        })
            .then((res) => res.json())
            .then((data) => {
                if (data.source_url) {
                    updateLogo(index, data.source_url);
                    setMessage(__('Logo uploaded successfully.', 'manfi-expense-tracker'));
                } else {
                    throw new Error(__('Upload failed: no URL returned', 'manfi-expense-tracker'));
                }
            })
            .catch((err) => {
                setError(err.message || __('Failed to upload logo.', 'manfi-expense-tracker'));
            })
            .finally(() => setUploadingLogoIdx(null));
    };

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

    const editVendor = (vendor) => {
        setEditingId(vendor.id);
        setForm({
            id: vendor.id,
            company_name: vendor.company_name || '',
            phones: parseList(vendor.phone),
            emails: parseList(vendor.email),
            websites: parseList(vendor.website_url),
            address: vendor.address || '',
            logos: parseList(vendor.logo_url),
            tagline: vendor.tagline || '',
        });
        setMessage(__('Editing vendor', 'manfi-expense-tracker'));
        setError('');
        window.scrollTo({ top: 0, behavior: 'smooth' });
    };

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

        const selectedVendor = vendors.find((vendor) => String(vendor.id) === String(vendorIdParam));
        if (selectedVendor && editingId !== selectedVendor.id) {
            editVendor(selectedVendor);
        }
    }, [editingId, isCreateMode, loading, vendorIdParam, vendors]);

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

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

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

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

        const payload = {
            company_name: form.company_name.trim(),
            phone: form.phones.map((s) => s.trim()).filter(Boolean).join(', '),
            email: form.emails.map((s) => s.trim()).filter(Boolean).join(', '),
            website_url: form.websites.map((s) => s.trim()).filter(Boolean).join(', '),
            address: form.address.trim(),
            logo_url: form.logos.map((s) => s.trim()).filter(Boolean).join(', '),
            tagline: form.tagline.trim(),
        };

        const isUpdate = Boolean(editingId);
        const url = isUpdate ? `${restBase}vendors/${editingId}` : `${restBase}vendors`;
        const method = isUpdate ? 'PUT' : 'POST';

        requestJson(url, {
            method,
            body: JSON.stringify(payload),
        })
            .then((savedVendor) => {
                setMessage(isUpdate ? __('Vendor updated successfully.', 'manfi-expense-tracker') : __('Vendor created successfully.', 'manfi-expense-tracker'));
                loadVendors();
                if (!isUpdate) {
                    resetForm();
                } else {
                    editVendor(savedVendor);
                }
            })
            .catch((requestError) => {
                setError(requestError.message || __('Failed to save vendor.', 'manfi-expense-tracker'));
            })
            .finally(() => setSaving(false));
    };

    return (
        <div className="manfiet-wrap">
            <div className="manfiet-header" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
                <div>
                    <h1 className="manfiet-title">{isCreateMode ? __('Create Vendor', 'manfi-expense-tracker') : __('Vendor Manager', 'manfi-expense-tracker')}</h1>
                    <p className="manfiet-subtitle">{__('Manage vendor / agency profiles used in invoices. Add cloneable partner logos, phone numbers, emails & websites for joint collaborations.', 'manfi-expense-tracker')}</p>
                </div>
                {isCreateMode ? (
                    <a href={dashboardPageUrl} className="manfiet-button manfiet-button-secondary">
                        {__('Back to Vendors', 'manfi-expense-tracker')}
                    </a>
                ) : (
                    <a href={createPageUrl} className="manfiet-button manfiet-button-primary">
                        + {__('Create Vendor', 'manfi-expense-tracker')}
                    </a>
                )}
            </div>

            {error && <div className="manfiet-alert manfiet-alert-error" style={{ marginBottom: '16px' }}>{error}</div>}
            {message && <div className="manfiet-alert manfiet-alert-success" style={{ marginBottom: '16px' }}>{message}</div>}

            {isCreateMode && (
            <div className="manfiet-card" style={{ marginBottom: '24px' }}>
                <h3 className="manfiet-card-title">{editingId ? __('Edit Vendor', 'manfi-expense-tracker') : __('Add New Vendor', 'manfi-expense-tracker')}</h3>

                <form onSubmit={submitVendor} className="manfiet-form">
                    <div className="manfiet-field" style={{ marginBottom: '20px' }}>
                        <label className="manfiet-label" htmlFor="manfiet-company-name">
                            {__('Company / Joint Agency Name', 'manfi-expense-tracker')} <span style={{ color: '#dc2626' }}>*</span>
                        </label>
                        <input
                            id="manfiet-company-name"
                            className="manfiet-input"
                            value={form.company_name}
                            onChange={(e) => updateField('company_name', e.target.value)}
                            placeholder={__('e.g. Digital Agency Ltd', 'manfi-expense-tracker')}
                            required
                        />
                    </div>

                    {/* Cloneable Phone Numbers */}
                    <div className="manfiet-card manfiet-card-inset" style={{ marginBottom: '20px', background: '#fafafa', border: '1px solid #e2e8f0', padding: '16px', borderRadius: '8px' }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
                            <label className="manfiet-label" style={{ margin: 0, fontWeight: '600', color: '#1e293b' }}>
                                📞 {__('Phone Numbers (Cloneable)', 'manfi-expense-tracker')}
                            </label>
                            <button
                                type="button"
                                className="manfiet-button manfiet-button-secondary"
                                style={{ padding: '4px 12px', fontSize: '13px', display: 'flex', alignItems: 'center', gap: '4px' }}
                                onClick={addPhone}
                            >
                                + {__('Add Another Phone', 'manfi-expense-tracker')}
                            </button>
                        </div>
                        {form.phones.map((phone, idx) => (
                            <div key={idx} style={{ display: 'flex', gap: '8px', marginBottom: '8px' }}>
                                <input
                                    className="manfiet-input"
                                    value={phone}
                                    onChange={(e) => updatePhone(idx, e.target.value)}
                                    placeholder={__(`Phone ${idx + 1} (e.g. +1 555-0199)`, 'manfi-expense-tracker')}
                                />
                                {form.phones.length > 1 && (
                                    <button
                                        type="button"
                                        onClick={() => removePhone(idx)}
                                        style={{ background: '#fee2e2', color: '#b91c1c', border: '1px solid #fca5a5', padding: '0 14px', borderRadius: '6px', cursor: 'pointer', fontWeight: 'bold' }}
                                        title={__('Remove phone', 'manfi-expense-tracker')}
                                    >
                                        ✕
                                    </button>
                                )}
                            </div>
                        ))}
                    </div>

                    {/* Cloneable Email Addresses */}
                    <div className="manfiet-card manfiet-card-inset" style={{ marginBottom: '20px', background: '#fafafa', border: '1px solid #e2e8f0', padding: '16px', borderRadius: '8px' }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
                            <label className="manfiet-label" style={{ margin: 0, fontWeight: '600', color: '#1e293b' }}>
                                ✉️ {__('Email Addresses (Cloneable)', 'manfi-expense-tracker')}
                            </label>
                            <button
                                type="button"
                                className="manfiet-button manfiet-button-secondary"
                                style={{ padding: '4px 12px', fontSize: '13px', display: 'flex', alignItems: 'center', gap: '4px' }}
                                onClick={addEmail}
                            >
                                + {__('Add Another Email', 'manfi-expense-tracker')}
                            </button>
                        </div>
                        {form.emails.map((email, idx) => (
                            <div key={idx} style={{ display: 'flex', gap: '8px', marginBottom: '8px' }}>
                                <input
                                    className="manfiet-input"
                                    type="email"
                                    value={email}
                                    onChange={(e) => updateEmail(idx, e.target.value)}
                                    placeholder={__(`Email ${idx + 1} (e.g. contact@example.com)`, 'manfi-expense-tracker')}
                                />
                                {form.emails.length > 1 && (
                                    <button
                                        type="button"
                                        onClick={() => removeEmail(idx)}
                                        style={{ background: '#fee2e2', color: '#b91c1c', border: '1px solid #fca5a5', padding: '0 14px', borderRadius: '6px', cursor: 'pointer', fontWeight: 'bold' }}
                                        title={__('Remove email', 'manfi-expense-tracker')}
                                    >
                                        ✕
                                    </button>
                                )}
                            </div>
                        ))}
                    </div>

                    {/* Cloneable Website URLs */}
                    <div className="manfiet-card manfiet-card-inset" style={{ marginBottom: '20px', background: '#fafafa', border: '1px solid #e2e8f0', padding: '16px', borderRadius: '8px' }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
                            <label className="manfiet-label" style={{ margin: 0, fontWeight: '600', color: '#1e293b' }}>
                                🌐 {__('Website URLs (Cloneable)', 'manfi-expense-tracker')}
                            </label>
                            <button
                                type="button"
                                className="manfiet-button manfiet-button-secondary"
                                style={{ padding: '4px 12px', fontSize: '13px', display: 'flex', alignItems: 'center', gap: '4px' }}
                                onClick={addWebsite}
                            >
                                + {__('Add Another Website', 'manfi-expense-tracker')}
                            </button>
                        </div>
                        {form.websites.map((site, idx) => (
                            <div key={idx} style={{ display: 'flex', gap: '8px', marginBottom: '8px' }}>
                                <input
                                    className="manfiet-input"
                                    type="url"
                                    value={site}
                                    onChange={(e) => updateWebsite(idx, e.target.value)}
                                    placeholder={__(`Website ${idx + 1} (e.g. https://example.com)`, 'manfi-expense-tracker')}
                                />
                                {form.websites.length > 1 && (
                                    <button
                                        type="button"
                                        onClick={() => removeWebsite(idx)}
                                        style={{ background: '#fee2e2', color: '#b91c1c', border: '1px solid #fca5a5', padding: '0 14px', borderRadius: '6px', cursor: 'pointer', fontWeight: 'bold' }}
                                        title={__('Remove website', 'manfi-expense-tracker')}
                                    >
                                        ✕
                                    </button>
                                )}
                            </div>
                        ))}
                    </div>

                    <div className="manfiet-field" style={{ marginBottom: '20px' }}>
                        <label className="manfiet-label" htmlFor="manfiet-address">{__('Address (Multi-line / Joint Offices)', 'manfi-expense-tracker')}</label>
                        <textarea
                            id="manfiet-address"
                            className="manfiet-input"
                            rows="3"
                            value={form.address}
                            onChange={(e) => updateField('address', e.target.value)}
                            placeholder={__('123 Business Street, Suite 100, City, Country', 'manfi-expense-tracker')}
                        />
                    </div>

                    <div className="manfiet-field" style={{ marginBottom: '20px' }}>
                        <label className="manfiet-label" htmlFor="manfiet-tagline">{__('Tagline / Slogan', 'manfi-expense-tracker')}</label>
                        <input
                            id="manfiet-tagline"
                            className="manfiet-input"
                            value={form.tagline}
                            onChange={(e) => updateField('tagline', e.target.value)}
                            placeholder={__('e.g. Delivering Quality Services', 'manfi-expense-tracker')}
                        />
                    </div>

                    {/* Cloneable Partner Logos */}
                    <div className="manfiet-card manfiet-card-inset" style={{ marginBottom: '24px', background: '#f8fafc', border: '1px solid #cbd5e1', padding: '16px', borderRadius: '8px' }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
                            <div>
                                <h4 className="manfiet-card-subtitle" style={{ margin: 0, fontSize: '15px', color: '#0f172a' }}>🖼️ {__('Company / Partner Logos (Cloneable)', 'manfi-expense-tracker')}</h4>
                                <p style={{ fontSize: '12px', color: '#64748b', margin: '4px 0 0 0' }}>{__('Add logo slots for joint agency partners. Upload images directly or enter image URLs.', 'manfi-expense-tracker')}</p>
                            </div>
                            <button
                                type="button"
                                className="manfiet-button manfiet-button-secondary"
                                style={{ padding: '6px 14px', fontSize: '13px', display: 'flex', alignItems: 'center', gap: '4px' }}
                                onClick={addLogo}
                            >
                                + {__('Add Partner Logo Slot', 'manfi-expense-tracker')}
                            </button>
                        </div>

                        {form.logos.map((logoUrl, idx) => (
                            <div key={idx} style={{ padding: '14px', background: '#ffffff', border: '1px solid #e2e8f0', borderRadius: '8px', marginBottom: '12px', boxShadow: '0 1px 3px rgba(0,0,0,0.04)' }}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                                    <span style={{ fontWeight: '600', fontSize: '13px', color: '#334155' }}>
                                        {__(`Logo Slot #${idx + 1}`, 'manfi-expense-tracker')}
                                    </span>
                                    {form.logos.length > 1 && (
                                        <button
                                            type="button"
                                            onClick={() => removeLogo(idx)}
                                            style={{ background: '#fee2e2', color: '#b91c1c', border: '1px solid #fca5a5', padding: '2px 10px', borderRadius: '4px', fontSize: '12px', cursor: 'pointer', fontWeight: '500' }}
                                        >
                                            {__('Remove Slot', 'manfi-expense-tracker')}
                                        </button>
                                    )}
                                </div>

                                <div style={{ display: 'flex', gap: '10px', alignItems: 'center' }}>
                                    <input
                                        className="manfiet-input"
                                        value={logoUrl}
                                        onChange={(e) => updateLogo(idx, e.target.value)}
                                        placeholder={__('Enter logo URL or upload image on right...', 'manfi-expense-tracker')}
                                        style={{ flex: 1 }}
                                    />
                                    <label style={{ background: '#2563eb', color: '#ffffff', padding: '9px 14px', borderRadius: '6px', cursor: 'pointer', fontSize: '13px', fontWeight: '500', whiteSpace: 'nowrap', display: 'inline-block' }}>
                                        {uploadingLogoIdx === idx ? __('Uploading...', 'manfi-expense-tracker') : __('📤 Upload Logo', 'manfi-expense-tracker')}
                                        <input
                                            type="file"
                                            accept="image/*"
                                            style={{ display: 'none' }}
                                            onChange={(e) => handleUploadLogoSlot(idx, e)}
                                            disabled={uploadingLogoIdx === idx}
                                        />
                                    </label>
                                </div>

                                {logoUrl && (
                                    <div style={{ marginTop: '10px', padding: '8px 12px', background: '#f8fafc', border: '1px solid #e2e8f0', borderRadius: '6px', display: 'flex', alignItems: 'center', gap: '12px' }}>
                                        <img src={logoUrl} alt={`Logo slot ${idx + 1}`} style={{ maxHeight: '50px', width: 'auto', borderRadius: '4px', border: '1px solid #cbd5e1', padding: '2px', background: '#fff' }} />
                                        <span style={{ fontSize: '11px', color: '#64748b', wordBreak: 'break-all' }}>{logoUrl}</span>
                                    </div>
                                )}
                            </div>
                        ))}
                    </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 Vendor', 'manfi-expense-tracker') : __('Save Vendor', '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 Vendors', 'manfi-expense-tracker')}</h3>
                </div>
                {loading ? (
                    <p>{__('Loading vendors...', 'manfi-expense-tracker')}</p>
                ) : vendors.length === 0 ? (
                    <p className="manfiet-text-muted">{__('No vendors added yet.', 'manfi-expense-tracker')}</p>
                ) : (
                    <div className="manfiet-table-scroll">
                        <table className="manfiet-table">
                            <thead>
                                <tr>
                                    <th>{__('Company', 'manfi-expense-tracker')}</th>
                                    <th>{__('Phone', 'manfi-expense-tracker')}</th>
                                    <th>{__('Email', 'manfi-expense-tracker')}</th>
                                    <th>{__('Tagline', 'manfi-expense-tracker')}</th>
                                    <th>{__('Actions', 'manfi-expense-tracker')}</th>
                                </tr>
                            </thead>
                            <tbody>
                                {vendors.map((vendor) => (
                                    <tr key={vendor.id}>
                                        <td>{vendor.company_name}</td>
                                        <td>{vendor.phone || '-'}</td>
                                        <td>{vendor.email || '-'}</td>
                                        <td>{vendor.tagline || '-'}</td>
                                        <td>
                                            <button type="button" className="manfiet-button manfiet-button-info manfiet-button-sm" onClick={() => { window.location.href = `${createPageUrl}&vendor_id=${vendor.id}`; }}>
                                                {__('Edit', 'manfi-expense-tracker')}
                                            </button>
                                            <button type="button" className="manfiet-button manfiet-button-danger manfiet-button-sm manfiet-ml-8" onClick={() => deleteVendor(vendor.id)} disabled={saving}>
                                                {__('Delete', 'manfi-expense-tracker')}
                                            </button>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>
            )}
        </div>
    );
};

export default VendorsManager;
