// src/components/ui/SchemaEditor.tsx

'use client';

import { useState, useCallback } from 'react';
import toast from 'react-hot-toast';

// ─── Types ────────────────────────────────────────────────────────────────────

type SchemaValue = Record<string, unknown>;
type SchemaEntry = [string, unknown];

interface SchemaEditorProps {
  value: SchemaValue;
  onChange: (schemas: SchemaValue) => void;
  label?: string;
  placeholder?: string;
  isRTL?: boolean;
}

// ─── Constants ────────────────────────────────────────────────────────────────

const INPUT_STYLE = {
  background: 'var(--color-surface-alt)',
  border: '1px solid var(--color-border-muted)',
  color: 'var(--color-text)',
} as const;

const LABEL_STYLE = { color: 'var(--color-text-secondary)' } as const;

// ─── Component ────────────────────────────────────────────────────────────────

export default function SchemaEditor({
  value,
  onChange,
  label = 'Schema Markup (JSON-LD)',
  placeholder = 'Enter schema JSON data...',
}: SchemaEditorProps) {
  const [schemaData, setSchemaData] = useState<string>('');
  const [isAdding, setIsAdding] = useState<boolean>(false);

  // `editingKey` = the ORIGINAL key name when editing an existing schema, null when adding a new one.
  // `keyInput` = the current value shown/typed in the key field (used for both add + edit).
  const [editingKey, setEditingKey] = useState<string | null>(null);
  const [keyInput, setKeyInput] = useState<string>('');

  // ── Helpers ─────────────────────────────────────────────────────────────────

  const formatJSON = useCallback((obj: unknown): string => {
    try {
      return JSON.stringify(obj, null, 2);
    } catch {
      return '{}';
    }
  }, []);

  const parseJSON = useCallback((str: string): unknown => {
    try {
      return JSON.parse(str);
    } catch {
      return null;
    }
  }, []);

  // ── Handlers ─────────────────────────────────────────────────────────────────

  const handleAddSchema = useCallback(() => {
    const trimmedKey = keyInput.trim();

    if (!trimmedKey) {
      toast.error('Please enter a schema key');
      return;
    }

    if (!schemaData.trim()) {
      toast.error('Please enter schema data');
      return;
    }

    const parsed = parseJSON(schemaData);
    if (!parsed) {
      toast.error('Invalid JSON format. Please check your schema data.');
      return;
    }

    const isRename = editingKey !== null && editingKey !== trimmedKey;
    const keyAlreadyExists = Object.prototype.hasOwnProperty.call(value, trimmedKey);

    // Only ask for confirmation if we're about to overwrite a DIFFERENT existing schema
    // (i.e. brand-new key that collides, or a rename that collides with another entry).
    if (keyAlreadyExists && (editingKey === null || isRename)) {
      if (!confirm(`Schema "${trimmedKey}" already exists. Do you want to replace it?`)) {
        return;
      }
    }

    const newSchemas = { ...value };
    if (isRename && editingKey) {
      delete newSchemas[editingKey];
    }
    newSchemas[trimmedKey] = parsed;

    onChange(newSchemas);

    setSchemaData('');
    setIsAdding(false);
    setEditingKey(null);
    setKeyInput('');
    toast.success(editingKey ? 'Schema updated successfully' : 'Schema added successfully');
  }, [keyInput, schemaData, parseJSON, editingKey, value, onChange]);

  const handleRemoveSchema = useCallback((key: string) => {
    if (!confirm(`Are you sure you want to remove this schema?`)) {
      return;
    }

    const newSchemas = { ...value };
    delete newSchemas[key];
    onChange(newSchemas);
    toast.success('Schema removed');
  }, [value, onChange]);

  const handleEditSchema = useCallback((key: string) => {
    setEditingKey(key);
    setKeyInput(key);
    setSchemaData(formatJSON(value[key]));
    setIsAdding(true);
  }, [value, formatJSON]);

  const handleStartAdd = useCallback(() => {
    setEditingKey(null);
    setKeyInput(`schema_${Object.keys(value).length + 1}`);
    setSchemaData('');
    setIsAdding(true);
  }, [value]);

  const handleCancelEdit = useCallback(() => {
    setIsAdding(false);
    setEditingKey(null);
    setSchemaData('');
    setKeyInput('');
  }, []);

  const loadSampleSchema = useCallback(() => {
    const sample = {
      '@context': 'https://schema.org',
      '@type': 'Product',
      name: 'Product Name',
      description: 'Product description',
      brand: {
        '@type': 'Brand',
        name: 'Brand Name',
      },
      offers: {
        '@type': 'Offer',
        price: '0.00',
        priceCurrency: 'USD',
        availability: 'https://schema.org/InStock',
      },
    };
    setSchemaData(formatJSON(sample));
  }, [formatJSON]);

  const getPropertyCount = useCallback((data: unknown): number => {
    if (data && typeof data === 'object' && !Array.isArray(data)) {
      return Object.keys(data).length;
    }
    return 0;
  }, []);

  // ── Render ──────────────────────────────────────────────────────────────────

  return (
    <div className="space-y-3">
      <label className="block text-sm font-medium" style={LABEL_STYLE}>
        {label}
      </label>

      {/* Existing Schemas */}
      {Object.keys(value).length > 0 && (
        <div className="space-y-2">
          {Object.entries(value).map(([key, data]: SchemaEntry) => (
            <div
              key={key}
              className="flex items-center justify-between p-3 rounded-lg"
              style={{
                background: 'var(--color-surface-alt)',
                border: '1px solid var(--color-border)',
              }}
            >
              <div className="flex items-center gap-2">
                <span className="text-sm font-medium" style={{ color: 'var(--color-text)' }}>
                  {key}
                </span>
                <span className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
                  ({getPropertyCount(data)} properties)
                </span>
              </div>
              <div className="flex gap-2">
                <button
                  type="button"
                  onClick={() => handleEditSchema(key)}
                  className="px-2 py-1 text-xs rounded transition-all hover:opacity-80"
                  style={{ color: 'var(--color-info)' }}
                >
                  Edit
                </button>
                <button
                  type="button"
                  onClick={() => handleRemoveSchema(key)}
                  className="px-2 py-1 text-xs rounded transition-all hover:opacity-80"
                  style={{ color: 'var(--color-danger)' }}
                >
                  Remove
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Add/Edit Schema Form */}
      {!isAdding ? (
        <button
          type="button"
          onClick={handleStartAdd}
          className="px-4 py-2 rounded-lg text-sm font-medium transition-all hover:opacity-80"
          style={{ background: 'var(--color-cta-light)', color: 'var(--color-cta)' }}
        >
          + Add Schema
        </button>
      ) : (
        <div className="space-y-3 p-4 rounded-lg" style={{
          background: 'var(--color-surface-alt)',
          border: '1px solid var(--color-border)',
        }}>
          <div className="flex items-center justify-between">
            <label className="text-sm font-medium" style={LABEL_STYLE}>
              {editingKey ? `Edit Schema: ${editingKey}` : 'Add New Schema'}
            </label>
            <div className="flex gap-2">
              <button
                type="button"
                onClick={loadSampleSchema}
                className="text-xs transition-all hover:opacity-80 px-2 py-1 rounded"
                style={{ background: 'var(--color-info-light)', color: 'var(--color-info)' }}
              >
                Load Sample
              </button>
              <button
                type="button"
                onClick={handleCancelEdit}
                className="text-xs transition-all hover:opacity-80"
                style={{ color: 'var(--color-text-tertiary)' }}
              >
                Cancel
              </button>
            </div>
          </div>

          {/* Key field is now ALWAYS visible and editable, both when adding and when editing */}
          <div>
            <label className="block text-xs font-medium mb-1" style={LABEL_STYLE}>
              Schema Key (e.g., product, article, faq)
            </label>
            <input
              type="text"
              value={keyInput}
              onChange={(e) => setKeyInput(e.target.value)}
              placeholder="Enter schema key..."
              className="w-full px-3 py-2 rounded-lg text-sm outline-none"
              style={INPUT_STYLE}
            />
          </div>

          <div>
            <label className="block text-xs font-medium mb-1" style={LABEL_STYLE}>
              Schema Data (JSON)
            </label>
            <textarea
              rows={8}
              value={schemaData}
              onChange={(e) => setSchemaData(e.target.value)}
              placeholder={placeholder}
              className="w-full px-3 py-2 rounded-lg text-sm outline-none font-mono resize-none"
              style={{
                ...INPUT_STYLE,
                direction: 'ltr', // JSON always LTR
              }}
            />
            <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
              Enter valid JSON-LD schema markup
            </p>
          </div>

          <button
            type="button"
            onClick={handleAddSchema}
            className="px-4 py-2 rounded-lg text-sm font-medium transition-all hover:opacity-80"
            style={{ background: 'var(--color-cta)', color: 'white' }}
          >
            {editingKey ? 'Update Schema' : 'Add Schema'}
          </button>
        </div>
      )}

      <p className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
        Schemas will be used for SEO and structured data markup
      </p>
    </div>
  );
}