'use client';

import { useState, useEffect, useCallback } from 'react';
import { Dialog, DialogHeader, DialogBody, DialogFooter } from '@/components/ui/dialog';
import { api } from '@/lib/api';
import { fetchAll } from '@/lib/fetch-all';

type LicenseType = 'STARTER' | 'STANDARD' | 'PREMIUM';

interface Club {
  id: string;
  name: string;
}

interface IssueLicenseDialogProps {
  open: boolean;
  onClose: () => void;
  onCreated: () => void;
}

const typeDefaults: Record<LicenseType, { maxUsers: number; maxClients: number }> = {
  STARTER: { maxUsers: 5, maxClients: 500 },
  STANDARD: { maxUsers: 10, maxClients: 1000 },
  PREMIUM: { maxUsers: 999, maxClients: 99999 },
};

const typeLabels: Record<LicenseType, string> = {
  STARTER: 'Стартовая',
  STANDARD: 'Стандартная',
  PREMIUM: 'Премиум',
};

function toDateInputValue(date: Date): string {
  return date.toISOString().split('T')[0] ?? '';
}

export function IssueLicenseDialog({ open, onClose, onCreated }: IssueLicenseDialogProps) {
  const [clubs, setClubs] = useState<Club[]>([]);
  const [clubsLoading, setClubsLoading] = useState(false);
  const [clubsError, setClubsError] = useState<string | null>(null);

  const [clubId, setClubId] = useState('');
  const [type, setType] = useState<LicenseType>('STARTER');
  const [startDate, setStartDate] = useState(() => toDateInputValue(new Date()));
  const [endDate, setEndDate] = useState(() => {
    const d = new Date();
    d.setDate(d.getDate() + 365);
    return toDateInputValue(d);
  });
  const [maxUsers, setMaxUsers] = useState(typeDefaults.STARTER.maxUsers);
  const [maxClients, setMaxClients] = useState(typeDefaults.STARTER.maxClients);

  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);

  const fetchClubs = useCallback(async () => {
    setClubsLoading(true);
    setClubsError(null);
    try {
      const clubs = await fetchAll<Club>('/clubs');
      setClubs(clubs);
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Не удалось загрузить список клубов';
      setClubsError(message);
    } finally {
      setClubsLoading(false);
    }
  }, []);

  useEffect(() => {
    if (open) {
      void fetchClubs();
      // Reset form on open
      setClubId('');
      setType('STARTER');
      const today = new Date();
      setStartDate(toDateInputValue(today));
      const end = new Date(today);
      end.setDate(end.getDate() + 365);
      setEndDate(toDateInputValue(end));
      setMaxUsers(typeDefaults.STARTER.maxUsers);
      setMaxClients(typeDefaults.STARTER.maxClients);
      setSubmitError(null);
    }
  }, [open, fetchClubs]);

  useEffect(() => {
    const defaults = typeDefaults[type];
    setMaxUsers(defaults.maxUsers);
    setMaxClients(defaults.maxClients);
  }, [type]);

  useEffect(() => {
    if (startDate) {
      const d = new Date(startDate);
      d.setDate(d.getDate() + 365);
      setEndDate(toDateInputValue(d));
    }
  }, [startDate]);

  const inputClass =
    'w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary';

  const handleSubmit = async () => {
    if (!clubId) {
      setSubmitError('Выберите клуб');
      return;
    }
    if (!startDate || !endDate) {
      setSubmitError('Укажите даты начала и окончания');
      return;
    }

    setSubmitting(true);
    setSubmitError(null);

    try {
      await api.post('/licenses', {
        clubId,
        type,
        startDate: new Date(startDate).toISOString(),
        endDate: new Date(endDate).toISOString(),
        maxUsers,
        maxClients,
      });
      onCreated();
      onClose();
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Не удалось выдать лицензию';
      setSubmitError(message);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Dialog open={open} onClose={onClose}>
      <DialogHeader
        title="Выдать лицензию"
        description="Создание новой лицензии для клуба"
        onClose={onClose}
      />

      <DialogBody className="space-y-4">
        {/* Club select */}
        <div>
          <label className="block text-sm font-medium text-text mb-1">Клуб</label>
          {clubsLoading ? (
            <div className="flex items-center gap-2 text-sm text-muted py-2">
              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary" />
              Загрузка клубов...
            </div>
          ) : clubsError ? (
            <div className="text-sm text-error py-1">
              {clubsError}{' '}
              <button
                type="button"
                onClick={() => void fetchClubs()}
                className="text-primary hover:underline"
              >
                Повторить
              </button>
            </div>
          ) : (
            <select
              value={clubId}
              onChange={(e) => setClubId(e.target.value)}
              className={inputClass}
            >
              <option value="">-- Выберите клуб --</option>
              {clubs.map((c) => (
                <option key={c.id} value={c.id}>
                  {c.name}
                </option>
              ))}
            </select>
          )}
        </div>

        {/* License type */}
        <div>
          <label className="block text-sm font-medium text-text mb-1">Тип лицензии</label>
          <select
            value={type}
            onChange={(e) => setType(e.target.value as LicenseType)}
            className={inputClass}
          >
            {(Object.keys(typeLabels) as LicenseType[]).map((t) => (
              <option key={t} value={t}>
                {typeLabels[t]}
              </option>
            ))}
          </select>
        </div>

        {/* Dates */}
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-text mb-1">Дата начала</label>
            <input
              type="date"
              value={startDate}
              onChange={(e) => setStartDate(e.target.value)}
              className={inputClass}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-1">Дата окончания</label>
            <input
              type="date"
              value={endDate}
              onChange={(e) => setEndDate(e.target.value)}
              className={inputClass}
            />
          </div>
        </div>

        {/* Limits */}
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-text mb-1">
              Макс. пользователей
            </label>
            <input
              type="number"
              min={1}
              value={maxUsers}
              onChange={(e) => setMaxUsers(Number(e.target.value))}
              className={inputClass}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-1">
              Макс. клиентов
            </label>
            <input
              type="number"
              min={1}
              value={maxClients}
              onChange={(e) => setMaxClients(Number(e.target.value))}
              className={inputClass}
            />
          </div>
        </div>

        {submitError && (
          <div className="px-3 py-2 rounded-lg bg-error/10 border border-error/20 text-error text-sm">
            {submitError}
          </div>
        )}
      </DialogBody>

      <DialogFooter>
        <button
          type="button"
          onClick={onClose}
          disabled={submitting}
          className="px-4 py-2.5 rounded-xl text-sm font-medium border border-border text-text hover:bg-background transition-colors disabled:opacity-50"
        >
          Отмена
        </button>
        <button
          type="button"
          onClick={() => void handleSubmit()}
          disabled={submitting || clubsLoading}
          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"
        >
          {submitting ? 'Создание...' : 'Выдать лицензию'}
        </button>
      </DialogFooter>
    </Dialog>
  );
}
