/**
 * SettingsPanel Component
 *
 * Right sidebar for editing selected element OR container properties.
 * Uses the same tab structure as FloatingSettingsPanel but opens modals
 * instead of cascading popovers for complex settings.
 *
 * Shows:
 * - Element tabs (Content/Style/More) when an element is selected
 * - Container tabs (Spacing/Background/Border/HTML) when container is selected
 */

import { useState } from "react";
import * as Tabs from "@radix-ui/react-tabs";
import { GearIcon, ContainerIcon } from "@radix-ui/react-icons";

import { useCanvasStore, useSelectedElements, useContainerSelected, useContainerSettings } from "@/stores/canvasStore";
import type {
  CanvasElement,
  PriceElement,
  VariablePriceRangeElement,
  ResponsiveTypographySettings,
  ResponsiveBorderSettings,
  ContainerSettings,
} from "@/types";
import { createResponsiveValue, isResponsiveValue } from "@/types";

// Import shared tabs
import { ContentTab, StyleTab, MoreTab, ContainerSpacingTab, ContainerBackgroundTab, ContainerBorderTab, ContainerHooksTab } from "./tabs";
// Import modals for sidebar (instead of cascading popovers)
import { TypographyModal } from "./modals/TypographyModal";
import { BordersModal } from "./modals/BordersModal";

