from django import forms
from chatbot.models import Chat_Data, TableList, ColumnList, Options, RelatedOptionTable, MapTables

class ChatForm(forms.ModelForm):
    class Meta:
        model = Chat_Data
        fields = ["chat_name", "chat_type", "related_chat","option_table", "option_column", "message", "option_type", "related_option_id" ]

    chat_name = forms.CharField(
        label="Chat Name",
        widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "Enter Chat Name"}),
        required=True
    )

    chat_type = forms.ChoiceField(
        choices=[
            ("", "---------"),
            ("Welcome Message", "Welcome Message"),
            ("Related", "Related"),
            ("End Message", "End Message"),
        ],
        widget=forms.Select(attrs={"class": "form-control form-select", "id": "chat_type"}),
    )

    message = forms.CharField(
        widget=forms.Textarea(attrs={'rows': 5, 'cols': 50, 'class': 'form-control'}),
        required=True
    )

    related_chat = forms.ModelChoiceField(
        queryset=Chat_Data.objects.all(),  # Fetch chat data dynamically
        widget=forms.Select(attrs={"class": "form-control form-select", "id": "related_chat"}),
        required=False
    )

    option_type = forms.ChoiceField(
        choices=[("", "-------"), ("Custom", "Custom"), ("Table", "Table")],
        required=False,
        widget=forms.Select(attrs={"class": "form-control form-select", "id": "option_type"}),
    )
    related_option_id = forms.ModelChoiceField(
        queryset=RelatedOptionTable.objects.all(),
        required=False,
        empty_label="Select an option",
        widget=forms.Select(attrs={'class': 'form-control'})
    )
    # filter = forms.CharField(
    #     widget=forms.Select(
    #         choices=[("No", "No"), ("Yes", "Yes")],
    #         attrs={"class": "form-control form-select filter_class", "id": "filter"}
    #     ),
    #     required=False
    # )

    option_table = forms.ModelChoiceField(
        queryset=TableList.objects.all(),
        widget=forms.Select(attrs={"class": "form-control", "id": "option_table"}),
        required=False
    )

    option_column = forms.ModelChoiceField(
    queryset=ColumnList.objects.all(),  # Ensures Django recognizes the selected column
    widget=forms.Select(attrs={"class": "form-control", "id": "option_column"}),
    required=False
    )

    redirect = forms.ChoiceField(
        choices= [("No", "No"),
            ("Yes", "Yes"),],
        widget=forms.Select(
            attrs={"class": "form-control form-select redirect_class", "id": "redirect"}
        ),
        initial="No",
        required=False
    )

    def __init__(self, *args, **kwargs):
        super(ChatForm, self).__init__(*args, **kwargs)
        # ✅ Remove option_column validation by allowing all values
        self.fields["option_column"].choices = [("", "---------")] + [
            (col.id, col.column_name) for col in ColumnList.objects.all()
        ]

        self.fields['redirect'].initial = "Yes" if self.instance.redirect == "Yes" else "No"

        # # ✅ If instance exists and chat_type is "Welcome Message", remove fields
        # if self.instance and self.instance.chat_type == "Welcome Message":
        #     self.fields.pop("option_table", None)
        #     self.fields.pop("option_column", None)
        #     # self.fields.pop("related_chat", None)
        # else:
        #     print("ooooooo")
        #     if self.instance and self.instance.option_table:
        #         self.fields["option_column"].choices = [("", "---------")] + [
        #             (col.id, col.column_name) for col in ColumnList.objects.filter(table=self.instance.option_table)
        #         ]

        # Populate related_chat choices dynamically
        if "related_chat" in self.fields:
            self.fields["related_chat"].choices = [("", "---------")] + [
                (chat.pk, chat.chat_name) for chat in Chat_Data.objects.all()
            ]

    # ✅ Override validation to completely ignore errors for option_column

    def clean_option_type(self):
        chat_type = self.cleaned_data.get("chat_type", None)
        option_type = self.cleaned_data.get("option_type", None)
        if chat_type == "Related":
            if not option_type:
                raise forms.ValidationError("Please select a option type!")
        return option_type




    # def clean_option_column(self):
    #     chat_type = self.cleaned_data.get("chat_type", None)
    #     option_type = self.cleaned_data.get("option_type", None)
    #     option_column = self.cleaned_data.get("option_column", None)
    #     if chat_type == "Related":
    #         print("whooooooooooooo")
    #         print(option_type)
    #         if self.instance.option_type == "Table":
    #             print(".......................")
    #             if not option_column:
    #                 raise forms.ValidationError("Please select option column!")
    #     return option_column  # Return without validation
    #
    # def clean_option_table(self):
    #     chat_type = self.cleaned_data.get("chat_type", None)
    #     option_type = self.cleaned_data.get("option_type", None)
    #     option_table = self.cleaned_data.get("option_table", None)
    #     if chat_type == "Related":
    #         print("ewewerweweweww")
    #         print(option_type)
    #         print(self.instance.option_type)
    #         if self.instance.option_type == "Table":
    #             print("......")
    #             if not option_table:
    #                 raise forms.ValidationError("Please select option table!")
    #     return option_table



    def clean_chat_type(self):
        chat_type = self.cleaned_data.get("chat_type", None)
        if chat_type == "Welcome Message":
            if Chat_Data.objects.filter(chat_type="Welcome Message").exclude(chat_id=self.instance.chat_id).exists():
                raise forms.ValidationError("Only one welcome message allowed!")
        return chat_type

    # def clean_related_chat(self):
    #     chat_type = self.cleaned_data.get("chat_type", None)
    #     if chat_type == "Related" or chat_type == "End Message":
    #         related_chat = self.cleaned_data.get('related_chat')
    #         if not related_chat:
    #             raise forms.ValidationError('Please select a related chat message!')

    def clean(self):
        cleaned_data = super().clean()
        code = cleaned_data.get('code')
        chat_type = self.cleaned_data.get("chat_type", None)
        option_type = self.cleaned_data.get("option_type", None)
        option_column = self.cleaned_data.get("option_column", None)
        option_table = self.cleaned_data.get("option_table", None)
        related_option_id = self.cleaned_data.get("related_option_id", None)
        related_chat = self.cleaned_data.get("related_chat")

        if chat_type == "Related":
            if option_type == "Table":
                if not option_column:
                    self.add_error('option_column',"Please select option column!")
                if not option_table:
                    self.add_error('option_table', "Please select option table!")


        if chat_type == "Related" or chat_type == "End Message":
            if not related_chat:
                self.add_error('related_chat', 'Please select a related chat message!')
            else:
                chat_data  = Chat_Data.objects.filter(chat_id = related_chat.chat_id).first()
                if chat_data.option_type == "Custom":
                    if not related_option_id:
                        self.add_error('related_option_id', 'Please select a related option!')


        return cleaned_data  # Return without validation






