'use client';
import { formatErrorBanner } from '@/lib/api/toast-error';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetFooter } from '@/components/ui/sheet';
import { apiFetch } from '@/lib/api/client';
import { TemplateTokenPicker } from '@/components/admin/shared/template-token-picker';

const DOCUMENT_TYPES = [
  { value: 'eoi', label: 'Expression of Interest' },
  { value: 'contract', label: 'Contract' },
  { value: 'nda', label: 'NDA' },
  { value: 'reservation_agreement', label: 'Reservation Agreement' },
  { value: 'letter', label: 'Letter' },
  { value: 'other', label: 'Other' },
] as const;

const EMPTY_DOC = JSON.stringify(
  {
    type: 'doc',
    content: [
      {
        type: 'paragraph',
        content: [{ type: 'text', text: '' }],
      },
    ],
  },
  null,
  2,
);

interface AdminTemplate {
  id: string;
  name: string;
  templateType: string;
  bodyHtml: string;
  version: number;
  isActive: boolean;
  content: Record<string, unknown> | null;
}

interface TemplateFormProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  template?: AdminTemplate | null;
  onSuccess: () => void;
}

export function TemplateForm({ open, onOpenChange, template, onSuccess }: TemplateFormProps) {
  const isEdit = !!template;

  const [name, setName] = useState(template?.name ?? '');
  const [type, setType] = useState(template?.templateType ?? 'other');
  const [contentJson, setContentJson] = useState(
    template?.content ? JSON.stringify(template.content, null, 2) : EMPTY_DOC,
  );
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [jsonError, setJsonError] = useState<string | null>(null);

  function validateJson(value: string): boolean {
    try {
      JSON.parse(value);
      setJsonError(null);
      return true;
    } catch {
      setJsonError('Invalid JSON - check syntax.');
      return false;
    }
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);

    if (!validateJson(contentJson)) return;

    setLoading(true);
    try {
      const content = JSON.parse(contentJson) as Record<string, unknown>;

      if (isEdit) {
        await apiFetch(`/api/v1/admin/templates/${template.id}`, {
          method: 'PATCH',
          body: { name, content },
        });
      } else {
        await apiFetch('/api/v1/admin/templates', {
          method: 'POST',
          body: { name, type, content },
        });
      }
      onSuccess();
      onOpenChange(false);
    } catch (err: unknown) {
      const message = formatErrorBanner(err);
      setError(message);
    } finally {
      setLoading(false);
    }
  }

  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent className="w-full max-w-2xl overflow-y-auto sm:max-w-2xl lg:max-w-4xl">
        <SheetHeader>
          <SheetTitle>{isEdit ? 'Edit Template' : 'New Document Template'}</SheetTitle>
        </SheetHeader>

        <form onSubmit={handleSubmit} className="mt-6 space-y-6">
          {/* Name */}
          <div className="space-y-2">
            <Label htmlFor="template-name">Template Name</Label>
            <Input
              id="template-name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="e.g. EOI Confirmation Letter"
              required
            />
          </div>

          {/* Type - only on create */}
          {!isEdit && (
            <div className="space-y-2">
              <Label htmlFor="template-type">Document Type</Label>
              <Select value={type} onValueChange={setType}>
                <SelectTrigger id="template-type">
                  <SelectValue placeholder="Select type" />
                </SelectTrigger>
                <SelectContent>
                  {DOCUMENT_TYPES.map((t) => (
                    <SelectItem key={t.value} value={t.value}>
                      {t.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          )}

          {/* TipTap JSON Content */}
          <div className="space-y-2">
            <Label htmlFor="template-content">Document Content (TipTap JSON)</Label>
            <p className="text-xs text-muted-foreground">
              Paste or edit TipTap JSON. Use{' '}
              <code className="rounded bg-muted px-1 text-xs">{'{{scope.field}}'}</code> tokens for
              dynamic content - see the list below.
            </p>
            <textarea
              id="template-content"
              value={contentJson}
              onChange={(e) => {
                setContentJson(e.target.value);
                validateJson(e.target.value);
              }}
              rows={18}
              className="w-full rounded-md border border-input bg-background px-3 py-2 font-mono text-xs shadow-sm focus:outline-hidden focus:ring-2 focus:ring-ring"
              spellCheck={false}
            />
            {jsonError && <p className="text-xs text-destructive">{jsonError}</p>}
          </div>

          {/* Available Variables Reference */}
          <details className="rounded-md border p-3">
            <summary className="cursor-pointer text-sm font-medium">
              Available Template Variables
            </summary>
            <div className="mt-3">
              <TemplateTokenPicker />
            </div>
          </details>

          {error && (
            <p className="whitespace-pre-line rounded bg-destructive/10 px-3 py-2 text-sm text-destructive">
              {error}
            </p>
          )}

          <SheetFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              disabled={loading}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={loading || !!jsonError}>
              {loading ? 'Saving…' : isEdit ? 'Save changes' : 'Create Template'}
            </Button>
          </SheetFooter>
        </form>
      </SheetContent>
    </Sheet>
  );
}
