/**
 * Schema Library - Manage all schema configurations
 * Dashboard view for created schemas
 */

import { useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import {
  PlusIcon,
  MagnifyingGlassIcon,
  Squares2X2Icon,
  ListBulletIcon,
  EllipsisVerticalIcon,
  DocumentDuplicateIcon,
  ArrowDownTrayIcon,
  TrashIcon,
  PencilSquareIcon,
  CircleStackIcon,
  GlobeAltIcon,
  CheckCircleIcon,
  FolderIcon
} from '@heroicons/react/24/outline';
import { Button, Input, Select, Toggle, Card, Badge, Alert } from '../../../../components/ui';
import { schemaTypes } from '../utils/schemaTypes';

const SchemaLibrary = ({ schemas, onAddNew, onEdit, onDelete, onToggleStatus, onDuplicate }) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [filterType, setFilterType] = useState('all');
  const [view, setView] = useState('grid'); // grid or list
  const [showMenu, setShowMenu] = useState(null);

  const adminBase =
    typeof window !== 'undefined' && window?.prorankSeo?.adminUrl
      ? window.prorankSeo.adminUrl
      : '/wp-admin/';
  const normalizedAdminBase = adminBase.endsWith('/') ? adminBase : `${adminBase}/`;
  const newPageEditorUrl = `${normalizedAdminBase}post-new.php?post_type=page`;
  const newPostEditorUrl = `${normalizedAdminBase}post-new.php`;
  const schemaDocsUrl = 'https://prorank.io/docs/schema-markup';

  /**
   * Handle schema export - downloads schema config as JSON file
   */
  const handleExport = (schema) => {
    const exportData = {
      version: '1.0',
      exported: new Date().toISOString(),
      plugin: 'prorank-seo',
      schema: {
        name: schema.name,
        type: schema.type,
        targeting: schema.targeting,
        mapping: schema.mapping,
        priority: schema.priority || 10
      }
    };

    const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `schema-${schema.type}-${Date.now()}.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  /**
   * Handle schema duplication
   */
  const handleDuplicate = (schema) => {
    if (onDuplicate) {
      onDuplicate(schema);
    }
  };

  // Filter schemas
  const filteredSchemas = schemas.filter(schema => {
    const matchesSearch = !searchTerm ||
      schema.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      schema.type.toLowerCase().includes(searchTerm.toLowerCase());

    const matchesType = filterType === 'all' || schema.type === filterType;

    return matchesSearch && matchesType;
  });

  // Get unique schema types for filter
  const uniqueTypes = [...new Set(schemas.map(s => s.type))];

  const getSchemaIcon = (type) => {
    return schemaTypes[type]?.icon || CircleStackIcon;
  };

  const getSchemaLabel = (type) => {
    return schemaTypes[type]?.label || type;
  };

  const getTargetingSummary = (targeting) => {
    const parts = [];

    if (targeting.mode === 'auto') {
      return __('Automatic targeting', 'prorank-seo');
    }

    if (targeting.postTypes?.length) {
      parts.push(`${targeting.postTypes.length} post types`);
    }
    if (targeting.categories?.length) {
      parts.push(`${targeting.categories.length} categories`);
    }
    if (targeting.tags?.length) {
      parts.push(`${targeting.tags.length} tags`);
    }
    if (targeting.specific?.length) {
      parts.push(`${targeting.specific.length} specific pages`);
    }
    if (targeting.rules?.length) {
      parts.push(`${targeting.rules.length} custom rules`);
    }

    return parts.length ? parts.join(', ') : __('No targeting set', 'prorank-seo');
  };

  const getMappingSummary = (mapping) => {
    const mapped = Object.keys(mapping).length;
    if (mapped === 0) return __('No fields mapped', 'prorank-seo');
    return `${mapped} fields mapped`;
  };

  const getTargetingScopeCount = (targeting = {}) => {
    if (!targeting || typeof targeting !== 'object') {
      return 0;
    }

    if (targeting.mode === 'auto') {
      return 1;
    }

    return (
      (targeting.postTypes?.length || 0) +
      (targeting.categories?.length || 0) +
      (targeting.tags?.length || 0) +
      (targeting.specific?.length || 0) +
      (targeting.rules?.length || 0) +
      (targeting.userRoles?.length || 0)
    );
  };

  const handleMenuAction = (action, schema) => {
    setShowMenu(null);
    switch (action) {
      case 'edit':
        onEdit(schema);
        break;
      case 'duplicate':
        handleDuplicate(schema);
        break;
      case 'export':
        handleExport(schema);
        break;
      case 'delete':
        onDelete(schema.id);
        break;
      default:
        break;
    }
  };

  return (
    <div className="pr:space-y-6">
      {/* Header */}
      <div className="pr:flex pr:items-start pr:justify-between pr:gap-4">
        <div className="pr:flex-1">
          <h2 className="pr:text-2xl pr:font-semibold pr:text-gray-900 pr:mb-2">
            {__('Schema Configurations', 'prorank-seo')}
          </h2>
          <p className="pr:text-sm pr:text-gray-600">
            {__('Manage your schema markup configurations. Each configuration can be applied to multiple pages automatically.', 'prorank-seo')}
          </p>
        </div>
        <Button
          variant="primary"
          icon={PlusIcon}
          onClick={onAddNew}
        >
          {__('Add New Schema', 'prorank-seo')}
        </Button>
      </div>

      {/* Quick Links: FAQ/HowTo Blocks */}
      <Card variant="flat" className="pr:border pr:border-primary-200 pr:bg-primary-50">
        <div className="pr:flex pr:flex-col pr:lg:flex-row pr:items-start pr:lg:items-center pr:justify-between pr:gap-4">
          <div className="pr:space-y-1">
            <h3 className="pr:text-sm pr:font-semibold pr:text-gray-900">
              {__('Use FAQ & HowTo Schema Blocks', 'prorank-seo')}
            </h3>
            <p className="pr:text-sm pr:text-gray-700">
              {__('Open the editor and insert “ProRank FAQ Schema” or “ProRank HowTo Schema” blocks from the ProRank SEO category.', 'prorank-seo')}
            </p>
          </div>
          <div className="pr:flex pr:flex-wrap pr:gap-2">
            <a
              href={newPageEditorUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="pr:inline-flex pr:items-center pr:justify-center pr:px-3 pr:py-2 pr:bg-primary-500 pr:text-white pr:rounded-md pr:text-sm pr:font-medium pr:hover:bg-primary-600 pr:transition-colors"
            >
              {__('New Page Editor', 'prorank-seo')}
            </a>
            <a
              href={newPostEditorUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="pr:inline-flex pr:items-center pr:justify-center pr:px-3 pr:py-2 pr:bg-white pr:text-gray-800 pr:border pr:border-gray-300 pr:rounded-md pr:text-sm pr:font-medium pr:hover:bg-gray-100 pr:transition-colors"
            >
              {__('New Post Editor', 'prorank-seo')}
            </a>
            <a
              href={schemaDocsUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="pr:inline-flex pr:items-center pr:justify-center pr:px-3 pr:py-2 pr:text-sm pr:text-primary-700 pr:font-medium pr:hover:text-primary-800 pr:hover:underline"
            >
              {__('Schema Docs', 'prorank-seo')}
            </a>
          </div>
        </div>
      </Card>

      {/* Stats Cards */}
      <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-2 pr:lg:grid-cols-4 pr:gap-4">
        <Card variant="elevated" className="pr:bg-white">
          <div className="pr:flex pr:items-center pr:gap-4">
            <div className="pr:flex pr:items-center pr:justify-center pr:w-12 pr:h-12 pr:bg-primary-100 pr:rounded-lg">
              <FolderIcon className="pr:w-6 pr:h-6 pr:text-primary-600" />
            </div>
            <div>
              <div className="pr:text-2xl pr:font-bold pr:text-gray-900">
                {schemas.length}
              </div>
              <div className="pr:text-xs pr:text-gray-600">
                {__('Total Schemas', 'prorank-seo')}
              </div>
            </div>
          </div>
        </Card>

        <Card variant="elevated" className="pr:bg-white">
          <div className="pr:flex pr:items-center pr:gap-4">
            <div className="pr:flex pr:items-center pr:justify-center pr:w-12 pr:h-12 pr:bg-success-100 pr:rounded-lg">
              <CheckCircleIcon className="pr:w-6 pr:h-6 pr:text-success-600" />
            </div>
            <div>
              <div className="pr:text-2xl pr:font-bold pr:text-gray-900">
                {schemas.filter(s => s.status === 'active').length}
              </div>
              <div className="pr:text-xs pr:text-gray-600">
                {__('Active Schemas', 'prorank-seo')}
              </div>
            </div>
          </div>
        </Card>

        <Card variant="elevated" className="pr:bg-white">
          <div className="pr:flex pr:items-center pr:gap-4">
            <div className="pr:flex pr:items-center pr:justify-center pr:w-12 pr:h-12 pr:bg-info-100 pr:rounded-lg">
              <CircleStackIcon className="pr:w-6 pr:h-6 pr:text-info-600" />
            </div>
            <div>
              <div className="pr:text-2xl pr:font-bold pr:text-gray-900">
                {uniqueTypes.length}
              </div>
              <div className="pr:text-xs pr:text-gray-600">
                {__('Schema Types', 'prorank-seo')}
              </div>
            </div>
          </div>
        </Card>

        <Card variant="elevated" className="pr:bg-white">
          <div className="pr:flex pr:items-center pr:gap-4">
            <div className="pr:flex pr:items-center pr:justify-center pr:w-12 pr:h-12 pr:bg-warning-100 pr:rounded-lg">
              <GlobeAltIcon className="pr:w-6 pr:h-6 pr:text-warning-600" />
            </div>
            <div>
              <div className="pr:text-2xl pr:font-bold pr:text-gray-900">
                {schemas.reduce((acc, s) => acc + getTargetingScopeCount(s.targeting), 0)}
              </div>
              <div className="pr:text-xs pr:text-gray-600">
                {__('Target Rules', 'prorank-seo')}
              </div>
            </div>
          </div>
        </Card>
      </div>

      {/* Controls */}
      <Card variant="flat">
        <div className="pr:flex pr:flex-wrap pr:items-center pr:gap-4">
          <div className="pr:flex-1 pr:min-w-[200px]">
            <Input
              type="search"
              value={searchTerm}
              onChange={(value) => setSearchTerm(value)}
              placeholder={__('Search schemas...', 'prorank-seo')}
              leftIcon={MagnifyingGlassIcon}
            />
          </div>

          <Select
            value={filterType}
            onChange={(value) => setFilterType(value)}
            className="pr:min-w-[150px]"
          >
            <option value="all">{__('All Types', 'prorank-seo')}</option>
            {uniqueTypes.map(type => (
              <option key={type} value={type}>{getSchemaLabel(type)}</option>
            ))}
          </Select>

          <div className="pr:flex pr:gap-2 pr:border-l pr:border-gray-200 pr:pl-4">
            <Button
              variant={view === 'grid' ? 'primary' : 'secondary'}
              size="sm"
              icon={Squares2X2Icon}
              onClick={() => setView('grid')}
              aria-label={__('Grid View', 'prorank-seo')}
            />
            <Button
              variant={view === 'list' ? 'primary' : 'secondary'}
              size="sm"
              icon={ListBulletIcon}
              onClick={() => setView('list')}
              aria-label={__('List View', 'prorank-seo')}
            />
          </div>
        </div>
      </Card>

      {/* Empty State */}
      {filteredSchemas.length === 0 ? (
        <Card className="pr:text-center pr:py-12">
          <FolderIcon className="pr:w-16 pr:h-16 pr:text-gray-300 pr:mx-auto pr:mb-4" />
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900 pr:mb-2">
            {__('No Schemas Found', 'prorank-seo')}
          </h3>
          <p className="pr:text-sm pr:text-gray-600 pr:mb-6">
            {searchTerm
              ? __('No schemas match your search criteria.', 'prorank-seo')
              : __("You haven't created any schema configurations yet.", 'prorank-seo')
            }
          </p>
          {!searchTerm && (
            <Button variant="primary" icon={PlusIcon} onClick={onAddNew}>
              {__('Create Your First Schema', 'prorank-seo')}
            </Button>
          )}
        </Card>
      ) : (
        /* Schema Grid/List */
        <div className={
          view === 'grid'
            ? 'pr:grid pr:grid-cols-1 pr:md:grid-cols-2 pr:lg:grid-cols-3 pr:gap-4'
            : 'pr:space-y-4'
        }>
          {filteredSchemas.map(schema => (
            <Card
              key={schema.id}
              hoverable
              className={schema.status === 'inactive' ? 'pr:opacity-60' : ''}
            >
              <div className="pr:space-y-4">
                {/* Header */}
                <div className="pr:flex pr:items-start pr:justify-between pr:gap-3">
                  <div className="pr:flex pr:items-center pr:gap-3 pr:flex-1">
                    <div className="pr:flex pr:items-center pr:justify-center pr:w-10 pr:h-10 pr:bg-primary-100 pr:rounded-lg pr:shrink-0">
                      <span className="pr:text-primary-600 pr:text-lg">
                        {schema.icon || '📄'}
                      </span>
                    </div>
                    <div className="pr:flex-1 pr:min-w-0">
                      <h4 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-1 pr:truncate">
                        {schema.name}
                      </h4>
                      <Badge variant="info" size="sm">
                        {getSchemaLabel(schema.type)}
                      </Badge>
                    </div>
                  </div>

                  {/* Status Toggle */}
                  <Toggle
                    checked={schema.status === 'active'}
                    onChange={() => onToggleStatus(schema)}
                    size="sm"
                  />
                </div>

                {/* Details */}
                <div className="pr:space-y-2 pr:text-sm pr:text-gray-600">
                  <div className="pr:flex pr:items-center pr:gap-2">
                    <GlobeAltIcon className="pr:w-4 pr:h-4 pr:text-gray-400 pr:shrink-0" />
                    <span className="pr:truncate">{getTargetingSummary(schema.targeting)}</span>
                  </div>
                  <div className="pr:flex pr:items-center pr:gap-2">
                    <CircleStackIcon className="pr:w-4 pr:h-4 pr:text-gray-400 pr:shrink-0" />
                    <span className="pr:truncate">{getMappingSummary(schema.mapping)}</span>
                  </div>
                  {schema.priority && (
                    <div className="pr:flex pr:items-center pr:gap-2">
                      <span className="pr:text-xs pr:text-gray-500">
                        {__('Priority:', 'prorank-seo')} {schema.priority}
                      </span>
                    </div>
                  )}
                </div>

                {/* Actions */}
                <div className="pr:flex pr:items-center pr:gap-2 pr:pt-3 pr:border-t pr:border-gray-200">
                  <Button
                    variant="secondary"
                    size="sm"
                    icon={PencilSquareIcon}
                    onClick={() => onEdit(schema)}
                    fullWidth
                  >
                    {__('Edit', 'prorank-seo')}
                  </Button>

                  <div className="pr:relative">
                    <Button
                      variant="ghost"
                      size="sm"
                      icon={EllipsisVerticalIcon}
                      onClick={() => setShowMenu(showMenu === schema.id ? null : schema.id)}
                      aria-label={__('More actions', 'prorank-seo')}
                    />

                    {/* Dropdown Menu */}
                    {showMenu === schema.id && (
                      <div className="pr:absolute pr:right-0 pr:mt-2 pr:w-48 pr:bg-white pr:rounded-lg pr:shadow-lg pr:border pr:border-gray-200 pr:py-1 pr:z-10">
                        <button
                          className="pr:w-full pr:px-4 pr:py-2 pr:text-left pr:text-sm pr:text-gray-700 pr:hover:bg-gray-50 pr:flex pr:items-center pr:gap-2"
                          onClick={() => handleMenuAction('edit', schema)}
                        >
                          <PencilSquareIcon className="pr:w-4 pr:h-4" />
                          {__('Edit Configuration', 'prorank-seo')}
                        </button>
                        <button
                          className="pr:w-full pr:px-4 pr:py-2 pr:text-left pr:text-sm pr:text-gray-700 pr:hover:bg-gray-50 pr:flex pr:items-center pr:gap-2"
                          onClick={() => handleMenuAction('duplicate', schema)}
                        >
                          <DocumentDuplicateIcon className="pr:w-4 pr:h-4" />
                          {__('Duplicate', 'prorank-seo')}
                        </button>
                        <button
                          className="pr:w-full pr:px-4 pr:py-2 pr:text-left pr:text-sm pr:text-gray-700 pr:hover:bg-gray-50 pr:flex pr:items-center pr:gap-2"
                          onClick={() => handleMenuAction('export', schema)}
                        >
                          <ArrowDownTrayIcon className="pr:w-4 pr:h-4" />
                          {__('Export', 'prorank-seo')}
                        </button>
                        <hr className="pr:my-1 pr:border-gray-200" />
                        <button
                          className="pr:w-full pr:px-4 pr:py-2 pr:text-left pr:text-sm pr:text-error-600 pr:hover:bg-error-50 pr:flex pr:items-center pr:gap-2"
                          onClick={() => handleMenuAction('delete', schema)}
                        >
                          <TrashIcon className="pr:w-4 pr:h-4" />
                          {__('Delete', 'prorank-seo')}
                        </button>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </Card>
          ))}
        </div>
      )}

      {/* Footer Info */}
      <Alert variant="info">
        <div>
          <p className="pr:font-medium pr:mb-1">
            {__('Pro Tip:', 'prorank-seo')}
          </p>
          <p>
            {__('Schema configurations are applied in priority order. Higher priority schemas override lower ones when multiple schemas target the same content.', 'prorank-seo')}
          </p>
        </div>
      </Alert>

      {/* Click outside to close menu */}
      {showMenu && (
        <div
          className="pr:fixed pr:inset-0 pr:z-[9]"
          onClick={() => setShowMenu(null)}
        />
      )}
    </div>
  );
};

export default SchemaLibrary;
