/**
 * ContentTab Component
 *
 * First tab - shows content-specific settings based on element type:
 * - Price elements: Decimal settings, Line-through settings
 * - Currency elements: Currency symbol, custom image
 * - Discount badge: Format settings (percentage/amount/custom)
 * - Text elements: Text content, alignment, width mode
 * - Variable Price Range: Display mode, separator, prefix, decimal settings
 * - Other elements: Basic content info
 */

import type {
  CanvasElement,
  PriceElement,
  CurrencyElement,
  DiscountBadgeElement,
  TextElement,
  VariablePriceRangeElement,
  DecimalSettings as DecimalSettingsType,
  LineThroughSettings as LineThroughSettingsType,
} from "@/types";
import { DecimalBlock, CurrencyBlock } from "../blocks";
import { LineThroughGroup } from "../groups";
import { ButtonGroup, Select, Switch } from "../ui";

interface ContentTabProps {
  element: CanvasElement;
  onUpdate: (updates: Partial<CanvasElement>) => void;
  compact?: boolean;
  // For cascading decimal typography popover
  decimalTypographyOpen?: boolean;
  onDecimalTypographyToggle?: (open: boolean, field?: "decimal" | "minDecimal" | "maxDecimal") => void;
}

export function ContentTab({
  element,
  onUpdate,
  compact = false,
  decimalTypographyOpen = false,
  onDecimalTypographyToggle,
}: ContentTabProps) {
  const isPriceElement = element.type === "regularPrice" || element.type === "salePrice";
  const isCurrencyElement = element.type === "currencySymbol";
  const isDiscountBadge = element.type === "discountBadge";
  const isTextElement = element.type === "text";
  const isVariablePriceRange = element.type === "variablePriceRange";

  // Class names based on mode
  const sectionClass = compact ? "floating-settings__section floating-settings__section--scrollable" : "settings-section";
  const groupClass = compact ? "floating-settings__group" : "settings-field";
  const labelClass = compact ? "floating-settings__label" : "settings-label";
  const inputClass = compact ? "floating-settings__input" : "settings-input";
  const textareaClass = compact ? "floating-settings__input floating-settings__textarea" : "settings-input settings-textarea";

  // Price element content
  if (isPriceElement) {
    const priceElement = element as PriceElement;
    return (
      <div className={sectionClass}>
        <DecimalBlock
          decimal={priceElement.decimal}
          onUpdate={(decimal: DecimalSettingsType) => onUpdate({ decimal } as Partial<CanvasElement>)}
          compact={compact}
          typographyOpen={decimalTypographyOpen}
          onTypographyToggle={(open) => onDecimalTypographyToggle?.(open, "decimal")}
        />

        <div className="mt-4">
          <LineThroughGroup
            lineThrough={
              priceElement.lineThrough || { enabled: false, style: "single", direction: "horizontal", color: "#ef4444", thickness: 2 }
            }
            onUpdate={(lineThrough: LineThroughSettingsType) => onUpdate({ lineThrough } as Partial<CanvasElement>)}
            compact={compact}
          />
        </div>
      </div>
    );
  }

  // Currency element content
  if (isCurrencyElement) {
    const currencyElement = element as CurrencyElement;
    return (
      <div className={sectionClass}>
        <CurrencyBlock element={currencyElement} onUpdate={onUpdate} compact={compact} />
      </div>
    );
  }

  // Discount badge content
  if (isDiscountBadge) {
    const badgeElement = element as DiscountBadgeElement;
    const formatOptions = [
      { value: "percentage", label: "Percentage (%)" },
      { value: "amount", label: "Amount ($)" },
      { value: "custom", label: "Custom" },
    ];

    return (
      <div className={sectionClass}>
        <div className={groupClass}>
          <label className={labelClass}>Display Format</label>
          {compact ? (
            <ButtonGroup
              options={formatOptions}
              value={badgeElement.format || "percentage"}
              onChange={(value) => onUpdate({ format: value as "percentage" | "amount" | "custom" })}
              size="compact"
            />
          ) : (
            <Select
              value={badgeElement.format || "percentage"}
              onValueChange={(value) => onUpdate({ format: value as "percentage" | "amount" | "custom" })}
              options={formatOptions}
              size={compact ? "compact" : "default"}
            />
          )}
        </div>

        {badgeElement.format === "custom" && (
          <div className={`${groupClass} mt-3`}>
            <label className={labelClass}>Custom Format</label>
            <textarea
              className={textareaClass}
              value={badgeElement.customFormat || "-{discount}%"}
              onChange={(e) => onUpdate({ customFormat: e.target.value })}
              placeholder="-{discount}%"
              rows={3}
            />
            <p className="text-xs text-text-muted mt-1">
              Use {"\n"} for new line. Placeholders: {"{{discount}}"}, {"{{discountAmount}}"}
            </p>
          </div>
        )}
      </div>
    );
  }

  // Text element content
  if (isTextElement) {
    const textElement = element as TextElement;
    const textAlignOptions = [
      { value: "left", label: "Left" },
      { value: "center", label: "Center" },
      { value: "right", label: "Right" },
      { value: "justify", label: "Justify" },
    ];
    const widthModeOptions = [
      { value: "auto", label: "Auto" },
      { value: "full", label: "Full" },
      { value: "custom", label: "Custom" },
    ];

    return (
      <div className={sectionClass}>
        <div className={groupClass}>
          <label className={labelClass}>Text Content</label>
          <textarea
            className={textareaClass}
            value={textElement.text || ""}
            onChange={(e) => onUpdate({ text: e.target.value })}
            placeholder="Enter your text here..."
            rows={4}
          />
          <p className="text-xs text-text-muted mt-1">Use Enter for new lines.</p>
        </div>

        <div className={`${groupClass} mt-3`}>
          <label className={labelClass}>Text Align</label>
          <ButtonGroup
            options={textAlignOptions}
            value={textElement.textAlign || "left"}
            onChange={(value) =>
              onUpdate({
                textAlign: value as "left" | "center" | "right" | "justify",
              })
            }
            size={compact ? "compact" : "default"}
          />
        </div>

        <div className={`${groupClass} mt-3`}>
          <label className={labelClass}>Width Mode</label>
          <ButtonGroup
            options={widthModeOptions}
            value={textElement.widthMode || "auto"}
            onChange={(value) => onUpdate({ widthMode: value as "auto" | "full" | "custom" })}
            size={compact ? "compact" : "default"}
          />
        </div>

        {textElement.widthMode === "custom" && (
          <div className={`${groupClass} mt-3`}>
            <label className={labelClass}>Custom Width (px)</label>
            <input
              type="number"
              className={inputClass}
              value={textElement.customWidth || 200}
              onChange={(e) => onUpdate({ customWidth: parseInt(e.target.value, 10) || 200 })}
              min={50}
              max={1000}
            />
          </div>
        )}
      </div>
    );
  }

  // Variable Price Range element content
  if (isVariablePriceRange) {
    const rangeElement = element as VariablePriceRangeElement;
    const displayModeOptions = [
      { value: "range", label: "Range" },
      { value: "from", label: "From" },
      { value: "up-to", label: "Up to" },
      { value: "min-only", label: "Min" },
      { value: "max-only", label: "Max" },
    ];

    const showPrefixField = rangeElement.displayMode === "from" || rangeElement.displayMode === "up-to";

    return (
      <div className={sectionClass}>
        {/* Display Mode */}
        <div className={groupClass}>
          <label className={labelClass}>Display Mode</label>
          {compact ? (
            <ButtonGroup
              options={displayModeOptions}
              value={rangeElement.displayMode || "range"}
              onChange={(value) =>
                onUpdate({
                  displayMode: value as VariablePriceRangeElement["displayMode"],
                })
              }
              size="compact"
            />
          ) : (
            <Select
              value={rangeElement.displayMode || "range"}
              onValueChange={(value) =>
                onUpdate({
                  displayMode: value as VariablePriceRangeElement["displayMode"],
                })
              }
              options={displayModeOptions}
              size="default"
            />
          )}
          <p className="text-xs text-text-muted mt-1">
            {rangeElement.displayMode === "range" && "Shows: $19.99 – $99.99"}
            {rangeElement.displayMode === "from" && "Shows: From $19.99"}
            {rangeElement.displayMode === "up-to" && "Shows: Up to $99.99"}
            {rangeElement.displayMode === "min-only" && "Shows: $19.99 (lowest)"}
            {rangeElement.displayMode === "max-only" && "Shows: $99.99 (highest)"}
          </p>
        </div>

        {/* Separator (for range mode) */}
        {rangeElement.displayMode === "range" && (
          <div className={`${groupClass} mt-3`}>
            <label className={labelClass}>Separator</label>
            <input
              type="text"
              className={inputClass}
              value={rangeElement.separator || " – "}
              onChange={(e) => onUpdate({ separator: e.target.value })}
              placeholder=" – "
            />
            <p className="text-xs text-text-muted mt-1">Text between min and max prices</p>
          </div>
        )}

        {/* Prefix Text (for from/up-to modes) */}
        {showPrefixField && (
          <div className={`${groupClass} mt-3`}>
            <label className={labelClass}>Prefix Text</label>
            <input
              type="text"
              className={inputClass}
              value={rangeElement.prefixText ?? (rangeElement.displayMode === "up-to" ? "Up to" : "From")}
              onChange={(e) => onUpdate({ prefixText: e.target.value })}
              placeholder={rangeElement.displayMode === "up-to" ? "Up to" : "From"}
            />
          </div>
        )}

        {/* Show Currency Symbol Toggle */}
        <div className={compact ? "floating-settings__row mt-3" : "settings-field-inline mt-3"}>
          <label className={labelClass}>Show Currency Symbol</label>
          <Switch
            checked={rangeElement.showCurrency ?? true}
            onCheckedChange={(checked) => onUpdate({ showCurrency: checked })}
            size={compact ? "compact" : "default"}
          />
        </div>

        {/* Min Price Decimal Settings */}
        {(rangeElement.displayMode === "range" || rangeElement.displayMode === "from" || rangeElement.displayMode === "min-only") && (
          <div className="mt-4">
            <h4 className={`${labelClass} font-medium mb-2`}>
              {rangeElement.displayMode === "range" ? "Min Price Decimals" : "Decimal Settings"}
            </h4>
            <DecimalBlock
              decimal={rangeElement.minDecimal}
              onUpdate={(decimal: DecimalSettingsType) => onUpdate({ minDecimal: decimal } as Partial<CanvasElement>)}
              compact={compact}
              typographyOpen={decimalTypographyOpen}
              onTypographyToggle={(open) => onDecimalTypographyToggle?.(open, "minDecimal")}
              hideShowCurrency
            />
          </div>
        )}

        {/* Max Price Decimal Settings (for range, up-to, and max-only modes) */}
        {(rangeElement.displayMode === "range" || rangeElement.displayMode === "up-to" || rangeElement.displayMode === "max-only") && (
          <div className="mt-4">
            <h4 className={`${labelClass} font-medium mb-2`}>
              {rangeElement.displayMode === "range" ? "Max Price Decimals" : "Decimal Settings"}
            </h4>
            <DecimalBlock
              decimal={rangeElement.maxDecimal}
              onUpdate={(decimal: DecimalSettingsType) => onUpdate({ maxDecimal: decimal } as Partial<CanvasElement>)}
              compact={compact}
              typographyOpen={decimalTypographyOpen}
              onTypographyToggle={(open) => onDecimalTypographyToggle?.(open, "maxDecimal")}
              hideShowCurrency
            />
          </div>
        )}
      </div>
    );
  }

  // Default content for other elements
  return (
    <div className={sectionClass}>
      <div className={groupClass}>
        <p className="text-xs text-text-muted">No content settings available for this element type.</p>
      </div>
    </div>
  );
}

export default ContentTab;
