import { ChevronDown, Eye, Check } from "lucide-react";
import { FloatingStylePreview } from "@/features/home/ui/FloatingStylePreview";
import { SelectPopover } from "@/shared/ui/SelectPopover";

interface SubtitleStyleOption {
  id: string;
  label: string;
  font_family?: string;
  font_file?: string;
  font_size?: number;
  highlight_color?: string;
  normal_color?: string;
  stroke_color?: string;
  stroke_size?: number;
  letter_spacing?: number;
  bottom_margin?: number;
  is_default?: boolean;
}

interface TitleStyleOption {
  id: string;
  label: string;
  font_family?: string;
  font_file?: string;
  font_size?: number;
  color?: string;
  stroke_color?: string;
  stroke_size?: number;
  letter_spacing?: number;
  font_weight?: number;
  top_margin?: number;
  is_default?: boolean;
}

interface TitleSubtitlePanelProps {
  showStylePreview: boolean;
  onTogglePreview: () => void;
  videoTitle: string;
  onTitleChange: (value: string) => void;
  onTitleCompositionStart?: () => void;
  onTitleCompositionEnd?: (value: string) => void;
  videoSecondaryTitle: string;
  onSecondaryTitleChange: (value: string) => void;
  onSecondaryTitleCompositionStart?: () => void;
  onSecondaryTitleCompositionEnd?: (value: string) => void;
  titleStyles: TitleStyleOption[];
  selectedTitleStyleId: string;
  onSelectTitleStyle: (id: string) => void;
  titleFontSize: number;
  onTitleFontSizeChange: (value: number) => void;
  selectedSecondaryTitleStyleId: string;
  onSelectSecondaryTitleStyle: (id: string) => void;
  secondaryTitleFontSize: number;
  onSecondaryTitleFontSizeChange: (value: number) => void;
  secondaryTitleTopMargin: number;
  onSecondaryTitleTopMarginChange: (value: number) => void;
  subtitleStyles: SubtitleStyleOption[];
  selectedSubtitleStyleId: string;
  onSelectSubtitleStyle: (id: string) => void;
  subtitleFontSize: number;
  onSubtitleFontSizeChange: (value: number) => void;
  titleTopMargin: number;
  onTitleTopMarginChange: (value: number) => void;
  subtitleBottomMargin: number;
  onSubtitleBottomMarginChange: (value: number) => void;
  titleDisplayMode: "short" | "persistent";
  onTitleDisplayModeChange: (mode: "short" | "persistent") => void;
  resolveAssetUrl: (path?: string | null) => string | null;
  getFontFormat: (fontFile?: string) => string;
  buildTextShadow: (color: string, size: number) => string;
  previewBaseWidth?: number;
  previewBaseHeight?: number;
  previewBackgroundUrl?: string | null;
}

