import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useToast } from '../App';
import api from '../utils/api';
import PasswordField from '../components/PasswordField';
import LoadingState from '../components/LoadingState';

const CustomerEditor = () => {
    const navigate = useNavigate();
    const { id: customerId } = useParams();
    const { showSuccess, showError } = useToast();
    const [loading, setLoading] = useState(!!customerId);
    const [saving, setSaving] = useState(false);
    const [passwordValid, setPasswordValid] = useState(true);

    const [formData, setFormData] = useState({
        username: '',
        email: '',
        first_name: '',
        last_name: '',
        role: 'customer',
        password: '',
        billing: {
            first_name: '',
            last_name: '',
            company: '',
            address_1: '',
            address_2: '',
            city: '',
            state: '',
            postcode: '',
            country: 'US',
            phone: '',
            email: ''
        },
        shipping: {
            first_name: '',
            last_name: '',
            company: '',
            address_1: '',
            address_2: '',
            city: '',
            state: '',
            postcode: '',
            country: 'US'
        }
    });

    useEffect(() => {
        if (customerId) {
            loadCustomer();
        }
    }, [customerId]);

    const loadCustomer = async () => {
        try {
            setLoading(true);
            const response = await api.get(`/customers/${customerId}`);
            
            if (response.success) {
                const customer = response.customer;
                setFormData({
                    username: customer.username || '',
                    email: customer.email || '',
                    first_name: customer.first_name || '',
                    last_name: customer.last_name || '',
                    role: customer.role || 'customer',
                    password: '',
                    billing: customer.billing || formData.billing,
                    shipping: customer.shipping || formData.shipping
                });
            }
        } catch (err) {
            showError('Failed to load customer: ' + err.message);
        } finally {
            setLoading(false);
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        
        try {
            setSaving(true);
            
            if (customerId) {
                const response = await api.put(`/customers/${customerId}`, formData);
                if (response.success) {
                    showSuccess('Customer updated successfully');
                    navigate('/customers');
                } else {
                    throw new Error(response.message || 'Failed to update customer');
                }
            } else {
                const response = await api.post('/customers', formData);
                if (response.success) {
                    showSuccess('Customer created successfully');
                    navigate('/customers');
                } else {
                    throw new Error(response.message || 'Failed to create customer');
                }
            }
        } catch (err) {
            showError(err.message);
        } finally {
            setSaving(false);
        }
    };

    const handleChange = (field, value) => {
        setFormData(prev => ({
            ...prev,
            [field]: value
        }));
    };

    const handleAddressChange = (type, field, value) => {
        setFormData(prev => ({
            ...prev,
            [type]: {
                ...prev[type],
                [field]: value
            }
        }));
    };

    const copyBillingToShipping = () => {
        setFormData(prev => ({
            ...prev,
            shipping: { ...prev.billing }
        }));
    };

    if (loading) {
        return <LoadingState message="Loading customer..." fullScreen />;
    }

    return (
        <div className="page customer-editor-page">
            <div className="page-container">
                {/* Header */}
                <div className="page-header">
                    <div className="page-title">
                        <button className="btn-back" onClick={() => navigate('/customers')}>
                            ← Back to Customers
                        </button>
                        <div>
                            <h1>{customerId ? 'Edit Customer' : 'Add New Customer'}</h1>
                            <p>{customerId ? `Update customer #${customerId}` : 'Create a new customer account'}</p>
                        </div>
                    </div>
                    <div className="page-actions">
                        <button 
                            className="btn btn-secondary"
                            onClick={() => navigate('/customers')}
                        >
                            Cancel
                        </button>
                        <button 
                            className="btn btn-primary"
                            onClick={handleSubmit}
                            disabled={saving || !passwordValid}
                        >
                            {saving ? 'Saving...' : customerId ? 'Update Customer' : 'Create Customer'}
                        </button>
                    </div>
                </div>

                <form onSubmit={handleSubmit}>
                    <div className="editor-grid">
                        {/* Account Information */}
                        <div className="editor-section">
                            <div className="section-header">
                                <h3>Account Information</h3>
                            </div>
                            <div className="section-content">
                                <div className="form-row">
                                    <div className="form-group">
                                        <label>Username *</label>
                                        <input
                                            type="text"
                                            value={formData.username}
                                            onChange={(e) => handleChange('username', e.target.value)}
                                            disabled={!!customerId}
                                            required
                                        />
                                        {customerId && <small>Usernames cannot be changed</small>}
                                    </div>
                                    <div className="form-group">
                                        <label>Email *</label>
                                        <input
                                            type="email"
                                            value={formData.email}
                                            onChange={(e) => handleChange('email', e.target.value)}
                                            required
                                        />
                                    </div>
                                </div>

                                <div className="form-row">
                                    <div className="form-group">
                                        <label>First Name</label>
                                        <input
                                            type="text"
                                            value={formData.first_name}
                                            onChange={(e) => handleChange('first_name', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>Last Name</label>
                                        <input
                                            type="text"
                                            value={formData.last_name}
                                            onChange={(e) => handleChange('last_name', e.target.value)}
                                        />
                                    </div>
                                </div>

                                <div className="form-row">
                                    <div className="form-group">
                                        <label>Role</label>
                                        <select
                                            value={formData.role}
                                            onChange={(e) => handleChange('role', e.target.value)}
                                        >
                                            <option value="customer">Customer</option>
                                            <option value="shop_manager">Shop Manager</option>
                                            <option value="subscriber">Subscriber</option>
                                            <option value="contributor">Contributor</option>
                                            <option value="author">Author</option>
                                            <option value="editor">Editor</option>
                                            <option value="administrator">Administrator</option>
                                        </select>
                                    </div>
                                    <PasswordField
                                        label={customerId ? 'New Password (leave blank to keep current)' : 'Password'}
                                        value={formData.password}
                                        onChange={(value) => handleChange('password', value)}
                                        onValidityChange={setPasswordValid}
                                        required={!customerId}
                                    />
                                </div>
                            </div>
                        </div>

                        {/* Billing Address */}
                        <div className="editor-section">
                            <div className="section-header">
                                <h3>Billing Address</h3>
                            </div>
                            <div className="section-content">
                                <div className="form-row">
                                    <div className="form-group">
                                        <label>First Name</label>
                                        <input
                                            type="text"
                                            value={formData.billing.first_name}
                                            onChange={(e) => handleAddressChange('billing', 'first_name', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>Last Name</label>
                                        <input
                                            type="text"
                                            value={formData.billing.last_name}
                                            onChange={(e) => handleAddressChange('billing', 'last_name', e.target.value)}
                                        />
                                    </div>
                                </div>

                                <div className="form-group">
                                    <label>Company</label>
                                    <input
                                        type="text"
                                        value={formData.billing.company}
                                        onChange={(e) => handleAddressChange('billing', 'company', e.target.value)}
                                    />
                                </div>

                                <div className="form-group">
                                    <label>Address Line 1</label>
                                    <input
                                        type="text"
                                        value={formData.billing.address_1}
                                        onChange={(e) => handleAddressChange('billing', 'address_1', e.target.value)}
                                    />
                                </div>

                                <div className="form-group">
                                    <label>Address Line 2</label>
                                    <input
                                        type="text"
                                        value={formData.billing.address_2}
                                        onChange={(e) => handleAddressChange('billing', 'address_2', e.target.value)}
                                    />
                                </div>

                                <div className="form-row">
                                    <div className="form-group">
                                        <label>City</label>
                                        <input
                                            type="text"
                                            value={formData.billing.city}
                                            onChange={(e) => handleAddressChange('billing', 'city', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>State / County</label>
                                        <input
                                            type="text"
                                            value={formData.billing.state}
                                            onChange={(e) => handleAddressChange('billing', 'state', e.target.value)}
                                        />
                                    </div>
                                </div>

                                <div className="form-row">
                                    <div className="form-group">
                                        <label>Postcode / ZIP</label>
                                        <input
                                            type="text"
                                            value={formData.billing.postcode}
                                            onChange={(e) => handleAddressChange('billing', 'postcode', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>Country</label>
                                        <input
                                            type="text"
                                            value={formData.billing.country}
                                            onChange={(e) => handleAddressChange('billing', 'country', e.target.value)}
                                        />
                                    </div>
                                </div>

                                <div className="form-row">
                                    <div className="form-group">
                                        <label>Phone</label>
                                        <input
                                            type="tel"
                                            value={formData.billing.phone}
                                            onChange={(e) => handleAddressChange('billing', 'phone', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>Email</label>
                                        <input
                                            type="email"
                                            value={formData.billing.email}
                                            onChange={(e) => handleAddressChange('billing', 'email', e.target.value)}
                                        />
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* Shipping Address */}
                        <div className="editor-section">
                            <div className="section-header">
                                <h3>Shipping Address</h3>
                                <button 
                                    type="button"
                                    className="btn btn-sm btn-secondary"
                                    onClick={copyBillingToShipping}
                                >
                                    Copy from Billing
                                </button>
                            </div>
                            <div className="section-content">
                                <div className="form-row">
                                    <div className="form-group">
                                        <label>First Name</label>
                                        <input
                                            type="text"
                                            value={formData.shipping.first_name}
                                            onChange={(e) => handleAddressChange('shipping', 'first_name', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>Last Name</label>
                                        <input
                                            type="text"
                                            value={formData.shipping.last_name}
                                            onChange={(e) => handleAddressChange('shipping', 'last_name', e.target.value)}
                                        />
                                    </div>
                                </div>

                                <div className="form-group">
                                    <label>Company</label>
                                    <input
                                        type="text"
                                        value={formData.shipping.company}
                                        onChange={(e) => handleAddressChange('shipping', 'company', e.target.value)}
                                    />
                                </div>

                                <div className="form-group">
                                    <label>Address Line 1</label>
                                    <input
                                        type="text"
                                        value={formData.shipping.address_1}
                                        onChange={(e) => handleAddressChange('shipping', 'address_1', e.target.value)}
                                    />
                                </div>

                                <div className="form-group">
                                    <label>Address Line 2</label>
                                    <input
                                        type="text"
                                        value={formData.shipping.address_2}
                                        onChange={(e) => handleAddressChange('shipping', 'address_2', e.target.value)}
                                    />
                                </div>

                                <div className="form-row">
                                    <div className="form-group">
                                        <label>City</label>
                                        <input
                                            type="text"
                                            value={formData.shipping.city}
                                            onChange={(e) => handleAddressChange('shipping', 'city', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>State / County</label>
                                        <input
                                            type="text"
                                            value={formData.shipping.state}
                                            onChange={(e) => handleAddressChange('shipping', 'state', e.target.value)}
                                        />
                                    </div>
                                </div>

                                <div className="form-row">
                                    <div className="form-group">
                                        <label>Postcode / ZIP</label>
                                        <input
                                            type="text"
                                            value={formData.shipping.postcode}
                                            onChange={(e) => handleAddressChange('shipping', 'postcode', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>Country</label>
                                        <input
                                            type="text"
                                            value={formData.shipping.country}
                                            onChange={(e) => handleAddressChange('shipping', 'country', e.target.value)}
                                        />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    );
};

export default CustomerEditor;
