'use client';

import { useToast } from './ToastProvider';
import { getResponseErrorTextWithRequestId } from '@/lib/api-client';

interface ExportButtonProps {
  linkId: string;
  period: string;
  disabled?: boolean;
  disabledReason?: string;
}

export default function ExportButton({ linkId, period, disabled = false, disabledReason }: ExportButtonProps) {
  const toast = useToast();

  const handleExport = async () => {
    if (disabled) {
      if (disabledReason) {
        toast.info(disabledReason);
      }
      return;
    }

    try {
      const response = await fetch(`/api/links/${linkId}/stats/export?period=${period}`);

      if (!response.ok) {
        throw new Error(await getResponseErrorTextWithRequestId(response, 'Ошибка экспорта'));
      }

      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `stats-${period}days.csv`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
      toast.success('CSV успешно скачан');
    } catch (error) {
      const message = error instanceof Error ? error.message : 'Не удалось экспортировать данные';
      toast.error(message);
    }
  };

  return (
    <button
      type="button"
      onClick={handleExport}
      disabled={disabled}
      title={disabled ? disabledReason : undefined}
      className="inline-flex min-h-[42px] items-center justify-center gap-2 rounded-xl border border-white/15 bg-white/[0.03] px-4 py-2.5 text-sm font-medium text-gray-200 shadow-[0_0_20px_rgba(42,171,238,0.08)] transition-all duration-300 hover:border-white/30 hover:bg-white/[0.08] hover:text-white disabled:cursor-not-allowed disabled:opacity-55"
    >
      <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
        <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
        <polyline points="7 10 12 15 17 10" />
        <line x1="12" y1="15" x2="12" y2="3" />
      </svg>
      {disabled ? 'CSV недоступен' : 'Экспорт CSV'}
    </button>
  );
}
