import {
  DndContext,
  closestCenter,
  PointerSensor,
  useSensor,
  useSensors,
} from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { restrictToVerticalAxis } from '@dnd-kit/modifiers';
import AudioTrimmer from './AudioTrimer';
import { ClipMetadata } from '../../redux/types';
import { useAppDispatch, useAppSelector } from '../hooks';

export interface ClipListProps {
  collection: string;
}

export default function ClipList({ collection }: ClipListProps) {
  const metadata = useAppSelector(
    (state) => state.collections[collection] || [],
  );
  const dispatch = useAppDispatch();

  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
  );

  async function handleDragEnd(event) {
    const { active, over } = event;
    if (active.id !== over?.id) {
      const oldIndex = metadata.findIndex(
        (item) => item.filename === active.id,
      );
      const newIndex = metadata.findIndex((item) => item.filename === over.id);
      const newMetadata = arrayMove(metadata, oldIndex, newIndex);
      console.log('New order:', newMetadata);
      dispatch({
        type: 'metadata/setCollections',
        payload: { collection, newMetadata },
      });
      try {
        const response = await fetch(
          'http://localhost:5010/meta/collection/clips/reorder',
          {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              name: collection,
              clips: newMetadata,
            }),
          },
        );
        const data = await response.json();
        console.log('handle reorder return:', data.collections);
        dispatch({ type: 'metadata/setAllData', payload: data });
      } catch (error) {
        console.error('Error saving new clip order:', error);
      }
      // setMetadata(newMetadata);
    }
  }

  async function handleClipSave(meta: ClipMetadata) {
    try {
      dispatch({
        type: 'metadata/editClip',
        payload: { collection, clip: meta },
      });
      const response = await fetch(
        'http://localhost:5010/meta/collection/clips/edit',
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            name: collection,
            clip: meta,
          }),
        },
      );
      const data = await response.json();
      // console.log('handle clip save return:', data.collections);
      dispatch({
        type: 'metadata/editClip',
        payload: { collection, clip: meta },
      });
    } catch (error) {
      console.error('Error saving clip metadata:', error);
    }
  }

  return (
    <div className="min-h-screen flex flex-col justify-center bg-midnight text-offwhite">
      <DndContext
        sensors={sensors}
        collisionDetection={closestCenter}
        onDragEnd={handleDragEnd}
        modifiers={[restrictToVerticalAxis]}
      >
        <SortableContext
          items={metadata.map((item) => item.filename)}
          strategy={verticalListSortingStrategy}
        >
          {metadata.map((trimmer) => (
            <AudioTrimmer
              key={trimmer.filename}
              filename={trimmer.filename}
              onSave={handleClipSave}
            />
          ))}
        </SortableContext>
      </DndContext>
    </div>
    // <div className="min-h-screen flex flex-col justify-center bg-midnight text-offwhite">
    //   <AudioTrimmer
    //     title="audio_capture_20251206_123108.wav"
    //     filePath="C:\\Users\\mickl\\Music\\clips\\original\\audio_capture_20250118_000351.wav"
    //     // section="Section 1"
    //   />
    //   <AudioTrimmer
    //     title="audio_capture_20251206_123108.wav"
    //     filePath="C:\\Users\\mickl\\Music\\clips\\original\\audio_capture_20250118_000351.wav"
    //     // section="Section 1"
    //   />
    //   <AudioTrimmer
    //     title="audio_capture_20251206_123108.wav"
    //     filePath="C:\\Users\\mickl\\Music\\clips\\original\\audio_capture_20250118_000351.wav"
    //     // section="Section 1"
    //   />
    // </div>
  );
}
