from django.urls import reverse, reverse_lazy
from lariv.registry import UIRegistry
from components import *  # noqa
from users.models import Role


# Menus
@UIRegistry.register("users.UserMenu")
class UserMenu(Component):
    def build(self):
        return Menu(
            uid="user-menu",
            back=MenuItem(
                uid="user-menu-back",
                title="Back to Home",
                url=reverse_lazy("apps"),
            ),
            title="Users",
            children=[
                MenuItem(
                    uid="user-menu-list",
                    title="All Users",
                    url=reverse_lazy("users:list"),
                ),
            ],
        )


@UIRegistry.register("users.UserDetailMenu")
class UserDetailMenu(Component):
    def build(self):
        return Menu(
            uid="user-detail-menu",
            back=MenuItem(
                uid="user-detail-menu-back",
                title="Back to All Users",
                url=reverse_lazy("users:list"),
            ),
            key="user",
            title=lambda o: f"User: {o.name}",
            children=[
                MenuItem(
                    uid="user-detail-menu-detail",
                    title="User Detail",
                    key="user",
                    url=lambda o: reverse("users:detail", args=[o.pk]),
                ),
                MenuItem(
                    uid="user-detail-menu-edit",
                    title="Edit User",
                    key="user",
                    url=lambda o: reverse("users:update", args=[o.pk]),
                ),
                MenuItem(
                    uid="user-detail-menu-delete",
                    title="Delete User",
                    key="user",
                    url=lambda o: reverse("users:delete", args=[o.pk]),
                ),
                MenuItem(
                    uid="user-detail-menu-change-password",
                    title="Change Password",
                    key="user",
                    url=lambda o: reverse("users:change_password", args=[o.pk]),
                ),
            ],
        )


# Filter
@UIRegistry.register("users.UserFilter")
class UserFilter(Component):
    def build(self):
        return Form(
            uid="user-filter",
            url=reverse_lazy("users:list"),
            target="#user-table_display_content",
            method="get",
            swap="morph",
            children=[
                TextInput(uid="user-filter-name", key="name", label="Name"),
                TextInput(uid="user-filter-email", key="email", label="Email"),
                PhoneInput(uid="user-filter-phone", key="phone", label="Phone"),
                TernaryInput(
                    uid="user-filter-is-active",
                    key="is_active",
                    label="Active",
                    true_label="Active Only",
                    false_label="Inactive Only",
                    none_label="All",
                ),
                Row(
                    uid="user-filter-actions",
                    classes="flex gap-2",
                    children=[
                        SubmitInput(
                            uid="user-filter-submit",
                            label="Apply Filters",
                        ),
                        ClearInput(uid="user-filter-clear", label="Clear"),
                    ],
                ),
            ],
        )


# Form Fields
@UIRegistry.register("users.UserFormFields")
class UserFormFields(Component):
    def build(self):
        return Column(
            uid="user-form-fields",
            children=[
                Row(
                    uid="user-form-row-1",
                    classes="grid grid-cols-1 gap-1 @md:grid-cols-2",
                    children=[
                        TextInput(
                            uid="user-form-name",
                            key="name",
                            label="Name",
                            required=True,
                        ),
                        EmailInput(
                            uid="user-form-email",
                            key="email",
                            label="Email",
                            required=True,
                        ),
                    ],
                ),
                Row(
                    uid="user-form-row-2",
                    classes="grid grid-cols-1 gap-1 @md:grid-cols-2",
                    children=[
                        PhoneInput(
                            uid="user-form-phone",
                            key="phone",
                            label="Phone",
                            required=True,
                        ),
                        ForeignKeyInput(
                            uid="user-form-role",
                            key="role",
                            model=Role,
                            label="Role",
                            url=reverse_lazy("users:role_select"),
                            display_attr="name",
                            placeholder="Select a role...",
                            required=True,
                        ),
                    ],
                ),
                TernaryInput(
                    uid="user-form-is-active",
                    key="is_active",
                    label="Active",
                    true_label="Yes",
                    false_label="No",
                    none_label="Not Set",
                ),
                SubmitInput(uid="user-form-submit", label="Save User"),
            ],
        )


@UIRegistry.register("users.UserCreateForm")
class UserCreateForm(Component):
    def build(self):
        return ScaffoldLayout(
            uid="user-create-scaffold",
            sidebar_children=[
                UIRegistry.get("users.UserMenu")().build(),
            ],
            children=[
                Form(
                    uid="user-create-form",
                    url=reverse_lazy("users:create"),
                    target="#app-layout",
                    key="user",
                    title="Create User",
                    subtitle="Create a new user",
                    classes="@container",
                    children=[UIRegistry.get("users.UserFormFields")().build()],
                )
            ],
        )