export function TitleSubtitlePanel({
  showStylePreview,
  onTogglePreview,
  videoTitle,
  onTitleChange,
  onTitleCompositionStart,
  onTitleCompositionEnd,
  videoSecondaryTitle,
  onSecondaryTitleChange,
  onSecondaryTitleCompositionStart,
  onSecondaryTitleCompositionEnd,
  titleStyles,
  selectedTitleStyleId,
  onSelectTitleStyle,
  titleFontSize,
  onTitleFontSizeChange,
  selectedSecondaryTitleStyleId,
  onSelectSecondaryTitleStyle,
  secondaryTitleFontSize,
  onSecondaryTitleFontSizeChange,
  secondaryTitleTopMargin,
  onSecondaryTitleTopMarginChange,
  subtitleStyles,
  selectedSubtitleStyleId,
  onSelectSubtitleStyle,
  subtitleFontSize,
  onSubtitleFontSizeChange,
  titleTopMargin,
  onTitleTopMarginChange,
  subtitleBottomMargin,
  onSubtitleBottomMarginChange,
  titleDisplayMode,
  onTitleDisplayModeChange,
  resolveAssetUrl,
  getFontFormat,
  buildTextShadow,
  previewBaseWidth = 1080,
  previewBaseHeight = 1920,
  previewBackgroundUrl,
}: TitleSubtitlePanelProps) {
  const titleDisplayOptions: Array<{ value: "short" | "persistent"; label: string }> = [
    { value: "short", label: "标题短暂显示" },
    { value: "persistent", label: "标题常驻显示" },
  ];
  const currentTitleDisplay = titleDisplayOptions.find((opt) => opt.value === titleDisplayMode) || titleDisplayOptions[0];

  const currentTitleStyle = titleStyles.find((style) => style.id === selectedTitleStyleId) || titleStyles[0] || null;
  const currentSecondaryTitleStyle = titleStyles.find((style) => style.id === selectedSecondaryTitleStyleId) || titleStyles[0] || null;
  const currentSubtitleStyle = subtitleStyles.find((style) => style.id === selectedSubtitleStyleId) || subtitleStyles[0] || null;

  return (
    <div className="bg-white/5 rounded-2xl p-4 sm:p-6 border border-white/10 backdrop-blur-sm">
      <div className="flex items-center justify-between mb-4 gap-2">
        <h2 className="text-base sm:text-lg font-semibold text-white flex items-center gap-2">
          四、标题与字幕
        </h2>
        <div className="flex items-center gap-1.5">
          <div className="shrink-0">
            <SelectPopover
              sheetTitle="标题显示方式"
              trigger={({ open, toggle }) => (
                <button
                  type="button"
                  onClick={toggle}
                  className="min-w-[146px] rounded-lg border border-white/10 bg-black/25 px-2.5 py-1.5 text-left text-xs text-gray-200 transition-colors hover:border-white/30"
                  aria-label="标题显示方式"
                >
                  <span className="flex items-center justify-between gap-2">
                    <span className="whitespace-nowrap">{currentTitleDisplay.label}</span>
                    <ChevronDown className={`h-3.5 w-3.5 text-gray-400 transition-transform ${open ? "rotate-180" : ""}`} />
                  </span>
                </button>
              )}
            >
              {({ close }) => (
                <div className="space-y-1">
                  {titleDisplayOptions.map((opt) => {
                    const isSelected = opt.value === titleDisplayMode;
                    return (
                      <button
                        key={opt.value}
                        type="button"
                        data-popover-selected={isSelected ? "true" : undefined}
                        onClick={() => {
                          onTitleDisplayModeChange(opt.value);
                          close();
                        }}
                        className={`flex w-full items-center justify-between rounded-lg border px-3 py-2 text-left transition-colors ${isSelected
                          ? "border-purple-500 bg-purple-500/20"
                          : "border-white/10 bg-white/5 hover:border-white/30"
                          }`}
                      >
                        <span className="text-xs text-white whitespace-nowrap">{opt.label}</span>
                        {isSelected && <Check className="h-3.5 w-3.5 text-purple-300" />}
                      </button>
                    );
                  })}
                </div>
              )}
            </SelectPopover>
          </div>
          <button
            onClick={onTogglePreview}
            className="px-2 py-1 text-xs bg-white/10 hover:bg-white/20 rounded text-gray-300 flex items-center gap-1"
          >
            <Eye className="h-3.5 w-3.5" />
            {showStylePreview ? "收起预览" : "预览样式"}
          </button>
        </div>
      </div>

      {showStylePreview && (
        <FloatingStylePreview
          onClose={onTogglePreview}
          videoTitle={videoTitle}
          videoSecondaryTitle={videoSecondaryTitle}
          titleStyles={titleStyles}
          selectedTitleStyleId={selectedTitleStyleId}
          titleFontSize={titleFontSize}
          selectedSecondaryTitleStyleId={selectedSecondaryTitleStyleId}
          secondaryTitleFontSize={secondaryTitleFontSize}
          secondaryTitleTopMargin={secondaryTitleTopMargin}
          subtitleStyles={subtitleStyles}
          selectedSubtitleStyleId={selectedSubtitleStyleId}
          subtitleFontSize={subtitleFontSize}
          titleTopMargin={titleTopMargin}
          subtitleBottomMargin={subtitleBottomMargin}
          enableSubtitles={true}
          resolveAssetUrl={resolveAssetUrl}
          getFontFormat={getFontFormat}
          buildTextShadow={buildTextShadow}
          previewBaseWidth={previewBaseWidth}
          previewBaseHeight={previewBaseHeight}
          previewBackgroundUrl={previewBackgroundUrl}
        />
      )}

      <div className="mb-4">
        <div className="flex items-center justify-between mb-2">
          <label className="text-sm text-gray-300">片头标题</label>
          <span className={`text-xs ${videoTitle.length > 15 ? "text-red-400" : "text-gray-500"}`}>{videoTitle.length}/15</span>
        </div>
        <input
          type="text"
          value={videoTitle}
          onChange={(e) => onTitleChange(e.target.value)}
          onCompositionStart={onTitleCompositionStart}
          onCompositionEnd={(e) => onTitleCompositionEnd?.(e.currentTarget.value)}
          placeholder="输入视频标题，将在片头显示"
          className="w-full px-3 sm:px-4 py-2 text-sm sm:text-base bg-black/30 border border-white/10 rounded-xl text-white placeholder-gray-500 focus:outline-none focus:border-purple-500 transition-colors"
        />
      </div>

      <div className="mb-4">
        <div className="flex items-center justify-between mb-2">
          <label className="text-sm text-gray-300">片头副标题</label>
          <span className={`text-xs ${videoSecondaryTitle.length > 20 ? "text-red-400" : "text-gray-500"}`}>{videoSecondaryTitle.length}/20</span>
        </div>
        <input
          type="text"
          value={videoSecondaryTitle}
          onChange={(e) => onSecondaryTitleChange(e.target.value)}
          onCompositionStart={onSecondaryTitleCompositionStart}
          onCompositionEnd={(e) => onSecondaryTitleCompositionEnd?.(e.currentTarget.value)}
          placeholder="输入副标题，显示在主标题下方"
          className="w-full px-3 sm:px-4 py-2 text-sm sm:text-base bg-black/30 border border-white/10 rounded-xl text-white placeholder-gray-500 focus:outline-none focus:border-purple-500 transition-colors"
        />
      </div>

      {titleStyles.length > 0 && (
        <div className="mb-4 space-y-3">
          <div className="flex items-center gap-3">
            <label className="text-sm text-gray-300 shrink-0 w-20">标题样式</label>
            <div className="w-1/3 min-w-[130px]">
              <SelectPopover
                sheetTitle="标题样式"
                trigger={({ open, toggle }) => (
                  <button
                    type="button"
                    onClick={toggle}
                    className="w-full rounded-lg border border-white/15 bg-black/35 px-3 py-2 text-left text-sm text-gray-200 transition-colors hover:border-white/25"
                  >
                    <span className="flex items-center justify-between gap-2">
                      <span className="truncate">{currentTitleStyle?.label || "请选择"}</span>
                      <ChevronDown className={`h-3.5 w-3.5 text-gray-400 transition-transform ${open ? "rotate-180" : ""}`} />
                    </span>
                  </button>
                )}
              >
                {({ close }) => (
                  <div className="space-y-1">
                    {titleStyles.map((style) => {
                      const isSelected = selectedTitleStyleId === style.id;
                      return (
                        <button
                          key={style.id}
                          type="button"
                          data-popover-selected={isSelected ? "true" : undefined}
                          onClick={() => {
                            onSelectTitleStyle(style.id);
                            close();
                          }}
                          className={`flex w-full items-center justify-between rounded-lg border px-3 py-2 text-left transition-colors ${isSelected
                            ? "border-purple-500 bg-purple-500/20"
                            : "border-white/10 bg-white/5 hover:border-white/30"
                            }`}
                        >
                          <span className="text-sm text-white">{style.label}</span>
                          {isSelected && <Check className="h-4 w-4 text-purple-300" />}
                        </button>
                      );
                    })}
                  </div>
                )}
              </SelectPopover>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <label className="text-xs text-gray-400 shrink-0 w-20">字号 {titleFontSize}</label>
            <input type="range" min="60" max="150" step="1" value={titleFontSize} onChange={(e) => onTitleFontSizeChange(parseInt(e.target.value, 10))} className="flex-1 accent-purple-500" />
          </div>
          <div className="flex items-center gap-3">
            <label className="text-xs text-gray-400 shrink-0 w-20">位置 {titleTopMargin}</label>
            <input type="range" min="0" max="300" step="1" value={titleTopMargin} onChange={(e) => onTitleTopMarginChange(parseInt(e.target.value, 10))} className="flex-1 accent-purple-500" />
          </div>
        </div>
      )}

      {titleStyles.length > 0 && (
        <div className="mb-4 space-y-3">
          <div className="flex items-center gap-3">
            <label className="text-sm text-gray-300 shrink-0 w-20">副标题样式</label>
            <div className="w-1/3 min-w-[130px]">
              <SelectPopover
                sheetTitle="副标题样式"
                trigger={({ open, toggle }) => (
                  <button
                    type="button"
                    onClick={toggle}
                    className="w-full rounded-lg border border-white/15 bg-black/35 px-3 py-2 text-left text-sm text-gray-200 transition-colors hover:border-white/25"
                  >
                    <span className="flex items-center justify-between gap-2">
                      <span className="truncate">{currentSecondaryTitleStyle?.label || "请选择"}</span>
                      <ChevronDown className={`h-3.5 w-3.5 text-gray-400 transition-transform ${open ? "rotate-180" : ""}`} />
                    </span>
                  </button>
                )}
              >
                {({ close }) => (
                  <div className="space-y-1">
                    {titleStyles.map((style) => {
                      const isSelected = selectedSecondaryTitleStyleId === style.id;
                      return (
                        <button
                          key={style.id}
                          type="button"
                          data-popover-selected={isSelected ? "true" : undefined}
                          onClick={() => {
                            onSelectSecondaryTitleStyle(style.id);
                            close();
                          }}
                          className={`flex w-full items-center justify-between rounded-lg border px-3 py-2 text-left transition-colors ${isSelected
                            ? "border-purple-500 bg-purple-500/20"
                            : "border-white/10 bg-white/5 hover:border-white/30"
                            }`}
                        >
                          <span className="text-sm text-white">{style.label}</span>
                          {isSelected && <Check className="h-4 w-4 text-purple-300" />}
                        </button>
                      );
                    })}
                  </div>
                )}
              </SelectPopover>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <label className="text-xs text-gray-400 shrink-0 w-20">字号 {secondaryTitleFontSize}</label>
            <input type="range" min="30" max="100" step="1" value={secondaryTitleFontSize} onChange={(e) => onSecondaryTitleFontSizeChange(parseInt(e.target.value, 10))} className="flex-1 accent-purple-500" />
          </div>
          <div className="flex items-center gap-3">
            <label className="text-xs text-gray-400 shrink-0 w-20">间距 {secondaryTitleTopMargin}</label>
            <input type="range" min="0" max="100" step="1" value={secondaryTitleTopMargin} onChange={(e) => onSecondaryTitleTopMarginChange(parseInt(e.target.value, 10))} className="flex-1 accent-purple-500" />
          </div>
        </div>
      )}

      {subtitleStyles.length > 0 && (
        <div className="mt-4 space-y-3">
          <div className="flex items-center gap-3">
            <label className="text-sm text-gray-300 shrink-0 w-20">字幕样式</label>
            <div className="w-1/3 min-w-[130px]">
              <SelectPopover
                sheetTitle="字幕样式"
                trigger={({ open, toggle }) => (
                  <button
                    type="button"
                    onClick={toggle}
                    className="w-full rounded-lg border border-white/15 bg-black/35 px-3 py-2 text-left text-sm text-gray-200 transition-colors hover:border-white/25"
                  >
                    <span className="flex items-center justify-between gap-2">
                      <span className="truncate">{currentSubtitleStyle?.label || "请选择"}</span>
                      <ChevronDown className={`h-3.5 w-3.5 text-gray-400 transition-transform ${open ? "rotate-180" : ""}`} />
                    </span>
                  </button>
                )}
              >
                {({ close }) => (
                  <div className="space-y-1">
                    {subtitleStyles.map((style) => {
                      const isSelected = selectedSubtitleStyleId === style.id;
                      return (
                        <button
                          key={style.id}
                          type="button"
                          data-popover-selected={isSelected ? "true" : undefined}
                          onClick={() => {
                            onSelectSubtitleStyle(style.id);
                            close();
                          }}
                          className={`flex w-full items-center justify-between rounded-lg border px-3 py-2 text-left transition-colors ${isSelected
                            ? "border-purple-500 bg-purple-500/20"
                            : "border-white/10 bg-white/5 hover:border-white/30"
                            }`}
                        >
                          <span className="text-sm text-white">{style.label}</span>
                          {isSelected && <Check className="h-4 w-4 text-purple-300" />}
                        </button>
                      );
                    })}
                  </div>
                )}
              </SelectPopover>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <label className="text-xs text-gray-400 shrink-0 w-20">字号 {subtitleFontSize}</label>
            <input type="range" min="40" max="90" step="1" value={subtitleFontSize} onChange={(e) => onSubtitleFontSizeChange(parseInt(e.target.value, 10))} className="flex-1 accent-purple-500" />
          </div>
          <div className="flex items-center gap-3">
            <label className="text-xs text-gray-400 shrink-0 w-20">位置 {subtitleBottomMargin}</label>
            <input type="range" min="0" max="300" step="1" value={subtitleBottomMargin} onChange={(e) => onSubtitleBottomMarginChange(parseInt(e.target.value, 10))} className="flex-1 accent-purple-500" />
          </div>
        </div>
      )}
    </div>
  );
}
