'use client';

/**
 * PublishDialog — confirms publishing the current draft.
 *
 * On mount fetches the live version and diffs it against the local draft to
 * show a summary of changes. Admin can add an optional note before confirming.
 */

import { useEffect, useId, useState } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/overlays/Dialog';
import { Button } from '@/components/ui/primitives/Button';
import { FormField } from '@/components/ui/primitives/FormField';
import { Input } from '@/components/ui/primitives/Input';
import { useT } from '@/lib/i18n/react';
import { diffLayouts, type LayoutDiff } from './diff';
import { fetchPage, publish } from './api';
import type { LayoutBody } from '@/server/page-layout/types';

export interface PublishDialogProps {
  page: string;
  draft: LayoutBody;
  onPublished: () => void;
  onClose: () => void;
}

export function PublishDialog({ page, draft, onPublished, onClose }: PublishDialogProps) {
  const t = useT('page_organizer');
  const noteId = useId();
  const [diff, setDiff] = useState<LayoutDiff | null>(null);
  const [note, setNote] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    void fetchPage(page).then((r) => {
      const draftBody = (r.draft?.body ?? draft) as LayoutBody;
      setDiff(diffLayouts(r.liveVersion.body as LayoutBody, draftBody));
    });
  }, [page, draft]);

  async function handlePublish() {
    setBusy(true);
    setError(null);
    try {
      await publish(page, { note: note.trim() || undefined });
      onPublished();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unknown error');
    } finally {
      setBusy(false);
    }
  }

  return (
    <Dialog open onOpenChange={(open) => !open && onClose()}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{t('btn_publish')}</DialogTitle>
        </DialogHeader>

        {diff && (
          <ul
            aria-label={t('btn_publish')}
            className="text-text-secondary mb-4 flex flex-col gap-1 text-sm"
          >
            <li>
              <span className="text-text-primary font-medium">{t('publish_diff_added')}:</span>{' '}
              {diff.added.length}
            </li>
            <li>
              <span className="text-text-primary font-medium">{t('publish_diff_removed')}:</span>{' '}
              {diff.removed.length}
            </li>
            <li>
              <span className="text-text-primary font-medium">{t('publish_diff_reordered')}:</span>{' '}
              {diff.reordered.length}
            </li>
            <li>
              <span className="text-text-primary font-medium">{t('publish_diff_edited')}:</span>{' '}
              {diff.edited.length}
            </li>
          </ul>
        )}

        <FormField label={t('publish_note_label')} htmlFor={noteId}>
          <Input
            id={noteId}
            value={note}
            onChange={(e) => setNote(e.target.value)}
            maxLength={500}
          />
        </FormField>

        {error && (
          <p role="alert" className="text-danger-600 mt-2 text-sm">
            {error}
          </p>
        )}

        <DialogFooter>
          <Button
            variant="primary"
            disabled={busy}
            loading={busy}
            onClick={() => void handlePublish()}
          >
            {t('btn_publish')}
          </Button>
          <Button variant="ghost" onClick={onClose}>
            {t('btn_cancel')}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
