/**
 * Export Button Component
 * Shows in header with dropdown for CSV/XLSX
 */

import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Download, FileSpreadsheet, FileText, Lock } from 'lucide-react';
import { useExportVariations } from '../../hooks/useExport';
import { useLicenseInfo } from '../../hooks/useLicense';
import ProBadge from '../ui/ProBadge';
import type { ExportFormat } from '../../types/export';

interface Props {
  selectedIds: number[];
}

export default function ExportButton({ selectedIds }: Props) {
  const { t } = useTranslation();
  const [showDropdown, setShowDropdown] = useState(false);
  const exportMutation = useExportVariations();
  const { data: licenseInfo } = useLicenseInfo();

  const handleExport = async (format: ExportFormat, allVariations: boolean = false) => {
    setShowDropdown(false);
    
    await exportMutation.mutateAsync({
      format,
      variation_ids: allVariations ? undefined : selectedIds,
      all_variations: allVariations,
    });
  };

  const hasSelection = selectedIds.length > 0;
  // ✅ NULL SAFETY: Ensure isFree is boolean
  const isFree = licenseInfo?.tier === 'free';
  // ✅ NULL SAFETY: xlsxLocked calculation with optional chaining
  const xlsxLocked = isFree && !(licenseInfo?.features?.xlsx_export ?? false);
  const csvLimit = licenseInfo?.limits?.csv_export_limit ?? 200;

  return (
    <div className="relative">
      <button
        onClick={() => setShowDropdown(!showDropdown)}
        disabled={exportMutation.isPending}
        className="flex items-center gap-2 px-4 py-2 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed"
      >
        <Download className="w-4 h-4" />
        <span className="font-medium text-sm">{t('export.button')}</span>
      </button>

      {showDropdown && (
        <>
          {/* Backdrop */}
          <div 
            className="fixed inset-0 z-10" 
            onClick={() => setShowDropdown(false)}
          />
          
          {/* Dropdown Menu */}
          <div className="absolute right-0 mt-2 w-64 bg-white rounded-lg shadow-lg border border-gray-200 z-20">
            <div className="p-2">
              <div className="text-xs font-semibold text-gray-500 uppercase px-3 py-2">
                {t('export.format')}
              </div>
              
              {/* CSV Options */}
              <div className="space-y-1">
                {hasSelection && (
                  <button
                    onClick={() => handleExport('csv', false)}
                    disabled={exportMutation.isPending}
                    className="w-full flex items-center gap-3 px-3 py-2 rounded-md hover:bg-gray-100 transition text-left"
                  >
                    <FileText className="w-5 h-5 text-green-600 shrink-0" />
                    <div className="flex-1 min-w-0">
                      <div className="text-sm font-medium">{t('export.csv_selected')}</div>
                      <div className="text-xs text-gray-500">
                        {selectedIds.length} {t('export.variations')}
                      </div>
                    </div>
                  </button>
                )}
                
                <button
                  onClick={() => handleExport('csv', true)}
                  disabled={exportMutation.isPending}
                  className="w-full flex items-center gap-3 px-3 py-2 rounded-md hover:bg-gray-100 transition text-left"
                >
                  <FileText className="w-5 h-5 text-green-600 shrink-0" />
                  <div className="flex-1 min-w-0">
                    <div className="text-sm font-medium">{t('export.csv_all')}</div>
                    <div className="text-xs text-gray-500">
                      {isFree ? t('export.csv_free_limit', { limit: csvLimit }) : t('export.all_variations')}
                    </div>
                  </div>
                </button>
              </div>

              <div className="h-px bg-gray-200 my-2" />

              {/* XLSX Options - PRO Only */}
              <div className="space-y-1">
                {hasSelection && (
                  <button
                    onClick={() => !xlsxLocked && handleExport('xlsx', false)}
                    disabled={exportMutation.isPending || xlsxLocked}
                    className={`
                      w-full flex items-center gap-3 px-3 py-2 rounded-md transition text-left
                      ${xlsxLocked 
                        ? 'bg-gray-50 cursor-not-allowed opacity-60' 
                        : 'hover:bg-gray-100'
                      }
                    `}
                    title={xlsxLocked ? t('export.xlsx_locked_tooltip') : ''}
                  >
                    {xlsxLocked ? (
                      <Lock className="w-5 h-5 text-gray-400 shrink-0" />
                    ) : (
                      <FileSpreadsheet className="w-5 h-5 text-blue-600 shrink-0" />
                    )}
                    <div className="flex-1 min-w-0">
                      <div className="text-sm font-medium flex items-center gap-2">
                        <span>{t('export.xlsx_selected')}</span>
                        {xlsxLocked && <ProBadge variant="inline" size="sm" />}
                      </div>
                      <div className="text-xs text-gray-500">
                        {selectedIds.length} {t('export.variations')}
                      </div>
                    </div>
                  </button>
                )}
                
                <button
                  onClick={() => !xlsxLocked && handleExport('xlsx', true)}
                  disabled={exportMutation.isPending || xlsxLocked}
                  className={`
                    w-full flex items-center gap-3 px-3 py-2 rounded-md transition text-left
                    ${xlsxLocked 
                      ? 'bg-gray-50 cursor-not-allowed opacity-60' 
                      : 'hover:bg-gray-100'
                    }
                  `}
                  title={xlsxLocked ? t('export.xlsx_locked_tooltip') : ''}
                >
                  {xlsxLocked ? (
                    <Lock className="w-5 h-5 text-gray-400 shrink-0" />
                  ) : (
                    <FileSpreadsheet className="w-5 h-5 text-blue-600 shrink-0" />
                  )}
                  <div className="flex-1 min-w-0">
                    <div className="text-sm font-medium flex items-center gap-2">
                      <span>{t('export.xlsx_all')}</span>
                      {xlsxLocked && <ProBadge variant="inline" size="sm" />}
                    </div>
                    <div className="text-xs text-gray-500">{t('export.all_variations')}</div>
                  </div>
                </button>
              </div>
            </div>
          </div>
        </>
      )}
    </div>
  );
}
