'use client';

import * as React from 'react';
import { IconCopy, IconEye } from '@tabler/icons-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
  SheetTrigger
} from '@/components/ui/sheet';

type TemplateJsonSheetProps = {
  version: string;
  filePath?: string | null;
  schemaJson: unknown;
  triggerLabel?: string;
};

function formatSchemaJson(schemaJson: unknown) {
  try {
    return JSON.stringify(schemaJson ?? {}, null, 2);
  } catch {
    return '{}';
  }
}

function getSchemaPageCount(schemaJson: unknown) {
  if (
    schemaJson &&
    typeof schemaJson === 'object' &&
    'schemas' in schemaJson &&
    Array.isArray((schemaJson as { schemas?: unknown }).schemas)
  ) {
    return (schemaJson as { schemas: unknown[] }).schemas.length;
  }

  return 0;
}

export function TemplateJsonSheet({
  version,
  filePath,
  schemaJson,
  triggerLabel = 'View JSON'
}: TemplateJsonSheetProps) {
  const formattedJson = React.useMemo(() => formatSchemaJson(schemaJson), [schemaJson]);
  const pageCount = React.useMemo(() => getSchemaPageCount(schemaJson), [schemaJson]);
  const hasSchemaJson = formattedJson !== '{}';

  async function handleCopy() {
    try {
      await navigator.clipboard.writeText(formattedJson);
      toast.success('Copied JSON');
    } catch {
      toast.error('Unable to copy JSON');
    }
  }

  return (
    <Sheet>
      <SheetTrigger asChild>
        <Button variant='outline' size='sm'>
          <IconEye className='size-4' />
          {triggerLabel}
        </Button>
      </SheetTrigger>

      <SheetContent side='right' className='w-full max-w-[90vw] sm:max-w-5xl'>
        <SheetHeader>
          <SheetTitle>Template Schema JSON</SheetTitle>
          <SheetDescription>
            Version {version}
            {filePath ? ` | ${filePath}` : ''}
          </SheetDescription>
        </SheetHeader>

        <div className='flex items-center justify-between gap-3'>
          <div className='text-muted-foreground text-sm'>
            {pageCount > 0 ? `Pages: ${pageCount}` : 'Schema metadata unavailable'}
          </div>

          <Button variant='outline' size='sm' onClick={handleCopy}>
            <IconCopy className='size-4' />
            Copy JSON
          </Button>
        </div>

        {hasSchemaJson ? (
          <pre className='bg-muted max-h-[calc(100vh-180px)] overflow-auto rounded-lg border p-4 font-mono text-xs whitespace-pre'>
            <code>{formattedJson}</code>
          </pre>
        ) : (
          <div className='text-muted-foreground rounded-lg border border-dashed p-6 text-sm'>
            No schema JSON available.
          </div>
        )}
      </SheetContent>
    </Sheet>
  );
}
