use phf::phf_map;
use std::borrow::Cow;

use crate::layout::style::{
  tw::{TailwindProperty, TailwindPropertyParser, parser::*},
  *,
};

fn extract_arbitrary_value(suffix: &str) -> Option<Cow<'_, str>> {
  if suffix.starts_with('[') && suffix.ends_with(']') {
    let value = &suffix[1..suffix.len() - 1];
    if value.contains('_') {
      Some(Cow::Owned(value.replace('_', " ")))
    } else {
      Some(Cow::Borrowed(value))
    }
  } else {
    None
  }
}

fn parse_property<T>(suffix: &str, f: fn(T) -> TailwindProperty) -> Option<TailwindProperty>
where
  T: TailwindPropertyParser,
{
  if let Some(value) = extract_arbitrary_value(suffix) {
    return T::from_str(&value).ok().map(f);
  }

  T::parse_tw(suffix).map(f)
}

/// Enum for data-driven property parsing
#[derive(Clone, Copy)]
pub enum PropertyParser {
  ObjectFit(fn(ObjectFit) -> TailwindProperty),
  BgPosition(fn(BackgroundPosition) -> TailwindProperty),
  BgSize(fn(BackgroundSize) -> TailwindProperty),
  BgImage(fn(BackgroundImage) -> TailwindProperty),
  LengthAuto(fn(LengthUnit) -> TailwindProperty),
  LengthZero(fn(LengthUnit<false>) -> TailwindProperty),
  FontWeight(fn(FontWeight) -> TailwindProperty),
  Justify(fn(JustifyContent) -> TailwindProperty),
  Align(fn(AlignItems) -> TailwindProperty),
  Overflow(fn(Overflow) -> TailwindProperty),
  BorderWidth(fn(TwBorderWidth) -> TailwindProperty),
  Rounded(fn(TwRounded) -> TailwindProperty),
  GridTemplate(fn(TwGridTemplate) -> TailwindProperty),
  GridAuto(fn(TwGridAutoSize) -> TailwindProperty),
  GridPlacement(fn(TwGridPlacement) -> TailwindProperty),
  GridSpan(fn(TwGridSpan) -> TailwindProperty),
  LetterSpacing(fn(TwLetterSpacing) -> TailwindProperty),
  FlexGrow(fn(FlexGrow) -> TailwindProperty),
  Aspect(fn(AspectRatio) -> TailwindProperty),
  TextAlign(fn(TextAlign) -> TailwindProperty),
  ColorCurrent(fn(ColorInput) -> TailwindProperty),
  ColorTransparent(fn(ColorInput<false>) -> TailwindProperty),
  Percentage(fn(PercentageNumber) -> TailwindProperty),
  FontFamily(fn(FontFamily) -> TailwindProperty),
  LineClamp(fn(LineClamp) -> TailwindProperty),
  WhiteSpace(fn(WhiteSpace) -> TailwindProperty),
  OverflowWrap(fn(OverflowWrap) -> TailwindProperty),
  FontSize(fn(TwFontSize) -> TailwindProperty),
  LineHeight(fn(LineHeight) -> TailwindProperty),
  Flex(fn(Flex) -> TailwindProperty),
  Angle(fn(Angle) -> TailwindProperty),
}

