// app/components/admin/CommonComponents/SchemaEditor.tsx
'use client';

import { useState } from 'react';
import toast from 'react-hot-toast';

export interface JsonLdSchema {
  '@context': 'https://schema.org' | 'https://schema.org/';
  '@type': string;
  name?: string;
  url?: string;
  [key: string]: unknown;
}

interface SchemaTemplate {
  id: string;
  name: string;
  description: string;
  template: JsonLdSchema;
}

interface SchemaEditorProps {
  schemas: JsonLdSchema[];
  onChange: (schemas: JsonLdSchema[]) => void;
  siteContext?: {
    name?: string;
    logo?: string;
    contact_phone?: string;
    contact_email?: string;
    facebook_url?: string;
    twitter_url?: string;
    linkedin_url?: string;
    instagram_url?: string;
    youtube_url?: string;
    address?: string;
  };
  className?: string;
}

function isValidSchema(json: string): boolean {
  try {
    const p = JSON.parse(json) as JsonLdSchema;
    return (p['@context'] === 'https://schema.org' || p['@context'] === 'https://schema.org/') && !!p['@type'];
  } catch {
    return false;
  }
}

const SCHEMA_TYPES = ['WebSite', 'Organization', 'LocalBusiness', 'Person', 'Product', 'Article', 'Event'];