export function SettingsPanel() {
  // Modal states for sidebar (instead of cascading popovers)
  const [typographyModalOpen, setTypographyModalOpen] = useState(false);
  const [bordersModalOpen, setBordersModalOpen] = useState(false);
  const [decimalTypographyModalOpen, setDecimalTypographyModalOpen] = useState(false);
  const [activeDecimalField, setActiveDecimalField] = useState<"decimal" | "minDecimal" | "maxDecimal">("decimal");

  const selectedElements = useSelectedElements();
  const containerSelected = useContainerSelected();
  const containerSettings = useContainerSettings();
  const element = selectedElements.length === 1 ? selectedElements[0] : null;

  const updateElement = useCanvasStore((state) => state.updateElement);
  const updateContainerSettings = useCanvasStore((state) => state.updateContainerSettings);

  // Handle container settings update
  const handleContainerUpdate = (updates: Partial<ContainerSettings>) => {
    updateContainerSettings(updates);
  };

  // Container is selected - show container settings
  if (containerSelected) {
    return (
      <div className="settings-panel">
        <div className="settings-panel__header">
          <h3 className="settings-panel__title">
            <ContainerIcon className="w-4 h-4 inline mr-2" />
            Container Settings
          </h3>
        </div>

        <div className="settings-panel__content">
          <Tabs.Root defaultValue="spacing" className="w-full">
            <Tabs.List className="settings-tabs-list">
              <Tabs.Trigger value="spacing" className="settings-tab">
                Spacing
              </Tabs.Trigger>
              <Tabs.Trigger value="background" className="settings-tab">
                Background
              </Tabs.Trigger>
              <Tabs.Trigger value="border" className="settings-tab">
                Border
              </Tabs.Trigger>
              <Tabs.Trigger value="hooks" className="settings-tab">
                Hooks
              </Tabs.Trigger>
            </Tabs.List>

            {/* Spacing Tab - Padding/Margin */}
            <Tabs.Content value="spacing" className="settings-tab-content">
              <ContainerSpacingTab containerSettings={containerSettings} onUpdate={handleContainerUpdate} compact={false} />
            </Tabs.Content>

            {/* Background Tab */}
            <Tabs.Content value="background" className="settings-tab-content">
              <ContainerBackgroundTab containerSettings={containerSettings} onUpdate={handleContainerUpdate} compact={false} />
            </Tabs.Content>

            {/* Border Tab */}
            <Tabs.Content value="border" className="settings-tab-content">
              <ContainerBorderTab containerSettings={containerSettings} onUpdate={handleContainerUpdate} compact={false} />
            </Tabs.Content>

            {/* Custom HTML Tab */}
            <Tabs.Content value="hooks" className="settings-tab-content">
              <ContainerHooksTab compact={false} />
            </Tabs.Content>
          </Tabs.Root>
        </div>
      </div>
    );
  }

  // No element selected
  if (selectedElements.length === 0) {
    return (
      <div className="settings-panel">
        <div className="settings-panel__header">
          <h3 className="settings-panel__title">Settings</h3>
        </div>
        <div className="settings-panel__content">
          <div className="settings-panel__empty">Select an element to edit its properties</div>
        </div>
      </div>
    );
  }

  // Multiple elements selected
  if (selectedElements.length > 1) {
    return (
      <div className="settings-panel">
        <div className="settings-panel__header">
          <h3 className="settings-panel__title">Settings</h3>
        </div>
        <div className="settings-panel__content">
          <div className="settings-panel__empty">{selectedElements.length} elements selected</div>
        </div>
      </div>
    );
  }

  // Shouldn't happen but handle edge case
  if (!element) {
    return null;
  }

  const isPriceElement = element.type === "regularPrice" || element.type === "salePrice";
  const priceElement = isPriceElement ? (element as PriceElement) : null;

  const handleUpdate = (updates: Partial<CanvasElement>) => {
    updateElement(element.id, updates);
  };

  return (
    <div className="settings-panel">
      <div className="settings-panel__header">
        <h3 className="settings-panel__title">
          <GearIcon className="w-4 h-4 inline mr-2" />
          {element.name}
        </h3>
      </div>

      <div className="settings-panel__content">
        <Tabs.Root defaultValue="content" className="w-full">
          <Tabs.List className="settings-tabs-list">
            <Tabs.Trigger value="content" className="settings-tab">
              Content
            </Tabs.Trigger>
            <Tabs.Trigger value="style" className="settings-tab">
              Style
            </Tabs.Trigger>
            <Tabs.Trigger value="more" className="settings-tab">
              More
            </Tabs.Trigger>
          </Tabs.List>

          {/* Content Tab - Price decimals, currency, discount badge, text */}
          <Tabs.Content value="content" className="settings-tab-content">
            <ContentTab
              element={element}
              onUpdate={handleUpdate}
              compact={false}
              decimalTypographyOpen={decimalTypographyModalOpen}
              onDecimalTypographyToggle={(open, field) => {
                setDecimalTypographyModalOpen(open);
                if (field) {
                  setActiveDecimalField(field);
                }
              }}
            />
          </Tabs.Content>

          {/* Style Tab - Colors, Typography, Borders, Padding */}
          <Tabs.Content value="style" className="settings-tab-content">
            <StyleTab
              element={element}
              onUpdate={handleUpdate}
              typographyOpen={typographyModalOpen}
              onTypographyToggle={setTypographyModalOpen}
              bordersOpen={bordersModalOpen}
              onBordersToggle={setBordersModalOpen}
              compact={false}
            />
          </Tabs.Content>

          {/* More Tab - Transform, Animation, Custom HTML */}
          <Tabs.Content value="more" className="settings-tab-content">
            <MoreTab element={element} onUpdate={handleUpdate} compact={false} />
          </Tabs.Content>
        </Tabs.Root>
      </div>

      {/* Typography Modal (responsive) */}
      <TypographyModal
        open={typographyModalOpen}
        onOpenChange={setTypographyModalOpen}
        typography={element.typography}
        onUpdate={(typography: ResponsiveTypographySettings) => handleUpdate({ typography })}
        isResponsive={true}
      />

      {/* Borders Modal (responsive) */}
      <BordersModal
        open={bordersModalOpen}
        onOpenChange={setBordersModalOpen}
        border={element.border}
        onUpdate={(border: ResponsiveBorderSettings) => handleUpdate({ border })}
        isResponsive={true}
      />

      {/* Decimal Typography Modal for Price Elements */}
      {isPriceElement && priceElement && activeDecimalField === "decimal" && (
        <TypographyModal
          open={decimalTypographyModalOpen}
          onOpenChange={setDecimalTypographyModalOpen}
          typography={{
            fontFamily: priceElement.decimal.typography?.fontFamily ?? "Inter",
            fontSize: isResponsiveValue(priceElement.decimal.typography?.fontSize)
              ? priceElement.decimal.typography.fontSize
              : createResponsiveValue((priceElement.decimal.typography?.fontSize as number | undefined) ?? 14),
            fontWeight: isResponsiveValue(priceElement.decimal.typography?.fontWeight)
              ? priceElement.decimal.typography.fontWeight
              : createResponsiveValue((priceElement.decimal.typography?.fontWeight as number | undefined) ?? 400),
            fontStyle: priceElement.decimal.typography?.fontStyle ?? "normal",
            lineHeight: priceElement.decimal.typography?.lineHeight ?? 1.2,
            letterSpacing: isResponsiveValue(priceElement.decimal.typography?.letterSpacing)
              ? priceElement.decimal.typography.letterSpacing
              : createResponsiveValue((priceElement.decimal.typography?.letterSpacing as number | undefined) ?? 0),
            textTransform: priceElement.decimal.typography?.textTransform ?? "none",
            textDecoration: priceElement.decimal.typography?.textDecoration ?? "none",
          }}
          onUpdate={(typography: ResponsiveTypographySettings) =>
            handleUpdate({
              decimal: {
                ...priceElement.decimal,
                typography: {
                  fontFamily: typography.fontFamily,
                  fontSize: typography.fontSize,
                  fontWeight: typography.fontWeight,
                  fontStyle: typography.fontStyle,
                  lineHeight: typography.lineHeight,
                  letterSpacing: typography.letterSpacing,
                  textTransform: typography.textTransform,
                  textDecoration: typography.textDecoration,
                },
              },
            } as Partial<CanvasElement>)
          }
          isResponsive={true}
        />
      )}

      {/* Decimal Typography Modal for Variable Range - Min Decimal */}
      {element?.type === "variablePriceRange" &&
        activeDecimalField === "minDecimal" &&
        (() => {
          const rangeEl = element as VariablePriceRangeElement;
          const typo = rangeEl.minDecimal.typography;
          return (
            <TypographyModal
              open={decimalTypographyModalOpen}
              onOpenChange={setDecimalTypographyModalOpen}
              typography={{
                fontFamily: typo?.fontFamily ?? "Inter",
                fontSize: isResponsiveValue(typo?.fontSize)
                  ? typo.fontSize
                  : createResponsiveValue((typo?.fontSize as number | undefined) ?? 14),
                fontWeight: isResponsiveValue(typo?.fontWeight)
                  ? typo.fontWeight
                  : createResponsiveValue((typo?.fontWeight as number | undefined) ?? 400),
                fontStyle: typo?.fontStyle ?? "normal",
                lineHeight: typo?.lineHeight ?? 1.2,
                letterSpacing: isResponsiveValue(typo?.letterSpacing)
                  ? typo.letterSpacing
                  : createResponsiveValue((typo?.letterSpacing as number | undefined) ?? 0),
                textTransform: typo?.textTransform ?? "none",
                textDecoration: typo?.textDecoration ?? "none",
              }}
              onUpdate={(typography: ResponsiveTypographySettings) =>
                handleUpdate({
                  minDecimal: {
                    ...rangeEl.minDecimal,
                    typography,
                  },
                } as Partial<CanvasElement>)
              }
              isResponsive={true}
            />
          );
        })()}

      {/* Decimal Typography Modal for Variable Range - Max Decimal */}
      {element?.type === "variablePriceRange" &&
        activeDecimalField === "maxDecimal" &&
        (() => {
          const rangeEl = element as VariablePriceRangeElement;
          const typo = rangeEl.maxDecimal.typography;
          return (
            <TypographyModal
              open={decimalTypographyModalOpen}
              onOpenChange={setDecimalTypographyModalOpen}
              typography={{
                fontFamily: typo?.fontFamily ?? "Inter",
                fontSize: isResponsiveValue(typo?.fontSize)
                  ? typo.fontSize
                  : createResponsiveValue((typo?.fontSize as number | undefined) ?? 14),
                fontWeight: isResponsiveValue(typo?.fontWeight)
                  ? typo.fontWeight
                  : createResponsiveValue((typo?.fontWeight as number | undefined) ?? 400),
                fontStyle: typo?.fontStyle ?? "normal",
                lineHeight: typo?.lineHeight ?? 1.2,
                letterSpacing: isResponsiveValue(typo?.letterSpacing)
                  ? typo.letterSpacing
                  : createResponsiveValue((typo?.letterSpacing as number | undefined) ?? 0),
                textTransform: typo?.textTransform ?? "none",
                textDecoration: typo?.textDecoration ?? "none",
              }}
              onUpdate={(typography: ResponsiveTypographySettings) =>
                handleUpdate({
                  maxDecimal: {
                    ...rangeEl.maxDecimal,
                    typography,
                  },
                } as Partial<CanvasElement>)
              }
              isResponsive={true}
            />
          );
        })()}
    </div>
  );
}

export default SettingsPanel;
