use derive_more::From;
use std::fmt;
use std::fmt::{Display, Formatter};

use crate::sql::expression::identifier::SimpleIdentifier;
use crate::sql::expression::literal::ColumnReference;
use crate::sql::expression::SQLExpression;
use crate::sql::query::TableReference;
use crate::types::struct_type::Struct;
use crate::write_utils::pad;

use super::SQLQuery;

#[derive(Debug, Clone, From, PartialEq, Eq)]
pub enum DML {
    Insert(Insert),
    Merge(Merge),
}

impl DML {
    pub fn fmt_indented(&self, f: &mut Formatter<'_>, indentation: usize) -> fmt::Result {
        match self {
            DML::Insert(insert) => insert.fmt_indented(f, indentation),
            DML::Merge(merge) => merge.fmt_indented(f, indentation),
        }
    }
}

impl Display for DML {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.fmt_indented(f, 0)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Insert {
    pub table: TableReference,
    pub schema: Struct,
    pub query: SQLQuery,
}

impl Insert {
    pub fn fmt_indented(&self, f: &mut Formatter<'_>, indentation: usize) -> fmt::Result {
        write!(f, "INSERT INTO ")?;
        write!(f, "{} (", self.table)?;
        for (i, si) in self.schema.fields.keys().enumerate() {
            si.fmt_indented(f, 0)?;
            if i != self.schema.fields.len() - 1 {
                write!(f, ", ")?;
            }
        }
        write!(f, ")")?;
        writeln!(f)?;
        self.query.fmt_indented(f, indentation)
    }
}

impl Display for Insert {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.fmt_indented(f, 0)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Merge {
    pub table_alias: SimpleIdentifier,
    pub query_alias: SimpleIdentifier,
    pub table: TableReference,
    pub search_condition: SQLExpression,
    pub when_clauses: Vec<MergeWhenClause>,
    pub query: SQLQuery,
}

impl Merge {
    pub fn fmt_indented(&self, f: &mut Formatter<'_>, indentation: usize) -> fmt::Result {
        write!(f, "MERGE INTO ")?;
        write!(f, "{} AS {}", self.table, self.table_alias.to_string())?;
        writeln!(f)?;
        write!(f, "USING (")?;
        writeln!(f)?;
        self.query.fmt_indented(f, indentation)?;
        writeln!(f)?;
        write!(f, ") AS {}", self.query_alias.to_string())?;
        writeln!(f)?;
        write!(f, "ON ")?;
        self.search_condition.fmt_indented(f, indentation)?;
        writeln!(f)?;
        for mc in self.when_clauses.iter() {
            mc.fmt_indented(f, indentation)?;
            writeln!(f)?;
        }
        Ok(())
    }
}

impl Display for Merge {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.fmt_indented(f, 0)
    }
}

#[derive(Debug, Clone, From, PartialEq, Eq)]
pub enum MergeWhenClause {
    Matched(MergeWhenMatched),
    NotMatched(MergeWhenNotMatched),
}

impl MergeWhenClause {
    pub fn fmt_indented(&self, f: &mut Formatter<'_>, indentation: usize) -> fmt::Result {
        match self {
            MergeWhenClause::Matched(when_matched) => when_matched.fmt_indented(f, indentation),
            MergeWhenClause::NotMatched(when_not_matched) => {
                when_not_matched.fmt_indented(f, indentation)
            }
        }
    }
}

impl Display for MergeWhenClause {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.fmt_indented(f, 0)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MergeWhenMatched {
    then: MergeAction,
}

impl MergeWhenMatched {
    pub fn fmt_indented(&self, f: &mut Formatter<'_>, _indentation: usize) -> fmt::Result {
        write!(f, "WHEN MATCHED\nTHEN {}", self.then)
    }
}

impl Display for MergeWhenMatched {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.fmt_indented(f, 0)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MergeWhenNotMatched {
    then: MergeAction,
}

impl MergeWhenNotMatched {
    pub fn new(then: MergeAction) -> Self {
        Self { then }
    }

    pub fn fmt_indented(&self, f: &mut Formatter<'_>, indentation: usize) -> fmt::Result {
        write!(f, "WHEN NOT MATCHED\nTHEN ")?;
        self.then.fmt_indented(f, indentation)
    }
}

impl Display for MergeWhenNotMatched {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.fmt_indented(f, 0)
    }
}

#[derive(Debug, Clone, From, PartialEq, Eq)]
pub enum MergeAction {
    Delete,
    Insert(MergeInsert),
    Update(MergeUpdate),
}

impl MergeAction {
    pub fn fmt_indented(&self, f: &mut Formatter<'_>, indentation: usize) -> fmt::Result {
        match self {
            MergeAction::Delete => write!(f, "DELETE"),
            MergeAction::Insert(insert) => insert.fmt_indented(f, indentation),
            MergeAction::Update(update) => update.fmt_indented(f, indentation),
        }
    }
}

impl Display for MergeAction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.fmt_indented(f, 0)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MergeInsert {
    columns: Vec<ColumnReference>,
}

impl MergeInsert {
    pub fn new(columns: Vec<ColumnReference>) -> Self {
        Self { columns }
    }

    pub fn fmt_indented(&self, f: &mut Formatter<'_>, indentation: usize) -> fmt::Result {
        write!(f, "INSERT (")?;
        let column_length = self.columns.len();
        for (i, c) in self.columns.iter().enumerate() {
            c.fmt_indented(f, indentation)?;
            if i != column_length - 1 {
                write!(f, ", ")?;
            }
        }
        write!(f, ") VALUES (")?;
        for (i, c) in self.columns.iter().enumerate() {
            c.prefix(&["source"]).fmt_indented(f, indentation)?;
            if i != column_length - 1 {
                write!(f, ", ")?;
            }
        }
        write!(f, ")")
    }
}

impl Display for MergeInsert {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.fmt_indented(f, 0)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MergeUpdate {
    columns: Vec<ColumnReference>,
}

impl MergeUpdate {
    pub fn fmt_indented(&self, f: &mut Formatter<'_>, indentation: usize) -> fmt::Result {
        writeln!(f, "UPDATE SET (")?;
        for (i, c) in self.columns.iter().enumerate() {
            pad(f, indentation)?;
            if i > 0 {
                write!(f, ", ")?;
            }
            c.fmt_indented(f, indentation + 4)?;
            write!(f, " = ",)?;
            c.prefix(&["source"]).fmt_indented(f, indentation + 4)?;
        }
        Ok(())
    }
}

impl Display for MergeUpdate {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.fmt_indented(f, 0)
    }
}
