import { useState, useEffect, useRef } from 'react';
import { useForm, router } from '@inertiajs/react';
import { toast, Toaster } from 'react-hot-toast';
import InputField from '@/Components/Admin/ui/InputField';
import SelectField from '@/Components/Admin/ui/SelectField';
import { usePage } from '@inertiajs/react';

export default function General({ settings }) {
    const { flash } = usePage().props;
    const processedMessages = useRef(new Set());
    const [isSubmitting, setIsSubmitting] = useState(false);

    const { data, setData, post, processing, errors } = useForm({
        site_name: settings?.site_name || '',
        site_description: settings?.site_description || '',
        contact_email: settings?.contact_email || '',
        contact_phone: settings?.contact_phone || '',
        timezone: settings?.timezone || 'UTC',
        date_format: settings?.date_format || 'Y-m-d',
    });

    // Update form data when settings prop changes (e.g., after save)
    useEffect(() => {
        if (settings) {
            setData({
                site_name: settings.site_name || '',
                site_description: settings.site_description || '',
                contact_email: settings.contact_email || '',
                contact_phone: settings.contact_phone || '',
                timezone: settings.timezone || 'UTC',
                date_format: settings.date_format || 'Y-m-d',
            });
        }
    }, [settings]);

    useEffect(() => {
        if (flash?.success) {
            const message = typeof flash.success === 'object' ? flash.success.message : flash.success;
            if (message && !processedMessages.current.has(`success-${message}`)) {
                toast.success(message);
                processedMessages.current.add(`success-${message}`);
            }
        }
        if (flash?.error) {
            const message = typeof flash.error === 'object' ? flash.error.message : flash.error;
            if (message && !processedMessages.current.has(`error-${message}`)) {
                toast.error(message);
                processedMessages.current.add(`error-${message}`);
            }
        }
    }, [flash]);

    const handleSubmit = (e) => {
        e.preventDefault();
        setIsSubmitting(true);
        
        post('/admin/settings/general', {
            onSuccess: () => {
                setIsSubmitting(false);
                // Success toast will be shown by flash message handler in useEffect
                // Reload the page to get updated settings
                router.reload({ only: ['settings'] });
            },
            onError: (errors) => {
                const errorMessage = errors?.message || 'Failed to update settings';
                toast.error(errorMessage);
                setIsSubmitting(false);
            },
            onFinish: () => {
                setIsSubmitting(false);
            }
        });
    };

    const timezones = [
        { value: 'UTC', label: 'UTC' },
        { value: 'Africa/Nairobi', label: 'Nairobi (EAT)' },
        { value: 'America/New_York', label: 'New York (EST)' },
        { value: 'Europe/London', label: 'London (GMT)' },
        { value: 'Asia/Tokyo', label: 'Tokyo (JST)' },
    ];

    const dateFormats = [
        { value: 'Y-m-d', label: 'YYYY-MM-DD' },
        { value: 'd/m/Y', label: 'DD/MM/YYYY' },
        { value: 'm/d/Y', label: 'MM/DD/YYYY' },
        { value: 'd-m-Y', label: 'DD-MM-YYYY' },
    ];

    return (
        <>
            <Toaster />
            <div className="row">
                <div className="col-lg-12">
                    <div className="card">
                        <div className="card-header">
                            <h4 className="card-title">General Settings</h4>
                        </div>
                        <div className="card-body">
                            <form onSubmit={handleSubmit}>
                                <div className="row">
                                    <div className="col-md-6">
                                        <InputField
                                            label="Site Name"
                                            type="text"
                                            value={data.site_name}
                                            onChange={(e) => setData('site_name', e.target.value)}
                                            error={errors.site_name}
                                            required
                                        />
                                    </div>
                                    <div className="col-md-6">
                                        <InputField
                                            label="Contact Email"
                                            type="email"
                                            value={data.contact_email}
                                            onChange={(e) => setData('contact_email', e.target.value)}
                                            error={errors.contact_email}
                                            required
                                        />
                                    </div>
                                </div>

                                <div className="row">
                                    <div className="col-md-12">
                                        <div className="form-group">
                                            <label className="col-form-label">Site Description</label>
                                            <textarea
                                                className="form-control"
                                                value={data.site_description}
                                                onChange={(e) => setData('site_description', e.target.value)}
                                                rows="3"
                                            />
                                            {errors.site_description && (
                                                <div className="text-danger">{errors.site_description}</div>
                                            )}
                                        </div>
                                    </div>
                                </div>

                                <div className="row">
                                    <div className="col-md-6">
                                        <InputField
                                            label="Contact Phone"
                                            type="text"
                                            value={data.contact_phone}
                                            onChange={(e) => setData('contact_phone', e.target.value)}
                                            error={errors.contact_phone}
                                        />
                                    </div>
                                    <div className="col-md-6">
                                        <SelectField
                                            label="Timezone"
                                            id="timezone"
                                            name="timezone"
                                            value={data.timezone}
                                            onChange={(e) => setData('timezone', e.target.value)}
                                            options={timezones}
                                            error={errors.timezone}
                                            required
                                        />
                                    </div>
                                </div>

                                <div className="row">
                                    <div className="col-md-6">
                                        <SelectField
                                            label="Date Format"
                                            id="date_format"
                                            name="date_format"
                                            value={data.date_format}
                                            onChange={(e) => setData('date_format', e.target.value)}
                                            options={dateFormats}
                                            error={errors.date_format}
                                            required
                                        />
                                    </div>
                                </div>

                                <div className="row mt-3">
                                    <div className="col-md-12">
                                        <button
                                            type="submit"
                                            className="btn btn-primary"
                                            disabled={processing || isSubmitting}
                                        >
                                            {processing || isSubmitting ? 'Saving...' : 'Save Settings'}
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
}

