/**
 * BordersModal Component
 *
 * Modal for editing border settings including width, style, color, and radius.
 * Supports both responsive (desktop/tablet/mobile) and non-responsive modes.
 */

import { useState } from "react";
import * as Dialog from "@radix-ui/react-dialog";
import { Cross2Icon, DesktopIcon, LaptopIcon, MobileIcon } from "@radix-ui/react-icons";

import { Select, Slider, ColorPicker } from "../ui";

import type { BorderSettings, ResponsiveBorderSettings, Breakpoint } from "@/types";
import { createResponsiveValue } from "@/types";

// Border styles
const BORDER_STYLE_OPTIONS = [
  { value: "solid", label: "Solid" },
  { value: "dashed", label: "Dashed" },
  { value: "dotted", label: "Dotted" },
];

// Breakpoint options
const BREAKPOINTS: { value: Breakpoint; icon: React.ReactNode; label: string }[] = [
  { value: "desktop", icon: <DesktopIcon />, label: "Desktop" },
  { value: "tablet", icon: <LaptopIcon />, label: "Tablet" },
  { value: "mobile", icon: <MobileIcon />, label: "Mobile" },
];

// Helper to convert responsive to non-responsive
const toNonResponsive = (responsive: ResponsiveBorderSettings): BorderSettings => ({
  width: responsive.width.desktop,
  style: responsive.style,
  color: responsive.color,
  radius: responsive.radius,
});

// Helper to convert non-responsive to responsive
const toResponsive = (nonResponsive: BorderSettings, original?: ResponsiveBorderSettings): ResponsiveBorderSettings => ({
  width: original ? { ...original.width, desktop: nonResponsive.width } : createResponsiveValue(nonResponsive.width),
  style: nonResponsive.style,
  color: nonResponsive.color,
  radius: nonResponsive.radius,
});

// Props supporting both responsive and non-responsive modes
interface BordersModalPropsBase {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

interface BordersModalPropsResponsive extends BordersModalPropsBase {
  border: ResponsiveBorderSettings;
  onUpdate: (border: ResponsiveBorderSettings) => void;
  isResponsive: true;
}

interface BordersModalPropsNonResponsive extends BordersModalPropsBase {
  border: BorderSettings;
  onUpdate: (border: BorderSettings) => void;
  isResponsive?: false;
}

type BordersModalProps = BordersModalPropsResponsive | BordersModalPropsNonResponsive;

export function BordersModal(props: BordersModalProps) {
  const { open, onOpenChange } = props;
  const [activeBreakpoint, setActiveBreakpoint] = useState<Breakpoint>("desktop");

  // Normalize to responsive format internally
  const isResponsive = props.isResponsive === true;
  const responsiveBorder: ResponsiveBorderSettings = isResponsive
    ? (props.border as ResponsiveBorderSettings)
    : toResponsive(props.border as BorderSettings);

  // Get value for current breakpoint
  const getWidth = (): number => responsiveBorder.width[activeBreakpoint];

  // Handle width change (responsive)
  const handleWidthChange = (value: number) => {
    const updatedBorder: ResponsiveBorderSettings = {
      ...responsiveBorder,
      width: {
        ...responsiveBorder.width,
        [activeBreakpoint]: value,
      },
    };

    if (isResponsive) {
      (props as BordersModalPropsResponsive).onUpdate(updatedBorder);
    } else {
      (props as BordersModalPropsNonResponsive).onUpdate(toNonResponsive(updatedBorder));
    }
  };

  // Handle non-responsive field change
  const handleFieldChange = <K extends keyof BorderSettings>(key: K, value: BorderSettings[K]) => {
    const updatedBorder: ResponsiveBorderSettings = {
      ...responsiveBorder,
      [key]: value,
    };

    if (isResponsive) {
      (props as BordersModalPropsResponsive).onUpdate(updatedBorder);
    } else {
      (props as BordersModalPropsNonResponsive).onUpdate(toNonResponsive(updatedBorder));
    }
  };

  return (
    <Dialog.Root open={open} onOpenChange={onOpenChange}>
      <Dialog.Portal>
        <Dialog.Overlay className="modal-overlay" />
        <Dialog.Content className="modal-content">
          <div className="modal-header">
            <Dialog.Title className="modal-title">Border Settings</Dialog.Title>
            <Dialog.Close asChild>
              <button className="modal-close" aria-label="Close">
                <Cross2Icon />
              </button>
            </Dialog.Close>
          </div>

          <div className="modal-body">
            {/* Responsive Breakpoint Toggle */}
            {isResponsive && (
              <div className="modal-field">
                <label className="modal-label">Breakpoint</label>
                <div className="modal-button-group">
                  {BREAKPOINTS.map((bp) => (
                    <button
                      key={bp.value}
                      type="button"
                      className={`modal-toggle-btn modal-toggle-btn--icon ${activeBreakpoint === bp.value ? "active" : ""}`}
                      onClick={() => setActiveBreakpoint(bp.value)}
                      title={bp.label}
                    >
                      {bp.icon}
                    </button>
                  ))}
                </div>
              </div>
            )}

            {/* Border Width - Responsive */}
            <div className="modal-field">
              <label className="modal-label">
                Border Width: {getWidth()}px
                {isResponsive && <span className="modal-label__breakpoint">({activeBreakpoint})</span>}
              </label>
              <Slider value={getWidth()} onValueChange={handleWidthChange} min={0} max={20} step={1} />
            </div>

            {/* Border Style */}
            <div className="modal-field">
              <label className="modal-label">Border Style</label>
              <Select
                value={responsiveBorder.style}
                onValueChange={(value) => handleFieldChange("style", value as BorderSettings["style"])}
                options={BORDER_STYLE_OPTIONS}
              />
            </div>

            {/* Border Color */}
            <div className="modal-field">
              <label className="modal-label">Border Color</label>
              <ColorPicker value={responsiveBorder.color} onChange={(value) => handleFieldChange("color", value)} />
            </div>

            {/* Border Radius */}
            <div className="modal-field">
              <label className="modal-label">Border Radius: {responsiveBorder.radius}px</label>
              <Slider
                value={responsiveBorder.radius}
                onValueChange={(value) => handleFieldChange("radius", value)}
                min={0}
                max={150}
                step={1}
              />
            </div>
          </div>

          <div className="modal-footer">
            <Dialog.Close asChild>
              <button className="oppb-button-secondary">Close</button>
            </Dialog.Close>
          </div>
        </Dialog.Content>
      </Dialog.Portal>
    </Dialog.Root>
  );
}

export default BordersModal;