@UIRegistry.register("users.UserUpdateForm")
class UserUpdateForm(Component):
    def build(self):
        return ScaffoldLayout(
            uid="user-update-scaffold",
            sidebar_children=[
                UIRegistry.get("users.UserDetailMenu")().build(),
            ],
            children=[
                Form(
                    uid="user-update-form",
                    url=lambda obj: reverse("users:update", args=[obj.pk]),
                    target="#app-layout",
                    key="user",
                    title="Edit User",
                    subtitle="Update user details",
                    classes="@container",
                    children=[UIRegistry.get("users.UserFormFields")().build()],
                )
            ],
        )


# Table
@UIRegistry.register("users.UserTable")
class UserTable(Component):
    def build(self):
        return ScaffoldLayout(
            uid="user-table-scaffold",
            sidebar_children=[
                UIRegistry.get("users.UserMenu")().build(),
            ],
            children=[
                Table(
                    uid="user-table",
                    classes="w-full",
                    key="users",
                    create_url=reverse_lazy("users:create"),
                    url=lambda o: reverse("users:detail", args=[o.pk]),
                    filter_component=UIRegistry.get("users.UserFilter")().build(),
                    columns=[
                        TableColumn(
                            uid="user-col-name",
                            label="Name",
                            key="name",
                            children=[TextField(uid="user-col-name-field", key="name")],
                        ),
                        TableColumn(
                            uid="user-col-email",
                            label="Email",
                            key="email",
                            children=[TextField(uid="user-col-email-field", key="email")],
                        ),
                        TableColumn(
                            uid="user-col-phone",
                            label="Phone",
                            key="phone",
                            children=[TextField(uid="user-col-phone-field", key="phone")],
                        ),
                        TableColumn(
                            uid="user-col-is-active",
                            key="is_active",
                            label="Active",
                            children=[CheckboxField(uid="user-col-is-active-field", key="is_active")],
                        ),
                    ],
                )
            ],
        )


# Detail
@UIRegistry.register("users.UserDetail")
class UserDetail(Component):
    def build(self):
        return ScaffoldLayout(
            uid="user-detail-scaffold",
            sidebar_children=[
                UIRegistry.get("users.UserDetailMenu")().build(),
            ],
            children=[
                Detail(
                    uid="user-detail-view",
                    key="user",
                    children=[
                        Column(
                            uid="user-detail",
                            children=[
                                TitleField(uid="name", key="name"),
                                SubtitleField(uid="email", key="email"),
                                InlineLabel(
                                    uid="user-detail-phone-label",
                                    title="Phone",
                                    classes="mt-2",
                                    children=[TextField(uid="phone", key="phone")],
                                ),
                                InlineLabel(
                                    uid="user-detail-is-active-label",
                                    title="Active",
                                    children=[CheckboxField(
                                        uid="is_active", key="is_active"
                                    )],
                                ),
                                InlineLabel(
                                    uid="user-detail-role-label",
                                    title="Role",
                                    children=[TextField(
                                        uid="user-detail-role", key="role"
                                    )],
                                ),
                            ],
                        ),
                    ],
                )
            ],
        )


# Delete Form
@UIRegistry.register("users.UserDeleteForm")
class UserDeleteForm(Component):
    def build(self):
        return ScaffoldLayout(
            uid="user-delete-scaffold",
            sidebar_children=[
                UIRegistry.get("users.UserDetailMenu")().build(),
            ],
            children=[
                DeleteConfirmation(
                    uid="user-delete-confirmation",
                    key="user",
                    title="Confirm Deletion",
                    message="Are you sure you want to delete this user?",
                    url=lambda obj: reverse("users:detail", args=[obj.pk]),
                ),
            ],
        )


# Change Password Form
@UIRegistry.register("users.ChangePasswordForm")
class ChangePasswordForm(Component):
    def build(self):
        return ScaffoldLayout(
            uid="user-change-password-scaffold",
            sidebar_children=[
                UIRegistry.get("users.UserDetailMenu")().build(),
            ],
            children=[
                Form(
                    uid="change-password-form",
                    url=lambda obj: (
                        reverse("users:change_password", args=[obj.pk])
                        if getattr(obj, "pk", None)
                        else ""
                    ),
                    target="#app-layout",
                    key="user",
                    title="Change Password",
                    subtitle="Update user password",
                    children=[
                        PasswordInput(
                            uid="change-password-new",
                            key="new_password",
                            label="New Password",
                            placeholder="Enter new password",
                            required=True,
                        ),
                        PasswordInput(
                            uid="change-password-confirm",
                            key="confirm_password",
                            label="Confirm New Password",
                            placeholder="Confirm new password",
                            required=True,
                        ),
                        SubmitInput(
                            uid="change-password-submit", label="Change Password"
                        ),
                    ],
                ),
            ],
        )


