'use client';

import React, { useEffect, useState } from 'react';
import type { DefaultCellComponentProps } from 'payload';
import { usePayloadAPI } from '@payloadcms/ui';
import { Pill } from '@payloadcms/ui';
import { ChevronIcon } from '@payloadcms/ui';

export const TableOrderCell: React.FC<DefaultCellComponentProps> = ({ rowData }) => {
  const [currentIndex, setCurrentIndex] = useState<number>(-1);

  const where = rowData?.parent ? { parent: { equals: rowData.parent } } : { parent: { exists: false } };

  const [{ data, isLoading, isError }, { setParams }] = usePayloadAPI(`/api/pages`, {
    initialParams: {
      where,
      sort: 'order',
      limit: 100
    }
  });

  useEffect(() => {
    if (data?.docs) {
      const idx = data.docs.findIndex((doc: any) => doc.id === rowData.id);
      setCurrentIndex(idx);
    }
  }, [data, rowData.id]);

  const swapOrder = async (direction: 'up' | 'down') => {
    const siblings = data?.docs || [];
    const neighborIndex = direction === 'up' ? currentIndex - 1 : currentIndex + 1;

    // if (neighborIndex < 0 || neighborIndex >= siblings.length) return

    const currentPage = siblings[currentIndex];
    const neighborPage = siblings[neighborIndex];


    await Promise.all([
      fetch(`/api/pages/${currentPage.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ order: neighborPage.order })
      }),
      fetch(`/api/pages/${neighborPage.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ order: currentPage.order })
      })
    ]);

    window.location.reload();
  };

  //if (isLoading) return <span>Loading...</span>;
  if (isError) return <span>Error loading data</span>;

  const canMoveUp = currentIndex > 0;
  const canMoveDown = currentIndex > -1 && currentIndex < (data?.docs?.length || 0) - 1;

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: '0.25rem' }}>
      <Pill pillStyle="white" onClick={() => swapOrder('up')}>
        <ChevronIcon direction ="up"></ChevronIcon>
      </Pill>

      <Pill pillStyle="white" onClick={() => swapOrder('down')}>
        <ChevronIcon direction ="down"></ChevronIcon>
      </Pill>
    </div>
  );
};