impl PropertyParser {
  pub fn parse(&self, suffix: &str) -> Option<TailwindProperty> {
    match self {
      Self::ObjectFit(f) => parse_property(suffix, *f),
      Self::BgPosition(f) => parse_property(suffix, *f),
      Self::BgSize(f) => parse_property(suffix, *f),
      Self::BgImage(f) => parse_property(suffix, *f),
      Self::LengthAuto(f) => parse_property(suffix, *f),
      Self::LengthZero(f) => parse_property(suffix, *f),
      Self::FontWeight(f) => parse_property(suffix, *f),
      Self::Justify(f) => parse_property(suffix, *f),
      Self::Align(f) => parse_property(suffix, *f),
      Self::Overflow(f) => parse_property(suffix, *f),
      Self::BorderWidth(f) => parse_property(suffix, *f),
      Self::Rounded(f) => parse_property(suffix, *f),
      Self::GridTemplate(f) => parse_property(suffix, *f),
      Self::GridAuto(f) => parse_property(suffix, *f),
      Self::GridPlacement(f) => parse_property(suffix, *f),
      Self::GridSpan(f) => parse_property(suffix, *f),
      Self::LetterSpacing(f) => parse_property(suffix, *f),
      Self::FlexGrow(f) => parse_property(suffix, *f),
      Self::Aspect(f) => parse_property(suffix, *f),
      Self::TextAlign(f) => parse_property(suffix, *f),
      Self::ColorCurrent(f) => parse_property(suffix, *f),
      Self::ColorTransparent(f) => parse_property(suffix, *f),
      Self::Percentage(f) => parse_property(suffix, *f),
      Self::FontFamily(f) => parse_property(suffix, *f),
      Self::LineClamp(f) => parse_property(suffix, *f),
      Self::WhiteSpace(f) => parse_property(suffix, *f),
      Self::OverflowWrap(f) => parse_property(suffix, *f),
      Self::FontSize(f) => parse_property(suffix, *f),
      Self::LineHeight(f) => parse_property(suffix, *f),
      Self::Flex(f) => parse_property(suffix, *f),
      Self::Angle(f) => parse_property(suffix, *f),
    }
  }
}

