// Properties for the currently selected clip — name, type, dimensions,
// start/duration/sourceIn numeric fields, jump-to-start/end, delete, and
// transition-in picker.

'use client';

import { Settings2, Trash2, Sparkles, AudioLines, Plus, X, Gauge, Palette, EyeOff } from 'lucide-react';
import { useEditor } from '@/store/editor';
import { formatTimeShort } from '@/lib/media';
import type { Clip, ColorPreset, ColorGrading, TransitionType, VolumeKeyframe, ChromaKey } from '@/types';
import { COLOR_PRESETS, DEFAULT_COLOR, DEFAULT_CHROMA_KEY } from '@/types';
import { Section, Row, NumberField, Slider } from './FormFields';

const TRANSITION_OPTIONS: { type: TransitionType; label: string; hint: string }[] = [
  { type: 'cut', label: 'ตัดข้าม', hint: 'ไม่มีเอฟเฟกต์' },
  { type: 'crossfade', label: 'เฟดสลับ', hint: 'ภาพ/เสียง ค่อยๆ เปลี่ยน' },
  { type: 'fadeIn', label: 'เฟดเข้า', hint: 'เริ่มจากดำ → ชัด' },
  { type: 'fadeOut', label: 'เฟดออก', hint: 'ชัด → ดำ' },
  { type: 'dipToBlack', label: 'ผ่านดำ', hint: 'ผ่านฉากดำ' },
];

