import React from 'react';
import { Check, X, Minus, Loader2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import {
  usePublicPlans,
  PublicPlanVersion,
  getPlanFeatureValue,
  formatLimit,
} from '../../hooks/usePublicPlans';

// Feature categories for the comparison table
const FEATURE_CATEGORIES = [
  {
    key: 'limits',
    features: [
      { code: 'max_users', label: 'Team members' },
      { code: 'max_resources', label: 'Resources' },
      { code: 'max_locations', label: 'Locations' },
      { code: 'max_services', label: 'Services' },
      { code: 'max_customers', label: 'Customers' },
      { code: 'max_appointments_per_month', label: 'Appointments/month' },
    ],
  },
  {
    key: 'communication',
    features: [
      { code: 'email_enabled', label: 'Email notifications' },
      { code: 'max_email_per_month', label: 'Emails/month' },
      { code: 'sms_enabled', label: 'SMS reminders' },
      { code: 'max_sms_per_month', label: 'SMS/month' },
      { code: 'masked_calling_enabled', label: 'Masked calling' },
    ],
  },
  {
    key: 'booking',
    features: [
      { code: 'online_booking', label: 'Online booking' },
      { code: 'recurring_appointments', label: 'Recurring appointments' },
      { code: 'payment_processing', label: 'Accept payments' },
      { code: 'mobile_app_access', label: 'Mobile app' },
    ],
  },
  {
    key: 'integrations',
    features: [
      { code: 'integrations_enabled', label: 'Third-party integrations' },
      { code: 'api_access', label: 'API access' },
      { code: 'max_api_calls_per_day', label: 'API calls/day' },
    ],
  },
  {
    key: 'branding',
    features: [
      { code: 'custom_domain', label: 'Custom domain' },
      { code: 'custom_branding', label: 'Custom branding' },
      { code: 'remove_branding', label: 'Remove "Powered by"' },
      { code: 'white_label', label: 'White label' },
    ],
  },
  {
    key: 'enterprise',
    features: [
      { code: 'multi_location', label: 'Multi-location management' },
      { code: 'team_permissions', label: 'Team permissions' },
      { code: 'audit_logs', label: 'Audit logs' },
      { code: 'advanced_reporting', label: 'Advanced analytics' },
    ],
  },
  {
    key: 'support',
    features: [
      { code: 'priority_support', label: 'Priority support' },
      { code: 'dedicated_account_manager', label: 'Dedicated account manager' },
      { code: 'sla_guarantee', label: 'SLA guarantee' },
    ],
  },
  {
    key: 'storage',
    features: [
      { code: 'max_storage_mb', label: 'File storage' },
    ],
  },
];

interface FeatureComparisonTableProps {
  className?: string;
}

const FeatureComparisonTable: React.FC<FeatureComparisonTableProps> = ({
  className = '',
}) => {
  const { t } = useTranslation();
  const { data: plans, isLoading, error } = usePublicPlans();

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="w-8 h-8 animate-spin text-brand-600" />
      </div>
    );
  }

  if (error || !plans || plans.length === 0) {
    return null;
  }

  // Sort plans by display_order
  const sortedPlans = [...plans].sort(
    (a, b) => a.plan.display_order - b.plan.display_order
  );

  return (
    <div className={`overflow-x-auto ${className}`}>
      <table className="w-full min-w-[800px]">
        {/* Header */}
        <thead>
          <tr>
            <th className="text-left py-4 px-4 text-sm font-medium text-gray-500 dark:text-gray-400 border-b border-gray-200 dark:border-gray-700 w-64">
              {t('marketing.pricing.featureComparison.features', 'Features')}
            </th>
            {sortedPlans.map((planVersion) => (
              <th
                key={planVersion.id}
                className={`text-center py-4 px-4 text-sm font-semibold border-b border-gray-200 dark:border-gray-700 ${
                  planVersion.is_most_popular
                    ? 'text-brand-600 dark:text-brand-400 bg-brand-50 dark:bg-brand-900/20'
                    : 'text-gray-900 dark:text-white'
                }`}
              >
                {planVersion.plan.name}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {FEATURE_CATEGORIES.map((category) => (
            <React.Fragment key={category.key}>
              {/* Category Header */}
              <tr>
                <td
                  colSpan={sortedPlans.length + 1}
                  className="py-3 px-4 text-xs font-semibold uppercase tracking-wider text-gray-500 dark:text-gray-400 bg-gray-50 dark:bg-gray-800/50"
                >
                  {t(
                    `marketing.pricing.featureComparison.categories.${category.key}`,
                    category.key.charAt(0).toUpperCase() + category.key.slice(1)
                  )}
                </td>
              </tr>
              {/* Features */}
              {category.features.map((feature) => (
                <tr
                  key={feature.code}
                  className="border-b border-gray-100 dark:border-gray-800"
                >
                  <td className="py-3 px-4 text-sm text-gray-700 dark:text-gray-300">
                    {t(
                      `marketing.pricing.featureComparison.features.${feature.code}`,
                      feature.label
                    )}
                  </td>
                  {sortedPlans.map((planVersion) => (
                    <td
                      key={`${planVersion.id}-${feature.code}`}
                      className={`py-3 px-4 text-center ${
                        planVersion.is_most_popular
                          ? 'bg-brand-50/50 dark:bg-brand-900/10'
                          : ''
                      }`}
                    >
                      <FeatureValue
                        planVersion={planVersion}
                        featureCode={feature.code}
                      />
                    </td>
                  ))}
                </tr>
              ))}
            </React.Fragment>
          ))}
        </tbody>
      </table>
    </div>
  );
};

interface FeatureValueProps {
  planVersion: PublicPlanVersion;
  featureCode: string;
}

const FeatureValue: React.FC<FeatureValueProps> = ({
  planVersion,
  featureCode,
}) => {
  const value = getPlanFeatureValue(planVersion, featureCode);

  // Handle null/undefined - feature not set
  if (value === null || value === undefined) {
    return (
      <X className="w-5 h-5 text-gray-300 dark:text-gray-600 mx-auto" />
    );
  }

  // Boolean feature
  if (typeof value === 'boolean') {
    return value ? (
      <Check className="w-5 h-5 text-green-500 mx-auto" />
    ) : (
      <X className="w-5 h-5 text-gray-300 dark:text-gray-600 mx-auto" />
    );
  }

  // Integer feature (limit)
  if (typeof value === 'number') {
    // Special handling for storage (convert MB to GB if > 1000)
    if (featureCode === 'max_storage_mb') {
      if (value === 0) {
        return (
          <span className="text-sm font-medium text-gray-900 dark:text-white">
            Unlimited
          </span>
        );
      }
      if (value >= 1000) {
        return (
          <span className="text-sm font-medium text-gray-900 dark:text-white">
            {(value / 1000).toFixed(0)} GB
          </span>
        );
      }
      return (
        <span className="text-sm font-medium text-gray-900 dark:text-white">
          {value} MB
        </span>
      );
    }

    // Regular limit display
    return (
      <span className="text-sm font-medium text-gray-900 dark:text-white">
        {formatLimit(value)}
      </span>
    );
  }

  // Fallback
  return <Minus className="w-5 h-5 text-gray-300 dark:text-gray-600 mx-auto" />;
};

export default FeatureComparisonTable;