pub static PREFIX_PARSERS: phf::Map<&str, &[PropertyParser]> = phf_map! {
  "object" => &[
    PropertyParser::ObjectFit(TailwindProperty::ObjectFit),
    PropertyParser::BgPosition(TailwindProperty::ObjectPosition),
  ],
  "bg" => &[
    PropertyParser::ColorTransparent(TailwindProperty::BackgroundColor),
    PropertyParser::BgImage(TailwindProperty::BackgroundImage),
    PropertyParser::BgPosition(TailwindProperty::BackgroundPosition),
    PropertyParser::BgSize(TailwindProperty::BackgroundSize),
  ],
  "bg-size" => &[PropertyParser::BgSize(TailwindProperty::BackgroundSize)],
  "bg-position" => &[PropertyParser::BgPosition(TailwindProperty::BackgroundPosition)],
  "w" => &[PropertyParser::LengthAuto(TailwindProperty::Width)],
  "h" => &[PropertyParser::LengthAuto(TailwindProperty::Height)],
  "min-w" => &[PropertyParser::LengthAuto(TailwindProperty::MinWidth)],
  "min-h" => &[PropertyParser::LengthAuto(TailwindProperty::MinHeight)],
  "max-w" => &[PropertyParser::LengthAuto(TailwindProperty::MaxWidth)],
  "max-h" => &[PropertyParser::LengthAuto(TailwindProperty::MaxHeight)],
  "size" => &[PropertyParser::LengthAuto(TailwindProperty::Size)],
  "font" => &[
    PropertyParser::FontWeight(TailwindProperty::FontWeight),
    PropertyParser::FontFamily(TailwindProperty::FontFamily),
  ],
  "gap-x" => &[PropertyParser::LengthZero(TailwindProperty::GapX)],
  "gap-y" => &[PropertyParser::LengthZero(TailwindProperty::GapY)],
  "gap" => &[PropertyParser::LengthZero(TailwindProperty::Gap)],
  "justify" => &[PropertyParser::Justify(TailwindProperty::Justify)],
  "content" => &[PropertyParser::Justify(TailwindProperty::Content)],
  "items" => &[PropertyParser::Align(TailwindProperty::Items)],
  "self" => &[PropertyParser::Align(TailwindProperty::AlignSelf)],
  "justify-self" => &[PropertyParser::Align(TailwindProperty::JustifySelf)],
  "justify-items" => &[PropertyParser::Align(TailwindProperty::JustifyItems)],
  "overflow-x" => &[PropertyParser::Overflow(TailwindProperty::OverflowX)],
  "overflow-y" => &[PropertyParser::Overflow(TailwindProperty::OverflowY)],
  "overflow" => &[PropertyParser::Overflow(TailwindProperty::Overflow)],
  "border" => &[
    PropertyParser::ColorCurrent(TailwindProperty::BorderColor),
    PropertyParser::BorderWidth(TailwindProperty::BorderWidth),
  ],
  "border-t" => &[PropertyParser::BorderWidth(TailwindProperty::BorderTopWidth)],
  "border-r" => &[PropertyParser::BorderWidth(TailwindProperty::BorderRightWidth)],
  "border-b" => &[PropertyParser::BorderWidth(TailwindProperty::BorderBottomWidth)],
  "border-l" => &[PropertyParser::BorderWidth(TailwindProperty::BorderLeftWidth)],
  "border-x" => &[PropertyParser::BorderWidth(TailwindProperty::BorderXWidth)],
  "border-y" => &[PropertyParser::BorderWidth(TailwindProperty::BorderYWidth)],
  "grow" | "flex-grow" => &[PropertyParser::FlexGrow(TailwindProperty::FlexGrow)],
  "shrink" | "flex-shrink" => &[PropertyParser::FlexGrow(TailwindProperty::FlexShrink)],
  "basis" | "flex-basis" => &[PropertyParser::LengthAuto(TailwindProperty::FlexBasis)],
  "aspect" => &[PropertyParser::Aspect(TailwindProperty::Aspect)],
  "text" => &[
    PropertyParser::FontSize(TailwindProperty::FontSize),
    PropertyParser::ColorCurrent(TailwindProperty::Color),
    PropertyParser::TextAlign(TailwindProperty::TextAlign),
  ],
  "decoration" => &[PropertyParser::ColorCurrent(TailwindProperty::TextDecorationColor)],
  "leading" => &[PropertyParser::LineHeight(TailwindProperty::LineHeight)],
  "opacity" => &[PropertyParser::Percentage(TailwindProperty::Opacity)],
  "line-clamp" => &[PropertyParser::LineClamp(TailwindProperty::LineClamp)],
  "whitespace" => &[PropertyParser::WhiteSpace(TailwindProperty::WhiteSpace)],
  "wrap" => &[PropertyParser::OverflowWrap(TailwindProperty::OverflowWrap)],
  "flex" => &[PropertyParser::Flex(TailwindProperty::Flex)],
  "origin" => &[PropertyParser::BgPosition(TailwindProperty::TransformOrigin)],
  "translate" => &[PropertyParser::LengthAuto(TailwindProperty::Translate)],
  "rotate" => &[PropertyParser::Angle(TailwindProperty::Rotate)],
  "scale" => &[PropertyParser::Percentage(TailwindProperty::Scale)],
  "scale-x" => &[PropertyParser::Percentage(TailwindProperty::ScaleX)],
  "scale-y" => &[PropertyParser::Percentage(TailwindProperty::ScaleY)],
  "translate-x" => &[PropertyParser::LengthAuto(TailwindProperty::TranslateX)],
  "translate-y" => &[PropertyParser::LengthAuto(TailwindProperty::TranslateY)],
  "m" => &[PropertyParser::LengthZero(TailwindProperty::Margin)],
  "mx" | "ms" => &[PropertyParser::LengthZero(TailwindProperty::MarginX)],
  "my" | "me" => &[PropertyParser::LengthZero(TailwindProperty::MarginY)],
  "mt" => &[PropertyParser::LengthZero(TailwindProperty::MarginTop)],
  "mr" => &[PropertyParser::LengthZero(TailwindProperty::MarginRight)],
  "mb" => &[PropertyParser::LengthZero(TailwindProperty::MarginBottom)],
  "ml" => &[PropertyParser::LengthZero(TailwindProperty::MarginLeft)],
  "p" => &[PropertyParser::LengthZero(TailwindProperty::Padding)],
  "px" | "ps" => &[PropertyParser::LengthZero(TailwindProperty::PaddingX)],
  "py" | "pe" => &[PropertyParser::LengthZero(TailwindProperty::PaddingY)],
  "pt" => &[PropertyParser::LengthZero(TailwindProperty::PaddingTop)],
  "pr" => &[PropertyParser::LengthZero(TailwindProperty::PaddingRight)],
  "pb" => &[PropertyParser::LengthZero(TailwindProperty::PaddingBottom)],
  "pl" => &[PropertyParser::LengthZero(TailwindProperty::PaddingLeft)],
  "inset" => &[PropertyParser::LengthAuto(TailwindProperty::Inset)],
  "inset-x" => &[PropertyParser::LengthAuto(TailwindProperty::InsetX)],
  "inset-y" => &[PropertyParser::LengthAuto(TailwindProperty::InsetY)],
  "top" => &[PropertyParser::LengthAuto(TailwindProperty::Top)],
  "right" => &[PropertyParser::LengthAuto(TailwindProperty::Right)],
  "bottom" => &[PropertyParser::LengthAuto(TailwindProperty::Bottom)],
  "left" => &[PropertyParser::LengthAuto(TailwindProperty::Left)],
  "rounded" => &[PropertyParser::Rounded(TailwindProperty::Rounded)],
  "rounded-t" => &[PropertyParser::Rounded(TailwindProperty::RoundedTop)],
  "rounded-r" => &[PropertyParser::Rounded(TailwindProperty::RoundedRight)],
  "rounded-b" => &[PropertyParser::Rounded(TailwindProperty::RoundedBottom)],
  "rounded-l" => &[PropertyParser::Rounded(TailwindProperty::RoundedLeft)],
  "rounded-tl" => &[PropertyParser::Rounded(TailwindProperty::RoundedTopLeft)],
  "rounded-tr" => &[PropertyParser::Rounded(TailwindProperty::RoundedTopRight)],
  "rounded-br" => &[PropertyParser::Rounded(TailwindProperty::RoundedBottomRight)],
  "rounded-bl" => &[PropertyParser::Rounded(TailwindProperty::RoundedBottomLeft)],
  "grid-cols" => &[PropertyParser::GridTemplate(TailwindProperty::GridTemplateColumns)],
  "grid-rows" => &[PropertyParser::GridTemplate(TailwindProperty::GridTemplateRows)],
  "auto-cols" => &[PropertyParser::GridAuto(TailwindProperty::GridAutoColumns)],
  "auto-rows" => &[PropertyParser::GridAuto(TailwindProperty::GridAutoRows)],
  "col-span" => &[PropertyParser::GridSpan(TailwindProperty::GridColumn)],
  "row-span" => &[PropertyParser::GridSpan(TailwindProperty::GridRow)],
  "col-start" => &[PropertyParser::GridPlacement(TailwindProperty::GridColumnStart)],
  "col-end" => &[PropertyParser::GridPlacement(TailwindProperty::GridColumnEnd)],
  "row-start" => &[PropertyParser::GridPlacement(TailwindProperty::GridRowStart)],
  "row-end" => &[PropertyParser::GridPlacement(TailwindProperty::GridRowEnd)],
  "tracking" => &[PropertyParser::LetterSpacing(TailwindProperty::LetterSpacing)],
};