export function ClipProperties({ clip, selectedAssetId }: { clip: Clip; selectedAssetId: string }) {
  const assets = useEditor((s) => s.assets);
  const updateClip = useEditor((s) => s.updateClip);
  const removeClip = useEditor((s) => s.removeClip);
  const setCurrentTime = useEditor((s) => s.setCurrentTime);
  const tracks = useEditor((s) => s.tracks);

  const asset = assets.find((a) => a.id === selectedAssetId);
  if (!asset) return null;

  return (
    <Section title="คุณสมบัติคลิป" icon={<Settings2 size={14} />}>
      <div className="space-y-2">
        <Row label="ชื่อสื่อ" value={asset.name} />
        <Row label="ประเภท" value={asset.kind === 'video' ? 'วิดีโอ' : 'เสียง'} />
        {asset.width && asset.height && (
          <Row label="ความละเอียด" value={`${asset.width}×${asset.height}`} />
        )}
        <Row label="ความยาวต้นฉบับ" value={formatTimeShort(asset.duration)} />
        <div className="grid grid-cols-2 gap-2 mt-2">
          <NumberField
            label="เริ่มบนไทม์ไลน์ (วินาที)"
            value={clip.start}
            step={0.1}
            onChange={(v) => updateClip(clip.id, { start: Math.max(0, v) })}
          />
          <NumberField
            label="ความยาว (วินาที)"
            value={clip.duration}
            step={0.1}
            onChange={(v) => updateClip(clip.id, { duration: Math.max(0.1, v) })}
          />
          <NumberField
            label="ต้นฉบับ in (วินาที)"
            value={clip.sourceIn}
            step={0.1}
            onChange={(v) => updateClip(clip.id, { sourceIn: Math.max(0, v) })}
          />
          <div className="flex items-end">
            <button
              type="button"
              onClick={() => removeClip(clip.id)}
              className="w-full h-9 rounded-md bg-capcut-red/20 hover:bg-capcut-red/30 text-capcut-red text-xs flex items-center justify-center gap-1"
            >
              <Trash2 size={12} /> ลบคลิป
            </button>
          </div>
        </div>

        <div className="pt-2 grid grid-cols-2 gap-2">
          <button
            type="button"
            onClick={() => setCurrentTime(clip.start)}
            className="h-8 rounded bg-capcut-surface hover:bg-capcut-border text-xs"
          >
            ไปที่จุดเริ่ม
          </button>
          <button
            type="button"
            onClick={() => setCurrentTime(clip.start + clip.duration)}
            className="h-8 rounded bg-capcut-surface hover:bg-capcut-border text-xs"
          >
            ไปที่จุดจบ
          </button>
        </div>

        {/* Speed ramp */}
        {asset.kind === 'video' && (
          <div className="pt-2 border-t border-capcut-border">
            <div className="flex items-center gap-1.5 text-[11px] text-capcut-muted mb-1.5">
              <Gauge size={12} /> ความเร็ว (Speed Ramp)
            </div>
            <div className="flex items-center gap-2">
              <input
                type="range"
                min={0.25}
                max={4}
                step={0.05}
                value={clip.speed ?? 1}
                onChange={(e) => updateClip(clip.id, { speed: Number(e.target.value) })}
                className="flex-1"
              />
              <span className="text-[11px] text-capcut-text font-mono w-14 text-right">
                {((clip.speed ?? 1) * 100).toFixed(0)}%
              </span>
              <button
                type="button"
                onClick={() => updateClip(clip.id, { speed: undefined })}
                className="text-[10px] text-capcut-muted hover:text-capcut-text"
              >
                reset
              </button>
            </div>
            <div className="grid grid-cols-4 gap-1 mt-2">
              {[
                { v: 0.25, label: '¼×' },
                { v: 0.5, label: '½×' },
                { v: 1, label: '1×' },
                { v: 2, label: '2×' },
              ].map((p) => (
                <button
                  key={p.v}
                  type="button"
                  onClick={() => updateClip(clip.id, { speed: p.v })}
                  className={`px-1 py-1 rounded text-[10px] border ${
                    (clip.speed ?? 1) === p.v
                      ? 'bg-capcut-blue/20 border-capcut-blue text-white'
                      : 'bg-capcut-surface border-capcut-border text-capcut-muted hover:text-capcut-text'
                  }`}
                >
                  {p.label}
                </button>
              ))}
            </div>
            <p className="text-[10px] text-capcut-muted mt-1">
              {(clip.speed ?? 1) < 1 ? '⏪ สโลว์โมชั่น' : (clip.speed ?? 1) > 1 ? '⏩ เร่งความเร็ว' : 'ความเร็วปกติ'}
            </p>
          </div>
        )}

        {/* Color grading (video clips) */}
        {asset.kind === 'video' && (
          <div className="pt-2 border-t border-capcut-border">
            <div className="flex items-center gap-1.5 text-[11px] text-capcut-muted mb-1.5">
              <Palette size={12} /> ฟิลเตอร์สี (Color Grading)
            </div>
            <div className="grid grid-cols-4 gap-1 mb-2">
              {(Object.keys(COLOR_PRESETS) as ColorPreset[]).map((preset) => {
                const p = COLOR_PRESETS[preset];
                const active = (clip.colorGrading?.preset ?? 'original') === preset;
                return (
                  <button
                    key={preset}
                    type="button"
                    onClick={() => updateClip(clip.id, { colorGrading: { ...p } })}
                    className={`px-1 py-1.5 rounded text-[10px] border ${
                      active
                        ? 'bg-capcut-blue/20 border-capcut-blue text-white'
                        : 'bg-capcut-surface border-capcut-border text-capcut-muted hover:text-capcut-text'
                    }`}
                    title={preset}
                  >
                    {preset === 'original' && 'ดั้งเดิม'}
                    {preset === 'warm' && 'อุ่น'}
                    {preset === 'cool' && 'เย็น'}
                    {preset === 'bw' && 'ขาว-ดำ'}
                    {preset === 'vintage' && 'วินเทจ'}
                    {preset === 'vivid' && 'สด'}
                    {preset === 'cinematic' && 'ภาพยนตร์'}
                    {preset === 'noir' && 'นัวร์'}
                  </button>
                );
              })}
            </div>
            <Slider
              label={`ความสว่าง ${((clip.colorGrading?.brightness ?? 0) * 100).toFixed(0)}%`}
              min={-1}
              max={1}
              step={0.05}
              value={clip.colorGrading?.brightness ?? 0}
              onChange={(v) => updateClip(clip.id, { colorGrading: { ...DEFAULT_COLOR, ...(clip.colorGrading ?? {}), brightness: v, preset: undefined } })}
            />
            <Slider
              label={`คอนทราสต์ ${((clip.colorGrading?.contrast ?? 0) * 100).toFixed(0)}%`}
              min={-1}
              max={1}
              step={0.05}
              value={clip.colorGrading?.contrast ?? 0}
              onChange={(v) => updateClip(clip.id, { colorGrading: { ...DEFAULT_COLOR, ...(clip.colorGrading ?? {}), contrast: v, preset: undefined } })}
            />
            <Slider
              label={`ความอิ่มตัวสี ${((clip.colorGrading?.saturation ?? 0) * 100).toFixed(0)}%`}
              min={-1}
              max={1}
              step={0.05}
              value={clip.colorGrading?.saturation ?? 0}
              onChange={(v) => updateClip(clip.id, { colorGrading: { ...DEFAULT_COLOR, ...(clip.colorGrading ?? {}), saturation: v, preset: undefined } })}
            />
            <button
              type="button"
              onClick={() => updateClip(clip.id, { colorGrading: undefined })}
              className="w-full mt-1 h-6 rounded text-[10px] text-capcut-muted hover:text-capcut-text border border-capcut-border"
            >
              รีเซ็ตฟิลเตอร์
            </button>
          </div>
        )}

        {/* Chroma Key (Green Screen) — only on overlay tracks (track 2+) */}
        {(() => {
          const t = tracks.find((tr) => tr.id === clip.trackId);
          if (!t || t.kind !== 'video' || t.videoPosition === 'full') return null;
          const ck: ChromaKey = clip.chromaKey ?? DEFAULT_CHROMA_KEY;
          const update = (patch: Partial<ChromaKey>) =>
            updateClip(clip.id, { chromaKey: { ...ck, ...patch } });
          return (
            <div className="pt-2 border-t border-capcut-border">
              <div className="flex items-center justify-between mb-1.5">
                <div className="flex items-center gap-1.5 text-[11px] text-capcut-muted">
                  <EyeOff size={12} /> ตัดฉากหลัง (Chroma Key)
                </div>
                <button
                  type="button"
                  onClick={() =>
                    updateClip(clip.id, {
                      chromaKey: ck.enabled
                        ? undefined
                        : { ...DEFAULT_CHROMA_KEY, enabled: true },
                    })
                  }
                  className={`relative w-9 h-4 rounded-full transition-colors ${
                    ck.enabled ? 'bg-capcut-green' : 'bg-capcut-border'
                  }`}
                  aria-label="chroma key toggle"
                >
                  <span
                    className={`absolute top-0.5 w-3 h-3 rounded-full bg-white transition-transform ${
                      ck.enabled ? 'translate-x-5' : 'translate-x-0.5'
                    }`}
                  />
                </button>
              </div>
              {ck.enabled && (
                <div className="space-y-1.5">
                  {/* Color picker + presets */}
                  <div>
                    <div className="text-[10px] text-capcut-muted mb-1">สีที่จะลบ</div>
                    <div className="flex items-center gap-1.5">
                      <input
                        type="color"
                        value={ck.color}
                        onChange={(e) => update({ color: e.target.value })}
                        className="w-9 h-7 rounded cursor-pointer bg-transparent border border-capcut-border"
                      />
                      <input
                        type="text"
                        value={ck.color}
                        onChange={(e) => {
                          const v = e.target.value;
                          if (/^#[0-9a-fA-F]{0,6}$/.test(v)) update({ color: v });
                        }}
                        className="flex-1 h-7 bg-capcut-surface border border-capcut-border rounded px-2 font-mono text-[10px] text-capcut-text"
                      />
                    </div>
                    <div className="flex gap-1 mt-1">
                      {[
                        { c: '#00ff00', n: 'เขียว' },
                        { c: '#0000ff', n: 'น้ำเงิน' },
                        { c: '#ff0000', n: 'แดง' },
                        { c: '#ffffff', n: 'ขาว' },
                      ].map((p) => (
                        <button
                          key={p.c}
                          type="button"
                          onClick={() => update({ color: p.c })}
                          title={p.n}
                          className={`flex-1 h-5 rounded border ${
                            ck.color.toLowerCase() === p.c
                              ? 'border-capcut-blue ring-1 ring-capcut-blue'
                              : 'border-capcut-border'
                          }`}
                          style={{ background: p.c }}
                        />
                      ))}
                    </div>
                  </div>
                  {/* Similarity */}
                  <Slider
                    label={`ความคล้ายสี ${ck.similarity.toFixed(2)}`}
                    min={0.01}
                    max={0.5}
                    step={0.01}
                    value={ck.similarity}
                    onChange={(v) => update({ similarity: v })}
                  />
                  {/* Blend */}
                  <Slider
                    label={`ความนุ่มของขอบ ${ck.blend.toFixed(2)}`}
                    min={0}
                    max={0.3}
                    step={0.01}
                    value={ck.blend}
                    onChange={(v) => update({ blend: v })}
                  />
                  <button
                    type="button"
                    onClick={() =>
                      updateClip(clip.id, { chromaKey: { ...DEFAULT_CHROMA_KEY, enabled: true } })
                    }
                    className="w-full h-6 rounded text-[10px] text-capcut-muted hover:text-capcut-text border border-capcut-border"
                  >
                    รีเซ็ตค่า Chroma Key
                  </button>
                </div>
              )}
            </div>
          );
        })()}

        {/* Volume keyframes (audio clips only) */}
        {(() => {
          const track = tracks.find((t) => t.id === clip.trackId);
          if (!track || track.kind !== 'audio') return null;
          const kf: VolumeKeyframe[] = clip.volumeKeyframes ?? [];
          return (
            <div className="pt-2 border-t border-capcut-border">
              <div className="flex items-center justify-between mb-1.5">
                <div className="flex items-center gap-1.5 text-[11px] text-capcut-muted">
                  <AudioLines size={12} /> Volume Keyframes
                </div>
                <button
                  type="button"
                  onClick={() => {
                    const kfs = [...kf, { time: clip.duration / 2, value: track.volume }];
                    kfs.sort((a, b) => a.time - b.time);
                    updateClip(clip.id, { volumeKeyframes: kfs });
                  }}
                  className="text-[10px] text-capcut-blue hover:underline flex items-center gap-1"
                >
                  <Plus size={10} /> เพิ่ม keyframe
                </button>
              </div>
              {/* Mini-curve visualisation */}
              {kf.length >= 2 && (
                <div className="relative h-12 bg-capcut-black rounded mb-2 overflow-hidden">
                  <svg className="absolute inset-0 w-full h-full" preserveAspectRatio="none" viewBox="0 0 100 50">
                    <polyline
                      points={kf
                        .map((p) => `${(p.time / clip.duration) * 100},${50 - (p.value / 2) * 50}`)
                        .join(' ')}
                      fill="none"
                      stroke="#4f9eff"
                      strokeWidth="2"
                      vectorEffect="non-scaling-stroke"
                    />
                  </svg>
                  <div className="absolute bottom-0 left-0 right-0 text-center text-[9px] text-capcut-muted/60">
                    {kf.length} keyframes · vol {Math.min(...kf.map((p) => p.value)).toFixed(2)} → {Math.max(...kf.map((p) => p.value)).toFixed(2)}
                  </div>
                </div>
              )}
              <div className="space-y-1 max-h-40 overflow-y-auto">
                {kf.map((p, idx) => (
                  <div key={idx} className="flex items-center gap-1.5 text-[10px]">
                    <input
                      type="number"
                      step={0.1}
                      min={0}
                      max={clip.duration}
                      value={p.time.toFixed(2)}
                      onChange={(e) => {
                        const t = Math.max(0, Math.min(clip.duration, Number(e.target.value)));
                        const next = [...kf];
                        next[idx] = { ...p, time: t };
                        next.sort((a, b) => a.time - b.time);
                        updateClip(clip.id, { volumeKeyframes: next });
                      }}
                      className="w-14 h-6 bg-capcut-surface border border-capcut-border rounded px-1 font-mono"
                    />
                    <span className="text-capcut-muted">s</span>
                    <input
                      type="number"
                      step={0.05}
                      min={0}
                      max={2}
                      value={p.value.toFixed(2)}
                      onChange={(e) => {
                        const v = Math.max(0, Math.min(2, Number(e.target.value)));
                        const next = [...kf];
                        next[idx] = { ...p, value: v };
                        updateClip(clip.id, { volumeKeyframes: next });
                      }}
                      className="w-14 h-6 bg-capcut-surface border border-capcut-border rounded px-1 font-mono"
                    />
                    <span className="text-capcut-muted">vol</span>
                    <button
                      type="button"
                      onClick={() => updateClip(clip.id, { volumeKeyframes: kf.filter((_, i) => i !== idx) })}
                      className="ml-auto w-5 h-5 rounded text-capcut-muted hover:text-capcut-red hover:bg-capcut-red/10 flex items-center justify-center"
                      data-tip="ลบ keyframe"
                    >
                      <X size={10} />
                    </button>
                  </div>
                ))}
                {kf.length === 0 && (
                  <p className="text-[10px] text-capcut-muted text-center py-1">
                    ไม่มี keyframe — ใช้ volume ของแทร็ก
                  </p>
                )}
              </div>
              {kf.length > 0 && (
                <button
                  type="button"
                  onClick={() => updateClip(clip.id, { volumeKeyframes: undefined })}
                  className="w-full mt-2 h-6 rounded text-[10px] text-capcut-muted hover:text-capcut-text border border-capcut-border"
                >
                  ล้าง keyframes (ใช้ volume ของแทร็ก)
                </button>
              )}
            </div>
          );
        })()}

        {/* Transition picker */}
        <div className="pt-2 border-t border-capcut-border">
          <div className="flex items-center gap-1.5 text-[11px] text-capcut-muted mb-1.5">
            <Sparkles size={12} /> เอฟเฟกต์เข้าคลิป (Transition)
          </div>
          <div className="grid grid-cols-3 gap-1">
            {TRANSITION_OPTIONS.map((opt) => {
              const isActive = (clip.transitionIn?.type ?? 'cut') === opt.type;
              return (
                <button
                  key={opt.type}
                  type="button"
                  onClick={() => {
                    if (opt.type === 'cut') {
                      updateClip(clip.id, { transitionIn: undefined });
                    } else {
                      updateClip(clip.id, {
                        transitionIn: {
                          type: opt.type,
                          durationMs: clip.transitionIn?.durationMs ?? 500,
                        },
                      });
                    }
                  }}
                  className={`px-1 py-1.5 rounded text-[10px] font-medium border transition-colors ${
                    isActive
                      ? 'bg-capcut-blue/20 border-capcut-blue text-white'
                      : 'bg-capcut-surface border-capcut-border text-capcut-muted hover:border-capcut-blue/40 hover:text-capcut-text'
                  }`}
                  title={opt.hint}
                >
                  {opt.label}
                </button>
              );
            })}
          </div>
          {clip.transitionIn && clip.transitionIn.type !== 'cut' && (
            <div className="mt-2">
              <NumberField
                label="ระยะเวลา (มิลลิวินาที)"
                value={clip.transitionIn.durationMs}
                step={50}
                min={50}
                max={3000}
                onChange={(v) =>
                  updateClip(clip.id, {
                    transitionIn: {
                      ...clip.transitionIn!,
                      durationMs: Math.max(50, Math.min(3000, Math.round(v))),
                    },
                  })
                }
              />
              <p className="text-[10px] text-capcut-muted mt-1">
                {clip.transitionIn.type === 'crossfade' && 'ภาพและเสียงจะค่อยๆ สลับจากคลิปก่อนหน้า'}
                {clip.transitionIn.type === 'fadeIn' && 'คลิปนี้จะเริ่มจากภาพ/เสียงดำ → ค่อยๆ ชัด'}
                {clip.transitionIn.type === 'fadeOut' && 'คลิปนี้จะจบที่ภาพ/เสียงดำ'}
                {clip.transitionIn.type === 'dipToBlack' && 'คลิปก่อนหน้า → ดำ → คลิปนี้'}
              </p>
            </div>
          )}
        </div>
      </div>
    </Section>
  );
}