'use client';

import { useState } from 'react';
import { CheckCircle } from 'lucide-react';
import { Dialog, DialogHeader, DialogBody, DialogFooter } from '@/components/ui/dialog';
import { api } from '@/lib/api';

type RenewDialogProps = {
  open: boolean;
  onClose: () => void;
  onRenewed: () => void;
  licenseInfo: { type: string; expiresAt: string } | null;
};

const RENEWAL_PERIODS = [
  { value: 1, label: '1 месяц' },
  { value: 3, label: '3 месяца' },
  { value: 6, label: '6 месяцев' },
  { value: 12, label: '12 месяцев' },
];

export function RenewDialog({ open, onClose, onRenewed, licenseInfo }: RenewDialogProps) {
  const [period, setPeriod] = useState(1);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  const reset = () => {
    setPeriod(1);
    setLoading(false);
    setError(null);
    setSuccess(false);
  };

  const handleClose = () => {
    if (success) {
      onRenewed();
    }
    reset();
    onClose();
  };

  const handleSubmit = async () => {
    setLoading(true);
    setError(null);
    try {
      await api.post('/licenses/renew', { period });
      setSuccess(true);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Не удалось продлить лицензию');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onClose={handleClose} className="max-w-md">
      <DialogHeader
        title="Продление лицензии"
        onClose={handleClose}
      />
      <DialogBody>
        {success ? (
          <div className="text-center py-4">
            <div className="bg-green-50 text-success p-3 rounded-full inline-flex mb-4">
              <CheckCircle className="h-8 w-8" />
            </div>
            <h3 className="text-base font-semibold text-gray-900 mb-1">
              Лицензия продлена
            </h3>
            <p className="text-sm text-gray-600">
              Лицензия успешно продлена на {RENEWAL_PERIODS.find((p) => p.value === period)?.label}.
            </p>
          </div>
        ) : (
          <div className="space-y-4">
            {licenseInfo && (
              <div className="bg-gray-50 rounded-lg p-4 space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-muted">Тип лицензии</span>
                  <span className="font-medium text-gray-900">{licenseInfo.type}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-muted">Истекает</span>
                  <span className="font-medium text-gray-900">{licenseInfo.expiresAt}</span>
                </div>
              </div>
            )}

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Период продления
              </label>
              <div className="grid grid-cols-2 gap-2">
                {RENEWAL_PERIODS.map((option) => (
                  <button
                    key={option.value}
                    onClick={() => setPeriod(option.value)}
                    className={`px-4 py-3 rounded-xl border text-sm font-medium transition-colors ${
                      period === option.value
                        ? 'border-primary bg-primary/5 text-primary'
                        : 'border-border text-gray-700 hover:bg-gray-50'
                    }`}
                  >
                    {option.label}
                  </button>
                ))}
              </div>
            </div>

            {error && (
              <p className="text-sm text-error">{error}</p>
            )}
          </div>
        )}
      </DialogBody>
      <DialogFooter>
        {success ? (
          <button
            onClick={handleClose}
            className="bg-primary text-white px-4 py-2.5 rounded-xl text-sm font-medium hover:bg-primary/90 transition-colors"
          >
            Закрыть
          </button>
        ) : (
          <>
            <button
              onClick={handleClose}
              disabled={loading}
              className="px-4 py-2 rounded-xl border border-border text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors"
            >
              Отмена
            </button>
            <button
              onClick={() => void handleSubmit()}
              disabled={loading}
              className="bg-primary text-white px-4 py-2.5 rounded-xl text-sm font-medium hover:bg-primary/90 transition-colors disabled:opacity-50"
            >
              {loading ? 'Оформление...' : 'Продлить'}
            </button>
          </>
        )}
      </DialogFooter>
    </Dialog>
  );
}
