// app/components/admin/redirects/RedirectsTable.tsx
'use client';

import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
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 Redirect extends BaseTableItem {
  id: string;
  source_path: string;
  destination_path: string;
  redirect_type: 301 | 302;
  is_active: boolean;
  created_at: string;
  updated_at: string;
}

interface RedirectsTableProps {
  initialData?: {
    redirects: Redirect[];
    pagination: PaginationData;
  } | null;
}

function RedirectTypeBadge({ type }: { type: 301 | 302 }) {
  switch (type) {
    case 301:
      return (
        <span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-var-warning-bg text-var-warning-text border border-var-warning-border">
          301 Permanent
        </span>
      );
    case 302:
      return (
        <span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-var-info-bg text-var-info-text border border-var-info-border">
          302 Temporary
        </span>
      );
    default:
      return null;
  }
}

export default function RedirectsTable({ initialData }: RedirectsTableProps) {
  const router = useRouter();
  const [redirects, setRedirects] = useState<Redirect[]>(initialData?.redirects || []);
  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: '',
    type: ''
  });

  const { hasPermission } = usePermissions();
  const { showAlert } = useAlert();

  const canCreateRedirect = hasPermission(PERMISSIONS.REDIRECTS_CREATE);
  const canEditRedirect = hasPermission(PERMISSIONS.REDIRECTS_UPDATE);
  const canDeleteRedirect = hasPermission(PERMISSIONS.REDIRECTS_DELETE);
  const canToggleStatus = hasPermission(PERMISSIONS.REDIRECTS_UPDATE);
  const canBulkDelete = hasPermission(PERMISSIONS.REDIRECTS_BULK_DELETE);

  const filterConfigs: FilterConfig[] = [
    {
      key: 'search',
      label: 'Search',
      type: 'search',
      placeholder: 'Search by source or destination...'
    },
    {
      key: 'status',
      label: 'Status',
      type: 'select',
      options: [
        { value: 'active', label: 'Active' },
        { value: 'inactive', label: 'Inactive' }
      ]
    },
    {
      key: 'type',
      label: 'Redirect Type',
      type: 'select',
      options: [
        { value: '301', label: '301 - Permanent' },
        { value: '302', label: '302 - Temporary' }
      ]
    }
  ];

  const fetchRedirects = 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/redirects?${params}`);
      const data = await response.json();

      if (response.ok) {
        setRedirects(data.redirects);
        setPagination(data.pagination);
      } else {
        if (response.status === 403) {
          toast.error('You do not have permission to view redirects');
        } else {
          toast.error(data.error || 'Failed to fetch redirects');
        }
      }
    } catch {
      toast.error('Failed to fetch redirects');
    } finally {
      setLoading(false);
    }
  }, [filters, pagination.limit]);

  const handleFilterChange = (newFilters: FilterValues) => {
    setFilters(newFilters);
    fetchRedirects(1, newFilters);
  };

  const handlePageChange = (page: number) => {
    fetchRedirects(page);
  };

  const toggleRedirectStatus = async (redirectId: string, currentStatus: boolean) => {
    if (!canToggleStatus) {
      toast.error('You do not have permission to update redirect status');
      return;
    }

    try {
      const response = await fetch(`/api/backend/admin/redirects/${redirectId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ is_active: !currentStatus }),
      });

      const data = await response.json();

      if (response.ok) {
        toast.success(data.message || `Redirect ${!currentStatus ? 'activated' : 'deactivated'} successfully`);
        fetchRedirects(pagination.page);
      } else {
        if (response.status === 403) {
          toast.error('You do not have permission to update redirects');
        } else {
          toast.error(data.error || 'Failed to update redirect status');
        }
      }
    } catch {
      toast.error('Failed to update redirect status');
    }
  };

  const handleDeleteClick = (redirect: Redirect) => {
    if (!canDeleteRedirect) {
      toast.error('You do not have permission to delete redirects');
      return;
    }

    showAlert({
      title: 'Delete Redirect',
      message: `Are you sure you want to delete the redirect for "${redirect.source_path}"? This action cannot be undone.`,
      confirmText: 'Delete Redirect',
      cancelText: 'Cancel',
      onConfirm: () => deleteRedirect(redirect.id),
    });
  };

  const deleteRedirect = async (redirectId: string) => {
    try {
      const response = await fetch(`/api/backend/admin/redirects/${redirectId}`, {
        method: 'DELETE',
      });

      const data = await response.json();

      if (response.ok) {
        toast.success(data.message || 'Redirect deleted successfully');
        fetchRedirects(pagination.page);
      } else {
        if (response.status === 403) {
          toast.error('You do not have permission to delete redirects');
        } else {
          toast.error(data.error || 'Failed to delete redirect');
        }
      }
    } catch {
      toast.error('Failed to delete redirect');
    }
  };

  const handleBulkDelete = async (selectedIds: string[]) => {
    try {
      const response = await fetch('/api/backend/admin/redirects/bulk-delete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids: selectedIds }),
      });

      const data = await response.json();

      if (response.ok) {
        if (data.notFoundIds && data.notFoundIds.length > 0) {
          toast.success(
            `${data.deletedCount} redirect${data.deletedCount !== 1 ? 's' : ''} deleted, ${data.notFoundIds.length} not found`
          );
        } else if (data.deletedCount === 1) {
          toast.success(data.message);
        } else {
          toast.success(data.message);
        }
        fetchRedirects(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 redirects',
      confirmMessage: (count: number) => {
        return `Are you sure you want to delete ${count} redirect${count !== 1 ? 's' : ''}? This action cannot be undone.`;
      },
      onClick: handleBulkDelete,
    }] : []),
  ];

  const columns: TableColumn<Redirect>[] = [
    {
      key: 'source',
      label: 'Source Path',
      render: (redirect) => (
        <code className="text-sm font-mono text-var-text bg-var-surface-hover px-2 py-1 rounded truncate block max-w-55">
          {redirect.source_path}
        </code>
      )
    },
    {
      key: 'destination',
      label: 'Destination Path',
      render: (redirect) => (
        <div className="flex items-center gap-1.5 max-w-55">
          <svg className="w-3.5 h-3.5 text-var-text-muted shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 8l4 4m0 0l-4 4m4-4H3" />
          </svg>
          <code className="text-sm font-mono text-var-primary bg-var-primary-muted px-2 py-1 rounded truncate block">
            {redirect.destination_path}
          </code>
        </div>
      )
    },
    {
      key: 'type',
      label: 'Type',
      render: (redirect) => <RedirectTypeBadge type={redirect.redirect_type} />
    },
    {
      key: 'status',
      label: 'Status',
      render: (redirect) => (
        <div className="flex items-center space-x-2">
          <div className={`w-2 h-2 rounded-full ${redirect.is_active ? 'bg-var-success' : 'bg-var-danger'}`} />
          <span className={`text-sm font-medium ${redirect.is_active ? 'text-var-success-text' : 'text-var-danger-text'}`}>
            {redirect.is_active ? 'Active' : 'Inactive'}
          </span>
        </div>
      )
    },
    {
      key: 'created_at',
      label: 'Created',
      render: (redirect) => (
        <span className="text-sm text-var-text-muted">
          {new Date(redirect.created_at).toLocaleDateString()}
        </span>
      )
    }
  ];

  const actions: TableAction<Redirect>[] = [
    ...(canEditRedirect ? [{
      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: (redirect: Redirect) => {
        router.push(`/admin/dashboard/redirects/edit/${redirect.id}`);
      },
      className: 'text-var-primary hover:text-var-primary-hover hover:bg-var-primary-muted',
      title: 'Edit redirect'
    }] : []),

    ...(canToggleStatus ? [{
      key: 'toggle-status',
      icon: (redirect: Redirect) => (
        redirect.is_active ? (
          <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: (redirect: Redirect) => toggleRedirectStatus(redirect.id, redirect.is_active),
      className: (redirect: Redirect) => 
        redirect.is_active
          ? '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: (redirect: Redirect) => 
        redirect.is_active ? 'Deactivate redirect' : 'Activate redirect'
    }] : []),

    ...(canDeleteRedirect ? [{
      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: (redirect: Redirect) => handleDeleteClick(redirect),
      className: 'text-var-danger hover:text-var-danger-text hover:bg-var-danger-bg',
      title: 'Delete redirect'
    }] : [])
  ];

  useEffect(() => {
    if (!initialData) fetchRedirects();
  }, [fetchRedirects, initialData]);

  const toggleFilters = () => setFiltersVisible(!filtersVisible);

  return (
    <div className="bg-var-surface rounded-2xl shadow-var-card border border-var-border overflow-hidden">
      <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">Redirect Management</h2>
            <p className="text-sm text-var-text-secondary mt-1">
              {pagination.total} redirect{pagination.total !== 1 ? 's' : ''} found
            </p>
          </div>
          
          <div className="flex items-center space-x-3">
            <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>

            {canCreateRedirect && (
              <Link
                href="/admin/dashboard/redirects/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 Redirect
              </Link>
            )}
          </div>
        </div>

        {filtersVisible && (
          <div className="mt-4">
            <TableFilters
              filters={filterConfigs}
              onFilterChange={handleFilterChange}
              initialValues={filters}
              className="mt-0"
            />
          </div>
        )}
      </div>

      <DataTable
        data={redirects}
        columns={columns}
        actions={actions}
        bulkActions={bulkActions}
        loading={loading}
        emptyMessage="No redirects found"
        emptyDescription="Try adjusting your search or filters"
        onCreateNew={canCreateRedirect ? () => {
          router.push('/admin/dashboard/redirects/new');
        } : undefined}
        createNewLabel="Create your first redirect →"
        keyExtractor={(redirect) => redirect.id}
      />

      <TablePagination pagination={pagination} onPageChange={handlePageChange} />
    </div>
  );
}