/**
 * General Tab Component
 * Layout, sizing, and display options for swatches.
 */
import React from "react";
import { BaseTabProps } from "../types";
import { SlidingTabs } from "../../components/SlidingTabs";
import { RangeSlider } from "../../components/RangeSlider";
import { Toggle } from "../../components/Toggle";
import { HighlightableField } from "../../components/HighlightableField";
import { coerceInt } from "../../constants";

export interface GeneralTabProps extends BaseTabProps {
  activeGeneralSubTab: "layout" | "size" | "options";
  setActiveGeneralSubTab: React.Dispatch<
    React.SetStateAction<"layout" | "size" | "options">
  >;
  contentOverride?: React.ReactNode | null;
  contentOverrideMode?: Partial<
    Record<"layout" | "size" | "options", "append" | "replace">
  >;
}

export function GeneralTab({
  settings,
  setSettings,
  activeGeneralSubTab,
  setActiveGeneralSubTab,
  contentOverride,
  contentOverrideMode,
  adminColor: _adminColor,
}: GeneralTabProps) {
  // Server-side settings normalization keeps the base layout contract stable.
  const layout = settings.layout === "wrap" ? "wrap" : "wrap";
  const shape = settings.shape === "square" ? "square" : "square";
  const selectorStyle =
    settings.swatch_style === "underline" ? "underline" : "underline";
  const swatchWidth = coerceInt(settings.swatch_width, 32);
  const swatchHeight = coerceInt(settings.swatch_height, 32);
  const swatchGap = coerceInt(settings.swatch_gap, 12);

  const layoutPaddingTop = coerceInt(settings.layout_padding_top, 5);
  const layoutPaddingRight = coerceInt(settings.layout_padding_right, 5);
  const layoutPaddingBottom = coerceInt(settings.layout_padding_bottom, 5);
  const layoutPaddingLeft = coerceInt(settings.layout_padding_left, 5);

  const externalPaddingTop = coerceInt(settings.external_padding_top ?? 5, 5);
  const externalPaddingRight = coerceInt(
    settings.external_padding_right ?? 5,
    5,
  );
  const externalPaddingBottom = coerceInt(
    settings.external_padding_bottom ?? 5,
    5,
  );
  const externalPaddingLeft = coerceInt(settings.external_padding_left ?? 5, 5);
  const layoutOverrideMode = contentOverrideMode?.layout ?? "append";
  const sizeOverrideMode = contentOverrideMode?.size ?? "append";
  const optionsOverrideMode = contentOverrideMode?.options ?? "append";

  return (
    <div className="b3-wvs-space-y-8">
      <h2 className="b3-wvs-text-xl b3-wvs-font-semibold">General</h2>

      {/* Sub-tab Navigation */}
      <div className="b3-wvs-mb-6">
        <SlidingTabs
          activeTab={activeGeneralSubTab}
          onChange={(id) =>
            setActiveGeneralSubTab(id as "layout" | "size" | "options")
          }
          tabs={[
            { id: "layout", label: "Layout & Display" },
            { id: "size", label: "Size & Dimensions" },
            { id: "options", label: "Labels & Options" },
          ]}
        />
      </div>

      {/* Tab Content */}
      <div>
        {/* Layout & Display Tab */}
        {activeGeneralSubTab === "layout" && (
          <div className="b3-wvs-space-y-6">
            {layoutOverrideMode !== "replace" ? (
              <>
                {/* Layout Selection */}
                <HighlightableField id="general-layout">
                  <div>
                    <label className="b3-wvs-block b3-wvs-text-sm b3-wvs-font-medium b3-wvs-text-gray-700 b3-wvs-mb-3">
                      Layout
                    </label>
                    <div className="b3-wvs-choice-grid b3-wvs-choice-grid--layout">
                      {(
                        [
                          {
                            value: "wrap",
                            label: "Wrap",
                            desc: "Wraps to new lines",
                            icon: (
                              <svg
                                className="b3-wvs-w-8 b3-wvs-h-8"
                                viewBox="0 0 32 32"
                                fill="none"
                                stroke="currentColor"
                                strokeWidth="1.5"
                              >
                                <rect x="4" y="6" width="6" height="6" rx="1" />
                                <rect
                                  x="13"
                                  y="6"
                                  width="6"
                                  height="6"
                                  rx="1"
                                />
                                <rect
                                  x="22"
                                  y="6"
                                  width="6"
                                  height="6"
                                  rx="1"
                                />
                                <rect
                                  x="4"
                                  y="15"
                                  width="6"
                                  height="6"
                                  rx="1"
                                />
                                <rect
                                  x="13"
                                  y="15"
                                  width="6"
                                  height="6"
                                  rx="1"
                                />
                              </svg>
                            ),
                          },
                        ] as const
                      ).map((layoutOption) => {
                        return (
                          <button
                            key={layoutOption.value}
                            type="button"
                            onClick={() => {
                              setSettings({
                                ...settings,
                                layout: "wrap",
                                swatch_style: "underline",
                              });
                            }}
                            className={`b3-wvs-relative b3-wvs-w-full b3-wvs-min-w-0 b3-wvs-p-3 b3-wvs-border b3-wvs-rounded-lg b3-wvs-text-center b3-wvs-transition-all ${
                              layout === layoutOption.value
                                ? "b3-wvs-border-blue-500 b3-wvs-bg-blue-50 b3-wvs-ring-2 b3-wvs-ring-blue-200"
                                : "b3-wvs-border-gray-200 hover:b3-wvs-border-gray-300 hover:b3-wvs-bg-gray-50"
                            }`}
                          >
                            <div className="b3-wvs-flex b3-wvs-justify-center b3-wvs-mb-2 b3-wvs-text-gray-600">
                              {layoutOption.icon}
                            </div>
                            <div className="b3-wvs-text-sm b3-wvs-font-medium">
                              {layoutOption.label}
                            </div>
                            <div className="b3-wvs-text-xs b3-wvs-text-gray-500 b3-wvs-mt-0.5">
                              {layoutOption.desc}
                            </div>
                          </button>
                        );
                      })}
                    </div>
                  </div>
                </HighlightableField>

                <HighlightableField id="general-selector-style">
                  <div>
                    <label className="b3-wvs-block b3-wvs-text-sm b3-wvs-font-medium b3-wvs-text-gray-700 b3-wvs-mb-3">
                      Selector Style
                    </label>
                    <div className="b3-wvs-choice-grid b3-wvs-choice-grid--selector">
                      <button
                        type="button"
                        onClick={() =>
                          setSettings({
                            ...settings,
                            swatch_style: "underline",
                          })
                        }
                        className={`b3-wvs-w-full b3-wvs-min-w-0 b3-wvs-p-4 b3-wvs-border b3-wvs-rounded-lg b3-wvs-text-center b3-wvs-transition-all ${
                          selectorStyle === "underline"
                            ? "b3-wvs-border-blue-500 b3-wvs-bg-blue-50 b3-wvs-ring-2 b3-wvs-ring-blue-200"
                            : "b3-wvs-border-gray-200 hover:b3-wvs-border-gray-300 hover:b3-wvs-bg-gray-50"
                        }`}
                      >
                        <div className="b3-wvs-flex b3-wvs-justify-center b3-wvs-mb-2">
                          <svg
                            className="b3-wvs-w-12 b3-wvs-h-10"
                            viewBox="0 0 48 40"
                            fill="none"
                          >
                            <rect
                              x="4"
                              y="8"
                              width="16"
                              height="16"
                              rx="2"
                              fill="#e5e7eb"
                              stroke="#9ca3af"
                              strokeWidth="1"
                            />
                            <rect
                              x="24"
                              y="8"
                              width="16"
                              height="16"
                              rx="2"
                              fill="#dbeafe"
                              stroke="#3b82f6"
                              strokeWidth="1"
                            />
                            <rect
                              x="24"
                              y="28"
                              width="16"
                              height="3"
                              rx="1"
                              fill="#3b82f6"
                            />
                          </svg>
                        </div>
                        <div className="b3-wvs-text-sm b3-wvs-font-medium">
                          Underline
                        </div>
                        <div className="b3-wvs-text-xs b3-wvs-text-gray-500 b3-wvs-mt-0.5">
                          Line below selected
                        </div>
                      </button>
                    </div>
                  </div>
                </HighlightableField>

                <HighlightableField id="general-shape">
                  <div>
                    <label className="b3-wvs-block b3-wvs-text-sm b3-wvs-font-medium b3-wvs-text-gray-700 b3-wvs-mb-3">
                      Shape
                    </label>
                    <div className="b3-wvs-choice-grid b3-wvs-choice-grid--shape">
                      <button
                        type="button"
                        onClick={() => {
                          setSettings({ ...settings, shape: "square" });
                        }}
                        className={`b3-wvs-relative b3-wvs-w-full b3-wvs-min-w-0 b3-wvs-p-4 b3-wvs-border b3-wvs-rounded-lg b3-wvs-text-center b3-wvs-transition-all ${
                          shape === "square"
                            ? "b3-wvs-border-blue-500 b3-wvs-bg-blue-50 b3-wvs-ring-2 b3-wvs-ring-blue-200"
                            : "b3-wvs-border-gray-200 hover:b3-wvs-border-gray-300 hover:b3-wvs-bg-gray-50"
                        }`}
                      >
                        <div className="b3-wvs-flex b3-wvs-justify-center b3-wvs-mb-2 b3-wvs-text-gray-600">
                          <svg
                            className="b3-wvs-w-10 b3-wvs-h-10"
                            viewBox="0 0 40 40"
                            fill="none"
                            stroke="currentColor"
                            strokeWidth="2"
                          >
                            <rect x="8" y="8" width="24" height="24" />
                          </svg>
                        </div>
                        <div className="b3-wvs-text-sm b3-wvs-font-medium">
                          Square
                        </div>
                        <div className="b3-wvs-text-xs b3-wvs-text-gray-500 b3-wvs-mt-0.5">
                          Sharp corners
                        </div>
                      </button>
                    </div>
                  </div>
                </HighlightableField>

                <HighlightableField id="general-swatch-spacing">
                  <div>
                    <RangeSlider
                      label="Swatch Spacing"
                      description="Gap between swatch options."
                      value={swatchGap}
                      min={0}
                      max={32}
                      unit="px"
                      onChange={(val) =>
                        setSettings({ ...settings, swatch_gap: val })
                      }
                    />
                  </div>
                </HighlightableField>
              </>
            ) : null}
            {contentOverride}
          </div>
        )}

        {/* Size & Dimensions Tab */}
        {activeGeneralSubTab === "size" && (
          <div className="b3-wvs-space-y-6">
            {sizeOverrideMode !== "replace" ? (
              <>
                <HighlightableField id="general-swatch-size">
                  <div>
                    <label className="b3-wvs-block b3-wvs-text-sm b3-wvs-font-medium b3-wvs-text-gray-700 b3-wvs-mb-3">
                      Color Swatch Size
                    </label>
                    <div className="b3-wvs-space-y-4">
                      <RangeSlider
                        label="Width"
                        value={swatchWidth}
                        min={24}
                        max={60}
                        unit="px"
                        onChange={(val) =>
                          setSettings({ ...settings, swatch_width: val })
                        }
                      />
                      <RangeSlider
                        label="Height"
                        value={swatchHeight}
                        min={24}
                        max={60}
                        unit="px"
                        onChange={(val) =>
                          setSettings({ ...settings, swatch_height: val })
                        }
                      />
                    </div>
                  </div>
                </HighlightableField>

                <HighlightableField id="general-internal-padding">
                  <div>
                    <label className="b3-wvs-block b3-wvs-text-sm b3-wvs-font-medium b3-wvs-text-gray-700">
                      Internal Layout Padding
                    </label>
                    <p className="b3-wvs-text-xs b3-wvs-text-gray-500 b3-wvs-mb-2">
                      Padding inside the swatch layout container
                    </p>
                    <div className="b3-wvs-grid b3-wvs-grid-cols-1 b3-wvs-gap-3">
                      <RangeSlider
                        label="Top"
                        value={layoutPaddingTop}
                        min={0}
                        max={48}
                        unit="px"
                        onChange={(val) =>
                          setSettings({ ...settings, layout_padding_top: val })
                        }
                      />
                      <RangeSlider
                        label="Right"
                        value={layoutPaddingRight}
                        min={0}
                        max={48}
                        unit="px"
                        onChange={(val) =>
                          setSettings({
                            ...settings,
                            layout_padding_right: val,
                          })
                        }
                      />
                      <RangeSlider
                        label="Bottom"
                        value={layoutPaddingBottom}
                        min={0}
                        max={48}
                        unit="px"
                        onChange={(val) =>
                          setSettings({
                            ...settings,
                            layout_padding_bottom: val,
                          })
                        }
                      />
                      <RangeSlider
                        label="Left"
                        value={layoutPaddingLeft}
                        min={0}
                        max={48}
                        unit="px"
                        onChange={(val) =>
                          setSettings({ ...settings, layout_padding_left: val })
                        }
                      />
                    </div>
                  </div>
                </HighlightableField>

                <HighlightableField id="general-external-padding">
                  <div>
                    <label className="b3-wvs-block b3-wvs-text-sm b3-wvs-font-medium b3-wvs-text-gray-700">
                      External Layout Padding
                    </label>
                    <p className="b3-wvs-text-xs b3-wvs-text-gray-500 b3-wvs-mb-2">
                      Padding outside the swatch layout container (spacing from
                      other elements)
                    </p>
                    <div className="b3-wvs-grid b3-wvs-grid-cols-1 b3-wvs-gap-3">
                      <RangeSlider
                        label="Top"
                        value={externalPaddingTop}
                        min={0}
                        max={48}
                        unit="px"
                        onChange={(val) =>
                          setSettings({
                            ...settings,
                            external_padding_top: val,
                          })
                        }
                      />
                      <RangeSlider
                        label="Right"
                        value={externalPaddingRight}
                        min={0}
                        max={48}
                        unit="px"
                        onChange={(val) =>
                          setSettings({
                            ...settings,
                            external_padding_right: val,
                          })
                        }
                      />
                      <RangeSlider
                        label="Bottom"
                        value={externalPaddingBottom}
                        min={0}
                        max={48}
                        unit="px"
                        onChange={(val) =>
                          setSettings({
                            ...settings,
                            external_padding_bottom: val,
                          })
                        }
                      />
                      <RangeSlider
                        label="Left"
                        value={externalPaddingLeft}
                        min={0}
                        max={48}
                        unit="px"
                        onChange={(val) =>
                          setSettings({
                            ...settings,
                            external_padding_left: val,
                          })
                        }
                      />
                    </div>
                  </div>
                </HighlightableField>
              </>
            ) : null}
            {contentOverride}
          </div>
        )}

        {/* Labels & Options Tab */}
        {activeGeneralSubTab === "options" && (
          <div className="b3-wvs-space-y-4">
            {optionsOverrideMode !== "replace" ? (
              <>
                <HighlightableField id="general-show-labels-colors">
                  <Toggle
                    label="Show Labels on Color Swatches"
                    description="Display text labels alongside color swatches"
                    checked={settings.show_labels_colors !== false}
                    onChange={(checked) =>
                      setSettings({ ...settings, show_labels_colors: checked })
                    }
                  />
                </HighlightableField>

                <HighlightableField id="general-auto-convert-dropdowns">
                  <Toggle
                    label="Replace WooCommerce Dropdowns with Swatches"
                    description="Replaces the default WooCommerce variation dropdowns (selects) with the B3 swatches UI on product pages. Disable to keep the stock dropdowns."
                    checked={settings.auto_convert_dropdowns !== false}
                    onChange={(checked) =>
                      setSettings({
                        ...settings,
                        auto_convert_dropdowns: checked,
                      })
                    }
                  />
                </HighlightableField>
              </>
            ) : null}
            {contentOverride}
          </div>
        )}
      </div>
    </div>
  );
}
