import * as React from "react";
import { cn } from "@/lib/utils";
import { ThemeProvider } from "@/lib/theme-provider";
import { Card, CardContent } from "@/components/ui/card";
import {
  BrandColorField,
  type BrandColorMode,
} from "@/components/ui/brand-color-field";
import { ChatWidgetWindow } from "@/components/ui/chat-widget";

/**
 * ChatWidgetAppearancePanel — WealthX DS (Organism)
 *
 * Brand-color settings for the embeddable website chat widget, beside a live
 * preview of the widget itself.
 *
 * The preview mirrors production rather than faking it: it is wrapped in a
 * nested ThemeProvider carrying the tenant color, and `brandColor` is passed
 * only in `"custom"` mode. So `"theme"` mode previews the same way it ships —
 * as the *absence* of an override, inheriting the tenant color.
 *
 * Pure display component. Persistence is owned by the app layer.
 */

export interface ChatWidgetAppearancePanelProps {
  mode: BrandColorMode;
  onModeChange: (mode: BrandColorMode) => void;
  /** Tenant brand color from company settings. */
  themeColor: string;
  customColor: string;
  onCustomColorChange: (color: string) => void;
  /** Broker name shown in the preview widget header. */
  brokerName?: string;
  title?: string;
  disabled?: boolean;
  className?: string;
}

export function ChatWidgetAppearancePanel({
  mode,
  onModeChange,
  themeColor,
  customColor,
  onCustomColorChange,
  brokerName = "Your Broker",
  title = "Widget Appearance",
  disabled,
  className,
}: ChatWidgetAppearancePanelProps) {
  return (
    <div
      className={cn(
        "grid items-start gap-6 lg:grid-cols-[minmax(0,1fr)_auto]",
        className,
      )}
      data-slot="chat-widget-appearance-panel"
    >
      <Card className="gap-0 py-0">
        <div className="border-b px-4 py-2.5">
          <p className="text-label-medium text-card-foreground">{title}</p>
        </div>
        <CardContent className="px-4 py-6">
          <BrandColorField
            mode={mode}
            onModeChange={onModeChange}
            themeColor={themeColor}
            customColor={customColor}
            onCustomColorChange={onCustomColorChange}
            disabled={disabled}
          />
        </CardContent>
      </Card>

      <div className="flex flex-col gap-2 lg:sticky lg:top-6">
        <p className="text-caption text-muted-foreground">Live preview</p>
        <ThemeProvider primary={themeColor}>
          <ChatWidgetWindow
            isOpen
            brokerName={brokerName}
            brandColor={mode === "custom" ? customColor : undefined}
            initialScreen="topics"
          />
        </ThemeProvider>
      </div>
    </div>
  );
}