export default function SchemaEditor({
  schemas,
  onChange,
  siteContext = {},
  className = '',
}: SchemaEditorProps) {
  const [editingIndex, setEditingIndex] = useState<number | null>(null);
  const [jsonInput, setJsonInput] = useState('');
  const [activeType, setActiveType] = useState('WebSite');

  const origin = typeof window !== 'undefined' ? window.location.origin : 'https://yoursite.com';

  const templates: SchemaTemplate[] = [
    {
      id: 'website',
      name: 'Website',
      description: 'For your main website',
      template: {
        '@context': 'https://schema.org',
        '@type': 'WebSite',
        name: siteContext.name || 'Your Website',
        url: origin,
        potentialAction: {
          '@type': 'SearchAction',
          target: { '@type': 'EntryPoint', urlTemplate: '{search_term_string}' },
          'query-input': 'required name=search_term_string',
        },
      },
    },
    {
      id: 'organization',
      name: 'Organization',
      description: 'For your organization/business',
      template: {
        '@context': 'https://schema.org',
        '@type': 'Organization',
        name: siteContext.name || 'Your Company',
        url: origin,
        logo: siteContext.logo || '',
        contactPoint: {
          '@type': 'ContactPoint',
          telephone: siteContext.contact_phone || '',
          email: siteContext.contact_email || '',
          contactType: 'customer service',
        },
        sameAs: [
          siteContext.facebook_url,
          siteContext.twitter_url,
          siteContext.linkedin_url,
          siteContext.instagram_url,
          siteContext.youtube_url,
        ].filter(Boolean) as string[],
      },
    },
    {
      id: 'local-business',
      name: 'Local Business',
      description: 'For businesses with a physical location',
      template: {
        '@context': 'https://schema.org',
        '@type': 'LocalBusiness',
        name: siteContext.name || 'Your Business',
        image: siteContext.logo || '',
        address: {
          '@type': 'PostalAddress',
          streetAddress: siteContext.address ? siteContext.address.split(',')[0] : '',
          addressLocality: '',
          addressRegion: '',
          postalCode: '',
          addressCountry: 'US',
        },
        telephone: siteContext.contact_phone || '',
        openingHours: 'Mo-Fr 09:00-17:00',
      },
    },
  ];

  const addFromTemplate = (templateId?: string) => {
    const tpl = templates.find(t => t.id === templateId) ?? templates[0];
    const newSchemas = [...schemas, tpl.template];
    onChange(newSchemas);
    openEditor(newSchemas.length - 1, tpl.template);
    toast.success('Schema added');
  };

  const openEditor = (index: number, schema: JsonLdSchema) => {
    setEditingIndex(index);
    setJsonInput(JSON.stringify(schema, null, 2));
    setActiveType(schema['@type'] || 'WebSite');
  };

  const closeEditor = () => {
    setEditingIndex(null);
    setJsonInput('');
  };

  const saveEdit = () => {
    if (editingIndex === null) return;
    try {
      const parsed = JSON.parse(jsonInput) as JsonLdSchema;
      const updated = schemas.map((s, i) => (i === editingIndex ? { ...s, ...parsed } : s));
      onChange(updated);
      closeEditor();
      toast.success('Schema updated');
    } catch {
      toast.error('Invalid JSON format');
    }
  };

  const removeSchema = (index: number) => {
    if (schemas.length <= 1) {
      toast.error('At least one schema is required');
      return;
    }
    onChange(schemas.filter((_, i) => i !== index));
    if (editingIndex === index) closeEditor();
    else if (editingIndex !== null && editingIndex > index) setEditingIndex(editingIndex - 1);
    toast.success('Schema removed');
  };

  const applyTypeChange = (type: string) => {
    setActiveType(type);
    try {
      const parsed = JSON.parse(jsonInput) as JsonLdSchema;
      setJsonInput(JSON.stringify({ ...parsed, '@type': type }, null, 2));
    } catch {
      // If JSON is currently invalid just update the type state
    }
  };

  const applyTemplate = (templateId: string) => {
    const tpl = templates.find(t => t.id === templateId);
    if (tpl) {
      setJsonInput(JSON.stringify(tpl.template, null, 2));
      setActiveType(tpl.template['@type']);
      toast.success(`${tpl.name} template applied`);
    }
  };

  return (
    <div className={`space-y-6 ${className}`}>
      <div>
        <h4 className="text-sm font-medium text-var-text mb-3">Quick Templates</h4>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
          {templates.map(tpl => (
            <button
              key={tpl.id}
              type="button"
              onClick={() => addFromTemplate(tpl.id)}
              className="p-4 border border-var-border rounded-xl text-left hover:border-var-primary hover:bg-var-primary-muted transition-colors duration-150"
            >
              <div className="font-medium text-var-text text-sm">{tpl.name}</div>
              <div className="text-xs text-var-text-muted mt-1">{tpl.description}</div>
            </button>
          ))}
        </div>
      </div>

      <div>
        <div className="flex items-center justify-between mb-3">
          <h4 className="text-sm font-medium text-var-text">Current Schemas ({schemas.length})</h4>
          <button
            type="button"
            onClick={() => addFromTemplate()}
            className="px-3 py-1.5 text-sm font-medium text-white bg-var-primary rounded-xl hover:bg-var-primary-hover transition-colors duration-150"
          >
            + Add Schema
          </button>
        </div>

        {schemas.length === 0 ? (
          <div className="text-center py-8 border-2 border-dashed border-var-border rounded-xl">
            <p className="text-var-text-muted text-sm">No schemas added yet</p>
            <p className="text-xs text-var-text-muted/80 mt-1">Add your first schema using the templates above</p>
          </div>
        ) : (
          <div className="space-y-3">
            {schemas.map((schema, index) => (
              <div key={index} className="border border-var-border rounded-xl overflow-hidden">
                <div className="px-4 py-3 bg-var-surface-hover flex items-center justify-between">
                  <div className="flex items-center gap-2 min-w-0">
                    <span className="font-medium text-var-text text-sm truncate">
                      {schema['@type'] || 'Unknown Type'}
                    </span>
                    {schema.name && (
                      <span className="text-var-text-muted text-sm truncate">— {String(schema.name)}</span>
                    )}
                  </div>
                  <div className="flex items-center gap-2 shrink-0 ml-3">
                    <button
                      type="button"
                      onClick={() => editingIndex === index ? closeEditor() : openEditor(index, schema)}
                      className="px-3 py-1 text-xs font-medium text-var-primary bg-var-primary-muted rounded-lg hover:bg-var-primary/20 transition-colors duration-150"
                    >
                      {editingIndex === index ? 'Close' : 'Edit'}
                    </button>
                    <button
                      type="button"
                      onClick={() => removeSchema(index)}
                      className="px-3 py-1 text-xs font-medium text-var-danger bg-var-danger-bg rounded-lg hover:bg-var-danger/20 transition-colors duration-150"
                    >
                      Remove
                    </button>
                  </div>
                </div>

                {editingIndex === index && (
                  <div className="p-4 border-t border-var-border space-y-4">
                    <div className="flex items-center justify-between flex-wrap gap-2">
                      <label className="text-sm font-medium text-var-text">Schema JSON</label>
                      <div className="flex items-center gap-2">
                        <select
                          value={activeType}
                          onChange={e => applyTypeChange(e.target.value)}
                          className="text-sm border border-var-border rounded-lg px-2 py-1 bg-var-surface text-var-text focus:ring-1 focus:ring-var-primary"
                        >
                          {SCHEMA_TYPES.map(t => (
                            <option key={t} value={t}>{t}</option>
                          ))}
                        </select>
                        <select
                          defaultValue=""
                          onChange={e => { if (e.target.value) applyTemplate(e.target.value); }}
                          className="text-sm border border-var-border rounded-lg px-2 py-1 bg-var-surface text-var-text focus:ring-1 focus:ring-var-primary"
                        >
                          <option value="">Apply Template</option>
                          {templates.map(t => (
                            <option key={t.id} value={t.id}>{t.name}</option>
                          ))}
                        </select>
                      </div>
                    </div>

                    <textarea
                      value={jsonInput}
                      onChange={e => setJsonInput(e.target.value)}
                      rows={8}
                      className="w-full px-3 py-2 border border-var-border rounded-xl font-mono text-sm bg-var-input text-var-text placeholder-var-text-muted focus:ring-2 focus:ring-var-primary focus:border-var-primary transition-colors duration-200"
                      placeholder='{"@context": "https://schema.org", "@type": "WebSite", ...}'
                    />

                    <div className="flex items-center justify-between">
                      {isValidSchema(jsonInput) ? (
                        <span className="flex items-center gap-1 text-sm text-var-success">
                          <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                            <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                          </svg>
                          Valid JSON-LD Schema
                        </span>
                      ) : (
                        <span className="flex items-center gap-1 text-sm text-var-danger">
                          <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                            <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                          </svg>
                          Invalid JSON or missing required fields
                        </span>
                      )}
                      <span className="text-xs text-var-text-muted">
                        {new Blob([jsonInput]).size} bytes
                      </span>
                    </div>

                    <div className="flex justify-end gap-3">
                      <button
                        type="button"
                        onClick={closeEditor}
                        className="px-4 py-2 text-sm font-medium text-var-text-secondary bg-var-surface border border-var-border rounded-lg hover:bg-var-surface-hover transition-colors duration-150"
                      >
                        Cancel
                      </button>
                      <button
                        type="button"
                        onClick={saveEdit}
                        disabled={!isValidSchema(jsonInput)}
                        className="px-4 py-2 text-sm font-medium text-white bg-var-success rounded-lg hover:bg-var-success/80 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-150"
                      >
                        Save Changes
                      </button>
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>

      <div className="p-4 bg-var-info-bg border border-var-border rounded-xl flex gap-2">
        <svg className="w-5 h-5 text-var-info mt-0.5 shrink-0" fill="currentColor" viewBox="0 0 20 20">
          <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
        </svg>
        <p className="text-sm text-var-info-text">
          <strong>Tip:</strong> JSON-LD schemas help search engines understand your content.
          Add multiple schemas for different aspects of your site — Website, Organization, Local Business, etc.
        </p>
      </div>
    </div>
  );
}