// app/components/admin/authors/AuthorsTable.tsx
'use client';

import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import toast from 'react-hot-toast';
import { usePermissions } from '@/hooks/usePermissions';
import { PERMISSIONS } from '@/lib/permissions';
import { useAlert } from '@/contexts/AlertContext';
import DataTable from '@/app/components/admin/CommonComponents/DataTable';
import TablePagination from '@/app/components/admin/CommonComponents/TablePagination';
import TableFilters from '@/app/components/admin/CommonComponents/TableFilters';
import { BaseTableItem, FilterConfig, FilterValues, PaginationData, TableColumn, TableAction } from '@/types/admin-table';

interface Author extends BaseTableItem {
  id: string;
  full_name: string;
  slug: string;
  bio: string;
  profile_image: string;
  website: string;
  social_facebook: string;
  social_twitter: string;
  social_instagram: string;
  social_linkedin: string;
  status: boolean;
  created_at: string;
  updated_at: string;
}

interface AuthorsTableProps {
  initialData?: {
    authors: Author[];
    pagination: PaginationData;
  };
}

const SOCIAL_ICONS: Record<string, React.ReactNode> = {
  facebook: (
    <svg className="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 24 24">
      <path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z" />
    </svg>
  ),
  twitter: (
    <svg className="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 24 24">
      <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
    </svg>
  ),
  instagram: (
    <svg className="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 24 24">
      <path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z" />
    </svg>
  ),
  linkedin: (
    <svg className="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 24 24">
      <path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 01-2.063-2.065 2.064 2.064 0 112.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z" />
    </svg>
  ),
};

function SocialBadges({ author }: { author: Author }) {
  const links = [
    { key: 'facebook', url: author.social_facebook },
    { key: 'twitter', url: author.social_twitter },
    { key: 'instagram', url: author.social_instagram },
    { key: 'linkedin', url: author.social_linkedin },
  ].filter((l) => l.url);

  if (links.length === 0)
    return <span className="text-xs text-var-text-muted italic">None</span>;

  return (
    <div className="flex items-center gap-1">
      {links.map((l) => (
        <a
          key={l.key}
          href={l.url}
          target="_blank"
          rel="noopener noreferrer"
          className="p-1 rounded-md text-var-text-muted hover:text-var-primary hover:bg-var-primary-muted transition-colors duration-150"
          title={l.key}
          onClick={(e) => e.stopPropagation()}
        >
          {SOCIAL_ICONS[l.key]}
        </a>
      ))}
    </div>
  );
}