# Selection Table Filter
@UIRegistry.register("users.UserSelectionFilter")
class UserSelectionFilter(Component):
    def build(self):
        return Form(
            uid="user-selection-filter",
            url=reverse_lazy("users:select"),
            target="#user-selection-table_display_content",
            method="get",
            swap="morph",
            children=[
                TextInput(uid="user-sel-filter-name", key="name", label="Name"),
                TextInput(uid="user-sel-filter-email", key="email", label="Email"),
                Row(
                    uid="user-sel-filter-actions",
                    classes="flex gap-2",
                    children=[
                        SubmitInput(
                            uid="user-sel-filter-submit",
                            label="Apply",
                        ),
                        ClearInput(uid="user-sel-filter-clear", label="Clear"),
                    ],
                ),
            ],
        )


# Selection Table
@UIRegistry.register("users.UserSelectionTable")
class UserSelectionTable(Component):
    def build(self):
        return Modal(
            uid="user-selection-modal",
            title="Select User",
            children=[
                Table(
                    uid="user-selection-table",
                    key="users",
                    select="single",
                    value_key="pk",
                    display_key="name",
                    filter_component=UIRegistry.get(
                        "users.UserSelectionFilter"
                    )().build(),
                    columns=[
                        TableColumn(
                            uid="user-sel-col-name",
                            label="Name",
                            key="name",
                            children=[TextField(uid="user-sel-name-field", key="name")],
                        ),
                        TableColumn(
                            uid="user-sel-col-email",
                            label="Email",
                            key="email",
                            children=[TextField(uid="user-sel-email-field", key="email")],
                        ),
                        TableColumn(
                            uid="user-sel-col-phone",
                            label="Phone",
                            key="phone",
                            children=[TextField(uid="user-sel-phone-field", key="phone")],
                        ),
                    ],
                ),
            ],
        )


# Multi Selection Table Filter
@UIRegistry.register("users.UserMultiSelectionFilter")
class UserMultiSelectionFilter(Component):
    def build(self):
        return Form(
            uid="user-multi-selection-filter",
            url=reverse_lazy("users:multi_select"),
            target="#user-multi-selection-table_display_content",
            method="get",
            swap="morph",
            children=[
                TextInput(uid="user-multi-sel-filter-name", key="name", label="Name"),
                TextInput(
                    uid="user-multi-sel-filter-email", key="email", label="Email"
                ),
                Row(
                    uid="user-multi-sel-filter-actions",
                    classes="flex gap-2",
                    children=[
                        SubmitInput(
                            uid="user-multi-sel-filter-submit",
                            label="Apply",
                        ),
                        ClearInput(uid="user-multi-sel-filter-clear", label="Clear"),
                    ],
                ),
            ],
        )


# Multi Selection Table
@UIRegistry.register("users.UserMultiSelectionTable")
class UserMultiSelectionTable(Component):
    def build(self):
        return Modal(
            uid="user-multi-selection-modal",
            title="Select Users",
            children=[
                Table(
                    uid="user-multi-selection-table",
                    key="users",
                    select="multi",
                    value_key="pk",
                    display_key="name",
                    filter_component=UIRegistry.get(
                        "users.UserMultiSelectionFilter"
                    )().build(),
                    columns=[
                        TableColumn(
                            uid="user-multi-sel-col-name",
                            label="Name",
                            key="name",
                            children=[TextField(uid="user-multi-sel-name-field", key="name")],
                        ),
                        TableColumn(
                            uid="user-multi-sel-col-email",
                            label="Email",
                            key="email",
                            children=[TextField(uid="user-multi-sel-email-field", key="email")],
                        ),
                    ],
                ),
            ],
        )


# =============================================================================
# AUTH FORMS (Login / Signup)
# =============================================================================


