'use client'

import { useDjangoFormCore } from 'mizan'
import { useStyles } from '../../contexts/StylesContext'
import { SettingsSection, Button } from './SettingsComponents'

export function PasswordSection() {
    const styles = useStyles()
    const form = useDjangoFormCore<Record<string, unknown>>({ name: 'change_password' })

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault()
        const result = await form.submit()
        if (result.success) {
            form.reset()
            alert('Password changed successfully!')
        }
    }

    if (form.loading) return null

    return (
        <SettingsSection title={form.schema?.title || 'Change Password'}>
            <form onSubmit={handleSubmit} className={styles.form}>
                <div className={styles.fieldsContainer}>
                    {form.schema?.fieldOrder.map(fieldName => {
                        const field = form.schema!.fields[fieldName]
                        return (
                            <div key={fieldName} className={styles.field}>
                                <label className={styles.fieldLabel}>{field.label}</label>
                                <input
                                    type={field.type}
                                    value={(form.data[fieldName] as string) || ''}
                                    onChange={(e) => form.set(fieldName, e.target.value)}
                                    onBlur={() => form.touch(fieldName)}
                                    className={styles.fieldInput}
                                    required={field.required}
                                />
                                {form.touchedFields.has(fieldName) &&
                                    form.getFieldErrors(fieldName).map((err, i) => (
                                        <p key={i} className={styles.fieldError}>{err.message}</p>
                                    ))
                                }
                            </div>
                        )
                    })}
                </div>
                <Button type="submit" disabled={form.submitting}>
                    {form.submitting ? 'Changing...' : (form.schema?.submit_label || 'Change Password')}
                </Button>
            </form>
        </SettingsSection>
    )
}
