'use client';

// PropertiesPanel — composes the sub-panels keyed off the current selection.
// Each property component manages its own Panel/Section wrapper.

import { MousePointer, Trash2, Copy, X, Square } from 'lucide-react';
import { useEditor } from '@/store/editor';
import { ClipProperties } from './properties/ClipProperties';
import { TrackProperties } from './properties/TrackProperties';
import { SubtitleProperties } from './properties/SubtitleProperties';
import { ExportProperties } from './properties/ExportProperties';
import { AutoEditProperties } from './properties/AutoEditProperties';
import { TextOverlayProperties } from './properties/TextOverlayProperties';

export function PropertiesPanel() {
  const selection = useEditor((s) => s.selection);
  const clips = useEditor((s) => s.clips);
  const tracks = useEditor((s) => s.tracks);
  const textOverlays = useEditor((s) => s.textOverlays);
  const removeClips = useEditor((s) => s.removeClips);
  const duplicateClips = useEditor((s) => s.duplicateClips);
  const setSelection = useEditor((s) => s.setSelection);
  const setClipIds = useEditor((s) => s.setClipIds);
  const setToast = useEditor((s) => s.setToast);

  const selectedClip = clips.find((c) => c.id === selection.clipId);
  const selectedTrack = tracks.find((t) => t.id === selection.trackId);
  const selectedTextOverlay = textOverlays.find((t) => t.id === selection.textOverlayId);
  // V23 — Multi-select: derive selected IDs (clipIds array or fallback to clipId)
  const selectedIds = selection.clipIds?.length
    ? selection.clipIds
    : selection.clipId
      ? [selection.clipId]
      : [];
  const isMultiSelect = selectedIds.length > 1;

  return (
    <div className="p-3 space-y-3 text-sm overflow-y-auto h-full scroll-thin">
      {/* V23 — Multi-select bulk action panel */}
      {isMultiSelect && (
        <div className="bg-gradient-to-br from-capcut-blue/15 to-capcut-purple/10 border border-capcut-blue/40 rounded-xl p-3 animate-fade-in">
          <div className="flex items-center gap-2 mb-2">
            <div className="w-7 h-7 rounded-lg bg-capcut-blue/20 flex items-center justify-center">
              <Square size={14} className="text-capcut-blue" />
            </div>
            <div className="flex-1">
              <div className="text-xs font-semibold text-white">
                เลือก {selectedIds.length} คลิป
              </div>
              <div className="text-[10px] text-capcut-muted">
                Multi-select · Shift+click เพิ่ม · Cmd+A ทั้งหมด
              </div>
            </div>
            <button
              type="button"
              onClick={() => setSelection({})}
              className="w-6 h-6 rounded flex items-center justify-center text-capcut-muted hover:text-white hover:bg-white/10"
              data-tip="ยกเลิกการเลือก"
            >
              <X size={12} />
            </button>
          </div>
          <div className="grid grid-cols-3 gap-1.5 mt-2">
            <button
              type="button"
              onClick={() => {
                duplicateClips(selectedIds);
              }}
              className="h-8 rounded-md bg-capcut-surface hover:bg-capcut-border border border-capcut-border text-[11px] text-capcut-text flex items-center justify-center gap-1"
              data-tip="Cmd/Ctrl+D · คัดลอกคลิป"
            >
              <Copy size={11} /> คัดลอก
            </button>
            <button
              type="button"
              onClick={() => {
                removeClips(selectedIds);
                setToast({ message: `ลบ ${selectedIds.length} คลิป`, level: 'success' });
              }}
              className="h-8 rounded-md bg-capcut-red/15 hover:bg-capcut-red/25 border border-capcut-red/40 text-[11px] text-capcut-red flex items-center justify-center gap-1"
              data-tip="Delete · ลบคลิป"
            >
              <Trash2 size={11} /> ลบ
            </button>
            <button
              type="button"
              onClick={() => {
                // V23 — Group: assign a groupId to all selected clips
                const groupId = `g-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
                const idSet = new Set(selectedIds);
                useEditor.setState((s) => ({
                  clips: s.clips.map((c) => (idSet.has(c.id) ? { ...c, groupId } : c)),
                }));
                setToast({ message: `จัดกลุ่ม ${selectedIds.length} คลิป`, level: 'success' });
              }}
              className="h-8 rounded-md bg-capcut-surface hover:bg-capcut-border border border-capcut-border text-[11px] text-capcut-text flex items-center justify-center gap-1"
              data-tip="Cmd+G · จัดกลุ่ม"
            >
              <Square size={11} /> กลุ่ม
            </button>
          </div>
          <div className="mt-2 text-[10px] text-capcut-muted leading-relaxed">
            💡 กด <kbd className="px-1 rounded bg-white/10 font-mono">Shift</kbd>+click
            เพื่อเพิ่มคลิป · <kbd className="px-1 rounded bg-white/10 font-mono">Cmd+A</kbd> เลือกทั้งหมด ·{' '}
            <kbd className="px-1 rounded bg-white/10 font-mono">Esc</kbd> ยกเลิก
          </div>
        </div>
      )}

      {!selectedClip && !selectedTrack && !selectedTextOverlay && !isMultiSelect && <EmptyState />}

      {selectedTextOverlay && <TextOverlayProperties overlay={selectedTextOverlay} />}
      {selectedClip && !isMultiSelect && (
        <ClipProperties clip={selectedClip} selectedAssetId={selectedClip.assetId} />
      )}
      {selectedTrack && <TrackProperties track={selectedTrack} />}

      <SubtitleProperties />
      <ExportProperties />
      <AutoEditProperties />
    </div>
  );
}

function EmptyState() {
  return (
    <div className="bg-gradient-to-br from-capcut-panel/60 to-capcut-dark/60 border border-capcut-border/40 rounded-xl p-6 text-center animate-fade-in">
      <div className="mx-auto mb-3 w-12 h-12 rounded-full bg-capcut-surface flex items-center justify-center">
        <MousePointer size={20} className="text-capcut-muted" />
      </div>
      <p className="text-sm font-medium text-capcut-text">เลือกคลิปหรือแทร็ก</p>
      <p className="text-[11px] text-capcut-muted mt-1 leading-relaxed">
        คลิกบนคลิปในไทม์ไลน์เพื่อดูและแก้ไขคุณสมบัติ
      </p>
    </div>
  );
}