@UIRegistry.register("users.LoginForm")
class LoginForm(Component):
    def build(self):
        return AuthScaffoldLayout(
            uid="login-scaffold",
            children=[
                Column(
                    uid="login-container",
                    classes="w-80",
                    children=[
                        TitleField(
                            uid="login-title",
                            key=None,
                            static_value="Login",
                        ),
                        Form(
                            uid="login-form",
                            key="user",
                            url=reverse_lazy("users:login"),
                            target="body",
                            method="post",
                            swap="outerHTML",
                            push_url=False,
                            children=[
                                EmailInput(
                                    uid="login-email",
                                    key="username",
                                    label="Email",
                                    placeholder="Enter your email",
                                    required=True,
                                ),
                                PasswordInput(
                                    uid="login-password",
                                    key="password",
                                    label="Password",
                                    placeholder="Enter your password",
                                    required=True,
                                ),
                                SubmitInput(
                                    uid="login-submit",
                                    label="Login",
                                    classes="w-full",
                                ),
                            ],
                        ),
                        Row(
                            uid="login-signup-link-row",
                            classes="text-center mt-4",
                            children=[
                                Link(
                                    uid="login-signup-link",
                                    text="Don't have an account? Sign up",
                                    url=reverse_lazy("users:signup"),
                                ),
                            ],
                        ),
                    ],
                ),
            ],
        )


@UIRegistry.register("users.SignupForm")
class SignupForm(Component):
    def build(self):
        return AuthScaffoldLayout(
            uid="signup-scaffold",
            children=[
                Column(
                    uid="signup-container",
                    classes="w-96",
                    children=[
                        TitleField(
                            uid="signup-title",
                            key=None,
                            static_value="Create an Account",
                        ),
                        Form(
                            uid="signup-form",
                            key="user",
                            url=reverse_lazy("users:signup"),
                            target="body",
                            method="post",
                            swap="outerHTML",
                            push_url=False,
                            children=[
                                TextInput(
                                    uid="signup-name",
                                    key="name",
                                    label="Full Name",
                                    placeholder="Enter your name",
                                    required=True,
                                ),
                                EmailInput(
                                    uid="signup-email",
                                    key="email",
                                    label="Email",
                                    placeholder="Enter your email",
                                    required=True,
                                ),
                                PhoneInput(
                                    uid="signup-phone",
                                    key="phone",
                                    label="Phone Number",
                                    placeholder="Enter your phone number",
                                    required=True,
                                ),
                                PasswordInput(
                                    uid="signup-password1",
                                    key="password1",
                                    label="Password",
                                    placeholder="Enter your password",
                                    required=True,
                                ),
                                PasswordInput(
                                    uid="signup-password2",
                                    key="password2",
                                    label="Confirm Password",
                                    placeholder="Confirm your password",
                                    required=True,
                                ),
                                CheckboxInput(
                                    uid="signup-terms",
                                    key="terms_accepted",
                                    label="I accept the terms and conditions",
                                    required=True,
                                ),
                                SubmitInput(
                                    uid="signup-submit",
                                    label="Sign Up",
                                    classes="w-full",
                                ),
                            ],
                        ),
                        Row(
                            uid="signup-login-link-row",
                            classes="text-center mt-4",
                            children=[
                                Link(
                                    uid="signup-login-link",
                                    text="Already have an account? Login",
                                    url=reverse_lazy("users:login"),
                                ),
                            ],
                        ),
                    ],
                ),
            ],
        )


# Role Selection Table Filter
@UIRegistry.register("users.RoleSelectionFilter")
class RoleSelectionFilter(Component):
    def build(self):
        return Form(
            uid="role-selection-filter",
            url=reverse_lazy("users:role_select"),
            target="#role-selection-table_display_content",
            method="get",
            swap="morph",
            children=[
                TextInput(uid="role-sel-filter-name", key="name", label="Name"),
                Row(
                    uid="role-sel-filter-actions",
                    classes="flex gap-2",
                    children=[
                        SubmitInput(
                            uid="role-sel-filter-submit",
                            label="Apply",
                        ),
                        ClearInput(uid="role-sel-filter-clear", label="Clear"),
                    ],
                ),
            ],
        )


# Role Selection Table
@UIRegistry.register("users.RoleSelectionTable")
class RoleSelectionTable(Component):
    def build(self):
        return Modal(
            uid="role-selection-modal",
            title="Select Role",
            children=[
                Table(
                    uid="role-selection-table",
                    key="roles",
                    select="single",
                    value_key="pk",
                    display_key="name",
                    filter_component=UIRegistry.get(
                        "users.RoleSelectionFilter"
                    )().build(),
                    columns=[
                        TableColumn(
                            uid="role-sel-col-name",
                            label="Name",
                            key="name",
                            children=[TextField(uid="role-sel-name-field", key="name")],
                        ),
                    ],
                ),
            ],
        )