pub static FIXED_PROPERTIES: phf::Map<&str, TailwindProperty> = phf_map! {
  "border" => TailwindProperty::BorderWidth(TwBorderWidth(LengthUnit::Px(1.0))),
  "box-border" => TailwindProperty::BoxSizing(BoxSizing::BorderBox),
  "box-content" => TailwindProperty::BoxSizing(BoxSizing::ContentBox),
  "inline" => TailwindProperty::Display(Display::Inline),
  "block" => TailwindProperty::Display(Display::Block),
  "flex" => TailwindProperty::Display(Display::Flex),
  "grid" => TailwindProperty::Display(Display::Grid),
  "hidden" => TailwindProperty::Display(Display::None),
  "bg-repeat" => TailwindProperty::BackgroundRepeat(BackgroundRepeat::repeat()),
  "bg-no-repeat" => TailwindProperty::BackgroundRepeat(BackgroundRepeat::no_repeat()),
  "bg-space" => TailwindProperty::BackgroundRepeat(BackgroundRepeat::space()),
  "bg-round" => TailwindProperty::BackgroundRepeat(BackgroundRepeat::round()),
  "bg-repeat-x" => TailwindProperty::BackgroundRepeat(BackgroundRepeat(
    BackgroundRepeatStyle::Repeat,
    BackgroundRepeatStyle::NoRepeat,
  )),
  "bg-repeat-y" => TailwindProperty::BackgroundRepeat(BackgroundRepeat(
    BackgroundRepeatStyle::NoRepeat,
    BackgroundRepeatStyle::Repeat,
  )),
  "aspect-auto" => TailwindProperty::Aspect(AspectRatio::Auto),
  "aspect-square" => TailwindProperty::Aspect(AspectRatio::Ratio(1.0)),
  "aspect-video" => TailwindProperty::Aspect(AspectRatio::Ratio(16.0 / 9.0)),
  "flex-grow" | "grow" => TailwindProperty::FlexGrow(FlexGrow(1.0)),
  "flex-shrink" | "shrink" => TailwindProperty::FlexShrink(FlexGrow(1.0)),
  "flex-row" => TailwindProperty::FlexDirection(FlexDirection::Row),
  "flex-row-reverse" => TailwindProperty::FlexDirection(FlexDirection::RowReverse),
  "flex-col" => TailwindProperty::FlexDirection(FlexDirection::Column),
  "flex-col-reverse" => TailwindProperty::FlexDirection(FlexDirection::ColumnReverse),
  "flex-wrap" => TailwindProperty::FlexWrap(FlexWrap::Wrap),
  "flex-wrap-reverse" => TailwindProperty::FlexWrap(FlexWrap::WrapReverse),
  "flex-nowrap" => TailwindProperty::FlexWrap(FlexWrap::NoWrap),
  "flex-auto" => TailwindProperty::Flex(Flex::auto()),
  "flex-initial" => TailwindProperty::Flex(Flex::initial()),
  "flex-none" => TailwindProperty::Flex(Flex::none()),
  "absolute" => TailwindProperty::Position(Position::Absolute),
  "relative" => TailwindProperty::Position(Position::Relative),
  "uppercase" => TailwindProperty::TextTransform(TextTransform::Uppercase),
  "lowercase" => TailwindProperty::TextTransform(TextTransform::Lowercase),
  "capitalize" => TailwindProperty::TextTransform(TextTransform::Capitalize),
  "normal-case" => TailwindProperty::TextTransform(TextTransform::None),
  "italic" => TailwindProperty::FontStyle(FontStyle::italic()),
  "not-italic" => TailwindProperty::FontStyle(FontStyle::normal()),
  "w-screen" => TailwindProperty::Width(LengthUnit::Vw(100.0)),
  "h-screen" => TailwindProperty::Height(LengthUnit::Vh(100.0)),
  "min-w-screen" => TailwindProperty::MinWidth(LengthUnit::Vw(100.0)),
  "min-h-screen" => TailwindProperty::MinHeight(LengthUnit::Vh(100.0)),
  "max-w-screen" => TailwindProperty::MaxWidth(LengthUnit::Vw(100.0)),
  "max-h-screen" => TailwindProperty::MaxHeight(LengthUnit::Vh(100.0)),
  "truncate" => TailwindProperty::Truncate,
  "text-ellipsis" => TailwindProperty::TextOverflow(TextOverflow::Ellipsis),
  "text-clip" => TailwindProperty::TextOverflow(TextOverflow::Clip),
  "text-wrap" => TailwindProperty::TextWrap(TextWrapMode::Wrap),
  "text-nowrap" => TailwindProperty::TextWrap(TextWrapMode::NoWrap),
  "break-normal" => TailwindProperty::WordBreak(WordBreak::Normal),
  "break-all" => TailwindProperty::WordBreak(WordBreak::BreakAll),
  "break-keep" => TailwindProperty::WordBreak(WordBreak::KeepAll),
  "grid-flow-row" => TailwindProperty::GridAutoFlow(GridAutoFlow::row()),
  "grid-flow-col" => TailwindProperty::GridAutoFlow(GridAutoFlow::column()),
  "grid-flow-row-dense" | "grid-flow-dense" => TailwindProperty::GridAutoFlow(GridAutoFlow::row().dense()),
  "grid-flow-col-dense" => TailwindProperty::GridAutoFlow(GridAutoFlow::column().dense()),
  "shadow-sm" => TailwindProperty::Shadow(BoxShadow {
    inset: false,
    offset_x: LengthUnit::Px(1.0),
    offset_y: LengthUnit::Px(1.0),
    blur_radius: LengthUnit::Px(1.0),
    spread_radius: LengthUnit::Px(0.0),
    color: ColorInput::Value(Color([0, 0, 0, 6])),
  }),
  "shadow" => TailwindProperty::Shadow(BoxShadow {
    inset: false,
    offset_x: LengthUnit::Px(1.0),
    offset_y: LengthUnit::Px(1.0),
    blur_radius: LengthUnit::Px(1.0),
    spread_radius: LengthUnit::Px(0.0),
    color: ColorInput::Value(Color([0, 0, 0, 19])),
  }),
  "shadow-md" => TailwindProperty::Shadow(BoxShadow {
    inset: false,
    offset_x: LengthUnit::Px(1.0),
    offset_y: LengthUnit::Px(1.0),
    blur_radius: LengthUnit::Px(3.0),
    spread_radius: LengthUnit::Px(0.0),
    color: ColorInput::Value(Color([0, 0, 0, 32])),
  }),
  "shadow-lg" => TailwindProperty::Shadow(BoxShadow {
    inset: false,
    offset_x: LengthUnit::Px(1.0),
    offset_y: LengthUnit::Px(1.0),
    blur_radius: LengthUnit::Px(8.0),
    spread_radius: LengthUnit::Px(0.0),
    color: ColorInput::Value(Color([0, 0, 0, 38])),
  }),
  "shadow-xl" => TailwindProperty::Shadow(BoxShadow {
    inset: false,
    offset_x: LengthUnit::Px(1.0),
    offset_y: LengthUnit::Px(1.0),
    blur_radius: LengthUnit::Px(20.0),
    spread_radius: LengthUnit::Px(0.0),
    color: ColorInput::Value(Color([0, 0, 0, 48])),
  }),
  "shadow-2xl" => TailwindProperty::Shadow(BoxShadow {
    inset: false,
    offset_x: LengthUnit::Px(1.0),
    offset_y: LengthUnit::Px(1.0),
    blur_radius: LengthUnit::Px(30.0),
    spread_radius: LengthUnit::Px(0.0),
    color: ColorInput::Value(Color([0, 0, 0, 64])),
  }),
  "shadow-none" => TailwindProperty::Shadow(BoxShadow {
    inset: false,
    offset_x: LengthUnit::Px(0.0),
    offset_y: LengthUnit::Px(0.0),
    blur_radius: LengthUnit::Px(0.0),
    spread_radius: LengthUnit::Px(0.0),
    color: ColorInput::Value(Color([0, 0, 0, 0])),
  }),
};