export default function AuthorsTable({ initialData }: AuthorsTableProps) {
  const router = useRouter();
  const [authors, setAuthors] = useState<Author[]>(initialData?.authors || []);
  const [loading, setLoading] = useState(false);
  const [filtersVisible, setFiltersVisible] = useState(false);
  const [pagination, setPagination] = useState<PaginationData>(
    initialData?.pagination || { page: 1, limit: 10, total: 0, pages: 0 }
  );
  const [filters, setFilters] = useState<FilterValues>({ 
    search: '', 
    status: '' 
  });

  const { hasPermission } = usePermissions();
  const { showAlert } = useAlert();

  const canCreate = hasPermission(PERMISSIONS.AUTHORS_CREATE);
  const canEdit = hasPermission(PERMISSIONS.AUTHORS_UPDATE);
  const canDelete = hasPermission(PERMISSIONS.AUTHORS_DELETE);
  const canToggle = hasPermission(PERMISSIONS.AUTHORS_UPDATE);
  const canBulkDelete = hasPermission(PERMISSIONS.AUTHORS_BULK_DELETE);

  // Filter configuration
  const filterConfigs: FilterConfig[] = [
    {
      key: 'search',
      label: 'Search',
      type: 'search',
      placeholder: 'Search by name or slug...'
    },
    {
      key: 'status',
      label: 'Status',
      type: 'select',
      options: [
        { value: 'active', label: 'Active' },
        { value: 'inactive', label: 'Inactive' }
      ]
    }
  ];

  const fetchAuthors = useCallback(
    async (page = 1, newFilters = filters) => {
      setLoading(true);
      try {
        const params = new URLSearchParams({
          page: page.toString(),
          limit: pagination.limit.toString(),
          ...newFilters,
        });

        const response = await fetch(`/api/backend/admin/authors?${params}`);
        const data = await response.json();

        if (response.ok) {
          setAuthors(data.authors);
          setPagination(data.pagination);
        } else {
          toast.error(
            response.status === 403
              ? 'You do not have permission to view authors'
              : data.error || 'Failed to fetch authors'
          );
        }
      } catch {
        toast.error('Failed to fetch authors');
      } finally {
        setLoading(false);
      }
    },
    [filters, pagination.limit]
  );

  // Handle filter changes
  const handleFilterChange = (newFilters: FilterValues) => {
    setFilters(newFilters);
    fetchAuthors(1, newFilters);
  };

  // Handle page change
  const handlePageChange = (page: number) => fetchAuthors(page);

  const toggleStatus = async (authorId: string, current: boolean) => {
    if (!canToggle) {
      toast.error('You do not have permission to update author status');
      return;
    }
    try {
      const response = await fetch(`/api/backend/admin/authors/${authorId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: !current }),
      });
      const data = await response.json();
      if (response.ok) {
        toast.success(
          `Author ${!current ? 'activated' : 'deactivated'} successfully`
        );
        fetchAuthors(pagination.page);
      } else {
        toast.error(data.error || 'Failed to update author status');
      }
    } catch {
      toast.error('Failed to update author status');
    }
  };

  const handleDeleteClick = (author: Author) => {
    if (!canDelete) {
      toast.error('You do not have permission to delete authors');
      return;
    }
    showAlert({
      title: 'Delete Author',
      message: `Are you sure you want to delete "${author.full_name}"? This action cannot be undone.`,
      confirmText: 'Delete Author',
      cancelText: 'Cancel',
      onConfirm: () => deleteAuthor(author.id),
    });
  };

  const deleteAuthor = async (authorId: string) => {
    try {
      const response = await fetch(`/api/backend/admin/authors/${authorId}`, {
        method: 'DELETE',
      });
      const data = await response.json();
      if (response.ok) {
        toast.success('Author deleted successfully');
        fetchAuthors(pagination.page);
      } else {
        toast.error(data.error || 'Failed to delete author');
      }
    } catch {
      toast.error('Failed to delete author');
    }
  };

  // ─── Bulk delete ────────────────────────────────────────────────────────────
  const handleBulkDelete = async (selectedIds: string[]) => {
    try {
      const response = await fetch('/api/backend/admin/authors/bulk-delete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids: selectedIds }),
      });

      const data = await response.json();

      if (response.ok) {
        toast.success(
          `${selectedIds.length} author${selectedIds.length !== 1 ? 's' : ''} deleted`
        );
        fetchAuthors(pagination.page);
      } else {
        toast.error(data.error || 'Bulk delete failed');
      }
    } catch {
      toast.error('Bulk delete failed');
    }
  };

  const bulkActions = [
    ...(canBulkDelete ? [{
      key: 'bulk-delete',
      label: 'Delete selected',
      icon: (
        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
            d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
        </svg>
      ),
      className: 'bg-var-danger-bg text-var-danger hover:bg-var-danger-bg',
      requiresConfirm: true,
      confirmTitle: 'Delete selected authors',
      confirmMessage: (count: number) =>
        `Are you sure you want to delete ${count} author${count !== 1 ? 's' : ''}? This action cannot be undone.`,
      onClick: handleBulkDelete,
    }] : []),
  ];
  // ────────────────────────────────────────────────────────────────────────────

  const getAvatar = (author: Author) => {
    if (author.profile_image) {
      return (
        <Image
          src={author.profile_image}
          alt={author.full_name}
          className="w-9 h-9 rounded-full object-cover border-2 border-var-surface shadow-var-card"
          width={36}
          height={36}
        />
      );
    }
    return (
      <div className="w-9 h-9 bg-var-primary rounded-full flex items-center justify-center text-white text-sm font-bold shadow-var-card">
        {author.full_name[0]?.toUpperCase()}
      </div>
    );
  };

  // Table columns configuration
  const columns: TableColumn<Author>[] = [
    {
      key: 'author',
      label: 'Author',
      render: (author) => (
        <div className="flex items-center gap-3">
          {getAvatar(author)}
          <div>
            <p className="text-sm font-medium text-var-text">
              {author.full_name}
            </p>
            <code className="text-xs font-mono text-var-text-muted bg-var-surface-hover px-1.5 py-0.5 rounded">
              /{author.slug}
            </code>
          </div>
        </div>
      )
    },
    {
      key: 'bio',
      label: 'Bio',
      render: (author) => (
        <p className="text-sm text-var-text-secondary max-w-50 truncate">
          {author.bio || (
            <span className="text-var-text-muted italic">No bio</span>
          )}
        </p>
      )
    },
    {
      key: 'social',
      label: 'Social',
      render: (author) => <SocialBadges author={author} />
    },
    {
      key: 'status',
      label: 'Status',
      render: (author) => (
        <div className="flex items-center space-x-2">
          <div
            className={`w-2 h-2 rounded-full ${
              author.status ? 'bg-var-success' : 'bg-var-danger'
            }`}
          />
          <span
            className={`text-sm font-medium ${
              author.status ? 'text-var-success-text' : 'text-var-danger-text'
            }`}
          >
            {author.status ? 'Active' : 'Inactive'}
          </span>
        </div>
      )
    },
    {
      key: 'created_at',
      label: 'Created',
      render: (author) => (
        <span className="text-sm text-var-text-muted">
          {new Date(author.created_at).toLocaleDateString()}
        </span>
      )
    }
  ];

  // Table actions configuration
  const actions: TableAction<Author>[] = [
    // Edit button
    ...(canEdit ? [{
      key: 'edit',
      icon: (
        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
        </svg>
      ),
      onClick: (author: Author) => {
        router.push(`/admin/dashboard/authors/edit/${author.id}`);
      },
      className: 'text-var-primary hover:text-var-primary-hover hover:bg-var-primary-muted',
      title: 'Edit author'
    }] : []),

    // Status Toggle Button
    ...(canToggle ? [{
      key: 'toggle-status',
      icon: (author: Author) => (
        author.status ? (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
        ) : (
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
        )
      ),
      onClick: (author: Author) => toggleStatus(author.id, author.status),
      className: (author: Author) => 
        author.status
          ? 'text-var-warning hover:text-var-warning-text hover:bg-var-warning-bg'
          : 'text-var-success hover:text-var-success-text hover:bg-var-success-bg',
      title: (author: Author) => 
        author.status ? 'Deactivate author' : 'Activate author'
    }] : []),

    // Delete button
    ...(canDelete ? [{
      key: 'delete',
      icon: (
        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
        </svg>
      ),
      onClick: (author: Author) => handleDeleteClick(author),
      className: 'text-var-danger hover:text-var-danger-text hover:bg-var-danger-bg',
      title: 'Delete author'
    }] : [])
  ];

  useEffect(() => {
    if (!initialData) fetchAuthors();
  }, [fetchAuthors, initialData]);

  const toggleFilters = () => {
    setFiltersVisible(!filtersVisible);
  };

  return (
    <div className="bg-var-surface rounded-2xl shadow-var-card border border-var-border overflow-hidden">
      {/* Header */}
      <div className="px-6 py-4 border-b border-var-border bg-var-surface-hover/50">
        <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between space-y-4 lg:space-y-0">
          <div>
            <h2 className="text-lg font-semibold text-var-text">
              Author Management
            </h2>
            <p className="text-sm text-var-text-secondary mt-1">
              {pagination.total} author{pagination.total !== 1 ? 's' : ''} found
            </p>
          </div>
          
          <div className="flex items-center gap-3">
            {/* Filter Toggle Button */}
            <button
              onClick={toggleFilters}
              className="inline-flex items-center px-3 py-2 bg-var-surface border border-var-border text-var-text-secondary font-medium rounded-xl hover:bg-var-surface-hover hover:text-var-text transition-all duration-200 shadow-var-button"
              title={filtersVisible ? "Hide filters" : "Show filters"}
            >
              <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
              </svg>
              {filtersVisible ? 'Hide Filters' : 'Show Filters'}
            </button>

            {canCreate && (
              <Link
                href="/admin/dashboard/authors/new"
                className="inline-flex items-center px-4 py-2 bg-var-primary text-white font-medium rounded-xl hover:bg-var-primary-hover transition-all duration-200 shadow-var-button hover:shadow-var-card"
              >
                <svg
                  className="w-4 h-4 mr-2"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M12 6v6m0 0v6m0-6h6m-6 0H6"
                  />
                </svg>
                Add Author
              </Link>
            )}
          </div>
        </div>

        {/* Filters - Conditionally rendered */}
        {filtersVisible && (
          <div className="mt-4">
            <TableFilters
              filters={filterConfigs}
              onFilterChange={handleFilterChange}
              initialValues={filters}
              className="mt-0"
            />
          </div>
        )}
      </div>

      {/* Table */}
      <DataTable
        data={authors}
        columns={columns}
        actions={actions}
        bulkActions={bulkActions}
        loading={loading}
        emptyMessage="No authors found"
        emptyDescription="Try adjusting your search or filters"
        onCreateNew={canCreate ? () => {
          router.push('/admin/dashboard/authors/new');
        } : undefined}
        createNewLabel="Create your first author →"
        keyExtractor={(author) => author.id}
      />

      {/* Pagination */}
      <TablePagination
        pagination={pagination}
        onPageChange={handlePageChange}
      />
    </div>
  );
}