// app/components/admin/packages/PackagesTable.tsx
'use client';

import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
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';
import { useRouter } from 'next/navigation';

interface PackageWebsite {
  id: string;
  website_id: string;
  website_name: string;
  website_url: string;
  website_da: number;
}

interface Package extends BaseTableItem {
  id: string;
  name: string;
  slug: string;
  description: string;
  package_type: 'standard' | 'special_niche' | 'custom';
  base_price: string;
  sale_price: string | null;
  features: string[];
  status: 'active' | 'inactive';
  is_popular: boolean;
  is_featured: boolean;
  websites: PackageWebsite[];
  created_at: string;
  updated_at: string;
}

interface PackagesTableProps {
  initialData?: {
    packages: Package[];
    pagination: PaginationData;
  };
}

export default function PackagesTable({ initialData }: PackagesTableProps) {
  const [packages, setPackages] = useState<Package[]>(initialData?.packages || []);
  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 router = useRouter();

  // Check permissions
  const canCreatePackage = hasPermission(PERMISSIONS.PACKAGES_CREATE);
  const canEditPackage = hasPermission(PERMISSIONS.PACKAGES_UPDATE);
  const canDeletePackage = hasPermission(PERMISSIONS.PACKAGES_DELETE);
  const canToggleStatus = hasPermission(PERMISSIONS.PACKAGES_UPDATE);

  // 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' }
      ]
    },
    {
      key: 'type',
      label: 'Package Type',
      type: 'select',
      options: [
        { value: 'standard', label: 'Standard' },
        { value: 'special_niche', label: 'Special Niche' },
        { value: 'custom', label: 'Custom' }
      ]
    }
  ];

  // Fetch packages with filters and pagination
  const fetchPackages = 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/packages?${params}`);
      const data = await response.json();

      if (response.ok) {
        setPackages(data.packages);
        setPagination(data.pagination);
      } else {
        if (response.status === 403) {
          toast.error('You do not have permission to view packages');
        } else {
          toast.error(data.error || 'Failed to fetch packages');
        }
      }
    } catch (error) {
      toast.error('Failed to fetch packages');
      console.error(error);
    } finally {
      setLoading(false);
    }
  }, [filters, pagination.limit]);

  // Handle filter changes
  const handleFilterChange = (newFilters: FilterValues) => {
    setFilters(newFilters);
    fetchPackages(1, newFilters);
  };

  // Handle page change
  const handlePageChange = (page: number) => {
    fetchPackages(page);
  };

  // Handle package status toggle
  const togglePackageStatus = async (packageId: string, currentStatus: string) => {
    if (!canToggleStatus) {
      toast.error('You do not have permission to update package status');
      return;
    }

    try {
      const response = await fetch(`/api/backend/admin/packages/${packageId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          status: currentStatus === 'active' ? 'inactive' : 'active'
        }),
      });

      const data = await response.json();

      if (response.ok) {
        toast.success(`Package ${currentStatus === 'active' ? 'deactivated' : 'activated'} successfully`);
        fetchPackages(pagination.page);
      } else {
        toast.error(data.error || 'Failed to update package status');
      }
    } catch (error) {
      toast.error('Failed to update package status');
      console.error(error);
    }
  };

  // Handle package deletion
  const handleDeleteClick = (pkg: Package) => {
    if (!canDeletePackage) {
      toast.error('You do not have permission to delete packages');
      return;
    }

    showAlert({
      title: 'Delete Package',
      message: `Are you sure you want to delete "${pkg.name}"? This action cannot be undone.`,
      confirmText: 'Delete Package',
      cancelText: 'Cancel',
      onConfirm: () => deletePackage(pkg.id),
    });
  };

  const handleEditPage = (packageId: string) => {
    if (!canEditPackage) {
      toast.error('You do not have permission to edit packages');
      return;
    }
    router.push(`/admin/dashboard/packages/edit/${packageId}`);
  };

  const deletePackage = async (packageId: string) => {
    try {
      const response = await fetch(`/api/backend/admin/packages/${packageId}`, {
        method: 'DELETE',
      });

      const data = await response.json();

      if (response.ok) {
        toast.success('Package deleted successfully');
        fetchPackages(pagination.page);
      } else {
        toast.error(data.error || 'Failed to delete package');
      }
    } catch (error) {
      toast.error('Failed to delete package');
      console.error(error);
    }
  };

  // Helper functions for rendering
  const getPackageTypeBadge = (type: string) => {
    const typeConfig = {
      standard: { bg: 'bg-var-primary-muted', text: 'text-var-primary-text', label: 'Standard' },
      special_niche: { bg: 'bg-var-info-bg', text: 'text-var-info-text', label: 'Special Niche' },
      custom: { bg: 'bg-var-warning-bg', text: 'text-var-warning-text', label: 'Custom' }
    };
    
    const config = typeConfig[type as keyof typeof typeConfig] || typeConfig.standard;
    return (
      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${config.bg} ${config.text}`}>
        {config.label}
      </span>
    );
  };

  const getPriceDisplay = (pkg: Package) => {
    const basePrice = parseFloat(pkg.base_price);
    if (pkg.sale_price) {
      const salePrice = parseFloat(pkg.sale_price);
      return (
        <div className="flex flex-col">
          <div className="flex items-center">
            <span className="text-sm font-bold text-var-success">${salePrice.toFixed(2)}</span>
            <span className="ml-2 text-xs text-var-text-muted line-through">${basePrice.toFixed(2)}</span>
          </div>
        </div>
      );
    }
    return <span className="text-sm font-medium text-var-text">${basePrice.toFixed(2)}</span>;
  };

  const getStatusBadge = (status: string) => {
    return status === 'active' ? (
      <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-var-success-bg text-var-success-text">
        Active
      </span>
    ) : (
      <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-var-danger-bg text-var-danger-text">
        Inactive
      </span>
    );
  };

  // Table columns configuration
  const columns: TableColumn<Package>[] = [
    {
      key: 'package',
      label: 'Package',
      render: (pkg) => (
        <div className="flex items-center">
          <div className={`w-1 h-10 rounded-full ${pkg.is_popular ? 'bg-var-accent-orange' : pkg.is_featured ? 'bg-var-accent-purple' : 'border-var-border'}`}></div>
          <div className="ml-4">
            <div className="flex items-center">
              <div className="text-sm font-medium text-var-text">{pkg.name}</div>
              {pkg.is_featured && (
                <span className="ml-2 inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-var-info-bg text-var-info-text">
                  Featured
                </span>
              )}
              {pkg.is_popular && (
                <span className="ml-2 inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-var-warning-bg text-var-warning-text">
                  Popular
                </span>
              )}
            </div>
            <code className="text-xs font-mono text-var-text-muted">/{pkg.slug}</code>
            <div className="mt-1 text-xs text-var-text-muted line-clamp-1" dangerouslySetInnerHTML={{ __html: pkg.description?.substring(0, 60) + (pkg.description?.length > 60 ? '...' : '') }} />
          </div>
        </div>
      )
    },
    {
      key: 'type_price',
      label: 'Type & Price',
      render: (pkg) => (
        <div className="space-y-2">
          {getPackageTypeBadge(pkg.package_type)}
          {getPriceDisplay(pkg)}
        </div>
      )
    },
    {
      key: 'websites',
      label: 'Websites',
      render: (pkg) => (
        <div>
          <div className="flex -space-x-2">
            {pkg.websites?.slice(0, 3).map((website) => (
              <div key={website.id} className="relative" title={`${website.website_name} (DA: ${website.website_da})`}>
                <div className="w-8 h-8 bg-var-primary rounded-full border-2 border-var-surface flex items-center justify-center text-white text-xs font-bold">
                  {website.website_name?.[0] || '?'}
                </div>
                {website.website_da >= 70 && (
                  <div className="absolute -top-1 -right-1 w-4 h-4 bg-var-accent-orange rounded-full border-2 border-var-surface flex items-center justify-center">
                    <svg className="w-2 h-2 text-white" fill="currentColor" viewBox="0 0 20 20">
                      <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                    </svg>
                  </div>
                )}
              </div>
            ))}
            {pkg.websites && pkg.websites.length > 3 && (
              <div className="w-8 h-8 bg-var-surface-hover rounded-full border-2 border-var-surface flex items-center justify-center text-var-text-muted text-xs font-medium">
                +{pkg.websites.length - 3}
              </div>
            )}
            {(!pkg.websites || pkg.websites.length === 0) && (
              <span className="text-xs text-var-text-muted italic">No websites</span>
            )}
          </div>
          <div className="mt-1 text-xs text-var-text-muted">
            {pkg.websites?.length || 0} website{pkg.websites?.length !== 1 ? 's' : ''}
          </div>
        </div>
      )
    },
    {
      key: 'features',
      label: 'Features',
      render: (pkg) => (
        <div className="flex flex-wrap gap-1 max-w-xs">
          {pkg.features?.slice(0, 3).map((feature, idx) => (
            <span key={idx} className="inline-block px-2 py-1 bg-var-surface-hover text-var-text-secondary text-xs rounded-lg">
              {feature}
            </span>
          ))}
          {pkg.features && pkg.features.length > 3 && (
            <span className="inline-block px-2 py-1 bg-var-surface-raised text-var-text-muted text-xs rounded-lg">
              +{pkg.features.length - 3} more
            </span>
          )}
          {(!pkg.features || pkg.features.length === 0) && (
            <span className="text-xs text-var-text-muted italic">No features</span>
          )}
        </div>
      )
    },
    {
      key: 'status',
      label: 'Status',
      render: (pkg) => getStatusBadge(pkg.status)
    },
    {
      key: 'created_at',
      label: 'Created',
      render: (pkg) => (
        <span className="text-sm text-var-text-muted">
          {new Date(pkg.created_at).toLocaleDateString()}
        </span>
      )
    }
  ];

  // Table actions configuration
  const actions: TableAction<Package>[] = [
    // Edit Button
    ...(canEditPackage ? [{
      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: (pkg: Package) => handleEditPage(pkg.id),
      condition: () => canEditPackage,
      className: 'text-var-primary hover:text-var-primary-hover hover:bg-var-primary-muted',
      title: 'Edit package'
    }] : []),
    
    // Status Toggle Button
    ...(canToggleStatus ? [{
      key: 'toggle-status',
      icon: (pkg: Package) => (
        pkg.status === '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: (pkg: Package) => togglePackageStatus(pkg.id, pkg.status),
      condition: () => canToggleStatus,
      className: (pkg: Package) => 
        pkg.status === '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: (pkg: Package) => 
        pkg.status === 'active' ? 'Deactivate package' : 'Activate package'
    }] : []),

    // Delete Button
    ...(canDeletePackage ? [{
      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: (pkg: Package) => handleDeleteClick(pkg),
      condition: () => canDeletePackage,
      className: 'text-var-danger hover:text-var-danger-text hover:bg-var-danger-bg',
      title: 'Delete package'
    }] : [])
  ];

  useEffect(() => {
    if (!initialData) {
      fetchPackages();
    }
  }, [fetchPackages, 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">Package Management</h2>
            <p className="text-sm text-var-text-secondary mt-1">
              {pagination.total} package{pagination.total !== 1 ? 's' : ''} found
            </p>
          </div>
          
          <div className="flex items-center space-x-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>

            {canCreatePackage && (
              <Link
                href="/admin/dashboard/packages/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 Package
              </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={packages}
        columns={columns}
        actions={actions}
        loading={loading}
        emptyMessage="No packages found"
        emptyDescription="Try adjusting your search or filters"
        onCreateNew={canCreatePackage ? () => {
          router.push('/admin/dashboard/packages/new');
        } : undefined}
        createNewLabel="Create your first package →"
        keyExtractor={(pkg) => pkg.id}
      />

      {/* Pagination */}
      <TablePagination
        pagination={pagination}
        onPageChange={handlePageChange}
      />
    </div>
  );
}