'use client';

import { useState } from 'react';
import LinkEditModal from './LinkEditModal';
import QRCodeModal from './QRCodeModal';
import ExportButton from './ExportButton';
import ExportHtmlButton from './ExportHtmlButton';
import ApiErrorAlert from './ApiErrorAlert';
import { useToast } from './ToastProvider';
import type { PlanFeatures } from '@/lib/plans/types';

interface LinkActionsProps {
  link: {
    id: string;
    shortUrl: string;
    longUrl: string;
    title: string | null;
    description: string | null;
    ogTitle: string | null;
    ogDescription: string | null;
    ogImage: string | null;
    hasPassword?: boolean;
  };
  period?: string;
  planFeatures?: PlanFeatures;
  onUpdate: () => void;
  onDelete: () => void;
}

const DEFAULT_PLAN_FEATURES: PlanFeatures = {
  customSlug: false,
  password: false,
  expiresAt: false,
  clickLimit: false,
  telegramClickNotifications: false,
  bulkActions: false,
  csvExport: false,
  pdfExport: false,
  manualOgEditing: false,
};

export default function LinkActions({
  link,
  period = '7',
  planFeatures = DEFAULT_PLAN_FEATURES,
  onUpdate,
  onDelete,
}: LinkActionsProps) {
  const [showEditModal, setShowEditModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [showQRModal, setShowQRModal] = useState(false);
  const toast = useToast();

  const handleCopyUrl = async () => {
    try {
      await navigator.clipboard.writeText(link.shortUrl);
      toast.success('URL скопирован');
    } catch {
      toast.error('Не удалось скопировать URL');
    }
  };

  return (
    <>
      {!planFeatures.csvExport || !planFeatures.pdfExport ? (
        <ApiErrorAlert
          message={!planFeatures.csvExport
            ? 'CSV-экспорт недоступен на текущем тарифе. Обновите тариф до Lite или выше.'
            : 'HTML-экспорт недоступен на текущем тарифе. Обновите тариф до Pro или выше.'}
          compact
          variant="inline"
          className="mb-2"
        />
      ) : null}

      <div className="grid w-full grid-cols-2 sm:grid-cols-4 gap-2 sm:flex sm:w-auto sm:flex-wrap sm:items-center">
        {/* Редактировать */}
        <button
          onClick={() => setShowEditModal(true)}
          className="inline-flex items-center justify-center gap-1.5 rounded-md border border-white/10 bg-white/[0.03] px-2.5 py-1 text-xs font-medium text-gray-300 transition-colors hover:bg-white/[0.08] hover:text-white"
          title="Редактировать ссылку"
        >
          <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
            <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
          </svg>
          <span className="hidden sm:inline">Редактировать</span>
        </button>

        {/* Копировать URL */}
        <button
          onClick={handleCopyUrl}
          className="inline-flex items-center justify-center gap-1.5 rounded-md border border-white/10 bg-white/[0.03] px-2.5 py-1 text-xs font-medium text-gray-300 transition-colors hover:bg-white/[0.08] hover:text-white"
          title="Копировать URL"
        >
          <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <rect x="9" y="9" width="13" height="13" rx="2"/>
            <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
          </svg>
          <span className="hidden sm:inline">Копировать</span>
        </button>

        {/* QR-код */}
        <button
          onClick={() => setShowQRModal(true)}
          className="inline-flex items-center justify-center gap-1.5 rounded-md border border-white/10 bg-white/[0.03] px-2.5 py-1 text-xs font-medium text-gray-300 transition-colors hover:bg-white/[0.08] hover:text-white"
          title="QR-код"
        >
          <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <rect x="3" y="3" width="7" height="7" rx="1" />
            <rect x="14" y="3" width="7" height="7" rx="1" />
            <rect x="3" y="14" width="7" height="7" rx="1" />
            <path d="M14 14h3v3h-3z" />
            <path d="M20 14v2" />
            <path d="M17 17h4v4" />
          </svg>
          <span className="hidden sm:inline">QR-код</span>
        </button>

        <ExportButton
          linkId={link.id}
          period={period}
          disabled={!planFeatures.csvExport}
          disabledReason="CSV-экспорт доступен начиная с тарифа Lite."
        />

        <ExportHtmlButton
          linkId={link.id}
          period={period}
          linkData={{
            shortUrl: link.shortUrl,
            longUrl: link.longUrl,
            title: link.title,
          }}
          disabled={!planFeatures.pdfExport}
          disabledReason="HTML-экспорт доступен начиная с тарифа Pro."
        />

        {/* Удалить */}
        <button
          onClick={() => setShowDeleteModal(true)}
          className="inline-flex items-center justify-center gap-1.5 rounded-md border border-red-500/30 bg-red-500/10 px-2.5 py-1 text-xs font-medium text-red-200 transition-colors hover:bg-red-500/20"
          title="Удалить ссылку"
        >
          <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M3 6h18M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
          </svg>
          <span className="hidden sm:inline">Удалить</span>
        </button>
      </div>

      {/* Модальное окно редактирования */}
      {showEditModal && (
        <LinkEditModal
          link={link}
          planFeatures={planFeatures}
          onClose={() => setShowEditModal(false)}
          onSave={() => {
            setShowEditModal(false);
            onUpdate();
          }}
        />
      )}

      {showQRModal && (
        <QRCodeModal
          isOpen={showQRModal}
          onClose={() => setShowQRModal(false)}
          url={link.shortUrl}
          title={link.title}
        />
      )}

      {/* Модальное окно удаления */}
      {showDeleteModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm">
          <div className="animate-scale-up w-full max-w-md rounded-xl border border-white/10 bg-[#0A0A0A]/95 p-6">
            <h3 className="mb-2 text-lg font-semibold text-white">Удалить ссылку?</h3>
            <p className="mb-6 text-sm text-gray-400">
              Вы уверены что хотите удалить ссылку <strong>{link.title || link.shortUrl}</strong>?
              Это действие нельзя отменить.
            </p>
            <div className="flex gap-3">
              <button
                onClick={() => setShowDeleteModal(false)}
                className="flex-1 rounded-lg border border-white/10 bg-white/[0.03] px-4 py-2.5 text-sm font-medium text-gray-300 transition-colors hover:bg-white/[0.08] hover:text-white"
              >
                Отмена
              </button>
              <button
                onClick={() => {
                  onDelete();
                  setShowDeleteModal(false);
                }}
                className="flex-1 rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-2.5 text-sm font-medium text-red-100 transition-colors hover:bg-red-500/20"
              >
                Удалить
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
