'use client';

import { useState } from 'react';
import { SpoonStatusBadge } from '@/components/spoons/spoon-status-badge';
import { useAction } from 'convex/react';
import { makeFunctionReference } from 'convex/server';
import { RefreshCw, RotateCw } from 'lucide-react';
import { toast } from 'sonner';

import type { Doc, Id } from '@spoon/backend/convex/_generated/dataModel.js';
import { Button } from '@spoon/ui';

const refreshRef = makeFunctionReference<
  'action',
  { spoonId: Id<'spoons'> },
  {
    success: boolean;
    status: string;
    upstreamAheadBy: number;
    forkAheadBy: number;
  }
>('githubSync:refreshSpoonGithubState');

const syncRef = makeFunctionReference<
  'action',
  { spoonId: Id<'spoons'> },
  unknown
>('githubSync:syncForkWithUpstream');

export const SpoonDetailHeader = ({
  spoon,
  state,
}: {
  spoon: Doc<'spoons'>;
  state?: Doc<'spoonRepositoryStates'> | null;
}) => {
  const refresh = useAction(refreshRef);
  const sync = useAction(syncRef);
  const [busy, setBusy] = useState<string | null>(null);
  const canSync =
    spoon.provider === 'github' &&
    state?.status === 'behind' &&
    state.forkAheadBy === 0;

  const run = async (label: string, action: () => Promise<unknown>) => {
    setBusy(label);
    try {
      await action();
      toast.success(`${label} complete.`);
    } catch (error) {
      console.error(error);
      toast.error(`${label} failed.`);
    } finally {
      setBusy(null);
    }
  };

  return (
    <div className='border-border bg-card flex flex-col justify-between gap-5 rounded-lg border p-5 shadow-sm lg:flex-row lg:items-start'>
      <div className='min-w-0 space-y-2'>
        <div className='flex flex-wrap items-center gap-3'>
          <h1 className='truncate text-3xl font-semibold tracking-normal'>
            {spoon.name}
          </h1>
          <SpoonStatusBadge
            status={state?.status ?? spoon.syncStatus ?? spoon.status}
          />
        </div>
        <div className='text-muted-foreground flex flex-wrap gap-x-4 gap-y-1 text-sm'>
          <a
            href={spoon.upstreamUrl}
            target='_blank'
            rel='noreferrer'
            className='hover:text-foreground'
          >
            Upstream: {spoon.upstreamOwner}/{spoon.upstreamRepo}
          </a>
          {spoon.forkUrl ? (
            <a
              href={spoon.forkUrl}
              target='_blank'
              rel='noreferrer'
              className='hover:text-foreground'
            >
              Fork: {spoon.forkOwner}/{spoon.forkRepo}
            </a>
          ) : (
            <span>Fork metadata missing</span>
          )}
        </div>
        {spoon.description ? (
          <p className='text-muted-foreground max-w-3xl text-sm leading-6'>
            {spoon.description}
          </p>
        ) : null}
      </div>
      <div className='flex shrink-0 flex-wrap gap-2'>
        <Button
          variant='outline'
          onClick={() => run('Refresh', () => refresh({ spoonId: spoon._id }))}
          disabled={Boolean(busy)}
        >
          <RefreshCw className='size-4' />
          Refresh
        </Button>
        <Button
          onClick={() => run('Sync', () => sync({ spoonId: spoon._id }))}
          disabled={Boolean(busy) || !canSync}
        >
          <RotateCw className='size-4' />
          Sync fork
        </Button>
      </div>
    </div>
  );
};