class TableListForm(forms.ModelForm):
    class Meta:
        model = TableList
        fields = ["table_name", ]

    table_name = forms.CharField(
        label="Table Name",
        widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "Enter Table Name"}),
        required=True
    )


class ColumnListForm(forms.ModelForm):

    class Meta:
        model = ColumnList
        fields = ["column_name", "column_id" ]

    column_name = forms.CharField(
        label="Column(Name)",
        widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "Enter Name Column"}),
        required=True
    )

    column_id = forms.CharField(
        label="Column(ID)",
        widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "Enter ID Column"}),
        required=True
    )


class MapForm(forms.ModelForm):
    class Meta:
        model = MapTables
        fields = ["map_name","table_name", ]

    map_name = forms.CharField(
        label="Map Name",
        widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "Enter Map Name"}),
        required=True
    )


    table_name = forms.ModelChoiceField(
        queryset=TableList.objects.all(),
        widget=forms.Select(attrs={"class": "form-control", "id": "option_table"}),
        required=False
    )

    def clean_table_name(self):
        table_name = self.cleaned_data.get("table_name", None)

        edit_flag = False
        try:
            existing_table_name = self.instance.table_name
            edit_flag = True
        except:
            existing_table_name = ""
            edit_flag = False


        valid_check =MapTables.objects.filter(table_name=table_name)
        if edit_flag:
            if table_name == self.instance.table_name:
                if len(list(valid_check)) > 1:
                    raise forms.ValidationError("Table is already mapped Please check map list!")
            else:
                if valid_check:
                    raise forms.ValidationError("Table is already mapped Please check map list!")
        else:
            if valid_check:
                raise forms.ValidationError("Table is already mapped Please check map list!")






        return table_name







