import React, { useState, useEffect } from 'react';
import { getErrorMessage } from '@nexuscrm/host-sdk';
import { metadataAPI } from '../infrastructure/api/metadata';
import { ValidationRule } from '../types';
import { useSuccessToast, useErrorToast } from '@nexuscrm/salesforce-crm-standard-frontend/platform/components/ui';
import { BaseModal } from '@nexuscrm/salesforce-crm-standard-frontend/platform/components/ui';

interface ValidationRuleEditorProps {
    objectApiName: string;
    rule: ValidationRule | null; // null means create mode
    onClose: () => void;
    onSave: () => void;
}

export const ValidationRuleEditor: React.FC<ValidationRuleEditorProps> = ({
    objectApiName,
    rule,
    onClose,
    onSave
}) => {
    const showSuccess = useSuccessToast();
    const showError = useErrorToast();
    const [saving, setSaving] = useState(false);
    const [formData, setFormData] = useState({
        name: '',
        active: true,
        description: '',
        errorMessage: '',
        errorDisplayField: '',
        condition: ''
    });

    useEffect(() => {
        if (rule) {
            setFormData({
                name: rule.name,
                active: rule.active,
                description: rule.description ?? '',
                errorMessage: rule.errorMessage,
                errorDisplayField: rule.errorDisplayField ?? '',
                condition: rule.condition
            });
        }
    }, [rule]);

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setSaving(true);

        try {
            const ruleData = {
                objectApiName: objectApiName,
                name: formData.name,
                active: formData.active,
                description: formData.description,
                errorMessage: formData.errorMessage,
                errorDisplayField: formData.errorDisplayField,
                condition: formData.condition
            };

            if (!objectApiName) {
                showError('Object API Name is missing');
                setSaving(false);
                return;
            }

            if (rule) {
                await metadataAPI.updateValidationRule(rule.id, ruleData);
                showSuccess('Validation rule updated successfully');
            } else {
                await metadataAPI.createValidationRule(ruleData);
                showSuccess('Validation rule created successfully');
            }
            onSave();
        } catch (err: unknown) {
            showError(getErrorMessage(err, 'Failed to save validation rule'));
        } finally {
            setSaving(false);
        }
    };

    return (
        <BaseModal
            isOpen={true}
            onClose={saving ? () => {} : onClose}
            title={
                <>
                    {rule ? 'Edit Validation Rule' : 'New Validation Rule'}
                    {objectApiName && <span className="text-gray-500 font-normal text-lg ml-2">for {objectApiName}</span>}
                </>
            }
            headerClassName="bg-slate-50 border-b border-slate-200"
            maxWidth="3xl"
        >
            <form onSubmit={handleSubmit} className="p-6 space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label className="block text-sm font-medium text-slate-700 mb-1">
                            Rule Name <span className="text-red-600">*</span>
                        </label>
                        <input
                            type="text"
                            required
                            value={formData.name}
                            onChange={e => setFormData({ ...formData, name: e.target.value })}
                            className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                            placeholder="e.g. High_Value_Record"
                        />
                    </div>
                    <div className="flex items-center pt-6">
                        <label className="flex items-center gap-2 cursor-pointer">
                            <input
                                type="checkbox"
                                checked={formData.active}
                                onChange={e => setFormData({ ...formData, active: e.target.checked })}
                                className="rounded border-slate-300 text-blue-600 focus:ring-blue-500 h-4 w-4"
                            />
                            <span className="text-sm font-medium text-slate-700">Active</span>
                        </label>
                    </div>
                </div>

                <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">
                        Description
                    </label>
                    <p className="text-xs text-slate-500 mb-2">
                        Optional. A note for admins explaining why this rule exists.
                    </p>
                    <textarea
                        value={formData.description}
                        onChange={e => setFormData({ ...formData, description: e.target.value })}
                        rows={3}
                        className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm"
                        placeholder="e.g. Prevent saving a record without a required date"
                    />
                </div>

                <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">
                        Error Condition Formula <span className="text-red-600">*</span>
                    </label>
                    <p className="text-xs text-slate-500 mb-2">
                        Enter an expression that returns <strong>TRUE</strong> if the data is <strong>INVALID</strong>.
                        Uses <a href="https://expr-lang.org/" target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">expr-lang syntax</a>.
                    </p>
                    <div className="text-xs text-slate-400 mb-2 p-2 bg-slate-50 rounded border border-slate-200 font-mono">
                        <div><strong>Syntax:</strong> field_name == 'value', amount &gt; 0, close_date == null</div>
                        <div><strong>Operators:</strong> ==, !=, &gt;, &lt;, &gt;=, &lt;=, &amp;&amp;, ||, !</div>
                        <div><strong>Null checks:</strong> field == null, field != null</div>
                    </div>
                    <div className="relative">
                        <textarea
                            required
                            value={formData.condition}
                            onChange={e => setFormData({ ...formData, condition: e.target.value })}
                            rows={4}
                            className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 font-mono text-sm"
                            placeholder="stage == 'Closed' && close_date == null"
                        />
                    </div>
                </div>

                <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">
                        Error Display Field
                    </label>
                    <p className="text-xs text-slate-500 mb-2">
                        Optional. Persisted for Salesforce parity; errors still display at the top of the page.
                    </p>
                    <input
                        type="text"
                        value={formData.errorDisplayField}
                        onChange={e => setFormData({ ...formData, errorDisplayField: e.target.value })}
                        className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                        placeholder="e.g. Amount"
                    />
                </div>

                <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">
                        Error Message <span className="text-red-600">*</span>
                    </label>
                    <p className="text-xs text-slate-500 mb-2">
                        The text to display to the user when the rule is violated.
                    </p>
                    <input
                        type="text"
                        required
                        value={formData.errorMessage}
                        onChange={e => setFormData({ ...formData, errorMessage: e.target.value })}
                        className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                        placeholder="Amount must be positive and less than 1,000,000"
                    />
                </div>

                <div className="flex justify-end gap-3 pt-6 border-t border-slate-200">
                    <button
                        type="button"
                        onClick={onClose}
                        className="px-4 py-2 text-slate-700 border border-slate-300 rounded-lg hover:bg-slate-50 font-medium"
                    >
                        Cancel
                    </button>
                    <button
                        type="submit"
                        disabled={saving}
                        className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-medium disabled:opacity-50 flex items-center gap-2"
                    >
                        {saving ? (
                            <>
                                <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                                Saving...
                            </>
                        ) : (
                            <>{rule ? 'Update Rule' : 'Save Rule'}</>
                        )}
                    </button>
                </div>
            </form>
        </BaseModal>
    );
};
