import { useState, useEffect, useCallback } from 'react'
import { promoApi } from '@/api'
import type { PromoCode, PromoCodeCreate, PromoCodeRedemption } from '@/types'
import { useToast } from '@/store/toast'
import { useConfirm } from '@/store/confirm'
import { NeonButton, Input, GlassCard } from '@/components/ui'
import {
  Gift, Plus, Trash2, Edit, Users, Copy, Check, X,
  Eye, Loader2, Coins
} from 'lucide-react'
import clsx from 'clsx'

// Format date for display
function formatDate(dateStr: string | null): string {
  if (!dateStr) return '—'
  return new Date(dateStr).toLocaleDateString('ru-RU', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}

// Format date for input
function formatDateForInput(dateStr: string | null): string {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toISOString().slice(0, 16)
}

export function AdminPromoCodesPage() {
  const [promoCodes, setPromoCodes] = useState<PromoCode[]>([])
  const [loading, setLoading] = useState(true)
  const [includeInactive, setIncludeInactive] = useState(false)

  // Create modal state
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [createData, setCreateData] = useState<PromoCodeCreate>({
    code: '',
    coins_amount: 100,
    max_uses: null,
    valid_from: null,
    valid_until: null,
  })
  const [autoGenerate, setAutoGenerate] = useState(true)
  const [creating, setCreating] = useState(false)

  // Edit modal state
  const [editingPromo, setEditingPromo] = useState<PromoCode | null>(null)
  const [editData, setEditData] = useState({
    is_active: true,
    max_uses: null as number | null,
    valid_until: '',
  })
  const [saving, setSaving] = useState(false)

  // Redemptions modal state
  const [viewingRedemptions, setViewingRedemptions] = useState<PromoCode | null>(null)
  const [redemptions, setRedemptions] = useState<PromoCodeRedemption[]>([])
  const [loadingRedemptions, setLoadingRedemptions] = useState(false)

  // Copied state for code
  const [copiedCode, setCopiedCode] = useState<string | null>(null)

  const toast = useToast()
  const confirm = useConfirm()

  const loadPromoCodes = useCallback(async () => {
    setLoading(true)
    try {
      const response = await promoApi.admin.list(includeInactive)
      setPromoCodes(response.data)
    } catch {
      toast.error('Ошибка загрузки промокодов')
    } finally {
      setLoading(false)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [includeInactive])

  useEffect(() => {
    loadPromoCodes()
  }, [loadPromoCodes])

  const handleCreate = async () => {
    if (!autoGenerate && !createData.code?.trim()) {
      toast.error('Введите код или включите автогенерацию')
      return
    }
    if (createData.coins_amount < 1) {
      toast.error('Количество монет должно быть больше 0')
      return
    }

    setCreating(true)
    try {
      const response = await promoApi.admin.create({
        ...createData,
        code: autoGenerate ? null : createData.code,
      })
      setPromoCodes([response.data, ...promoCodes])
      toast.success(`Промокод ${response.data.code} создан`)
      setShowCreateModal(false)
      resetCreateForm()
    } catch (error: unknown) {
      const err = error as { response?: { data?: { detail?: string } } }
      toast.error(err.response?.data?.detail || 'Ошибка создания промокода')
    } finally {
      setCreating(false)
    }
  }

  const resetCreateForm = () => {
    setCreateData({
      code: '',
      coins_amount: 100,
      max_uses: null,
      valid_from: null,
      valid_until: null,
    })
    setAutoGenerate(true)
  }

  const handleEdit = (promo: PromoCode) => {
    setEditingPromo(promo)
    setEditData({
      is_active: promo.is_active,
      max_uses: promo.max_uses,
      valid_until: formatDateForInput(promo.valid_until),
    })
  }

  const handleSaveEdit = async () => {
    if (!editingPromo) return

    setSaving(true)
    try {
      const response = await promoApi.admin.update(editingPromo.id, {
        is_active: editData.is_active,
        max_uses: editData.max_uses,
        valid_until: editData.valid_until ? new Date(editData.valid_until).toISOString() : null,
      })
      setPromoCodes(promoCodes.map(p => p.id === response.data.id ? response.data : p))
      toast.success('Промокод обновлён')
      setEditingPromo(null)
    } catch {
      toast.error('Ошибка обновления промокода')
    } finally {
      setSaving(false)
    }
  }

  const handleDelete = async (promo: PromoCode) => {
    const confirmed = await confirm({
      title: 'Удалить промокод',
      message: `Вы уверены, что хотите удалить промокод ${promo.code}?`,
      confirmText: 'Удалить',
      variant: 'danger',
    })
    if (!confirmed) return

    try {
      await promoApi.admin.delete(promo.id)
      setPromoCodes(promoCodes.filter(p => p.id !== promo.id))
      toast.success('Промокод удалён')
    } catch {
      toast.error('Ошибка удаления промокода')
    }
  }

  const handleToggleActive = async (promo: PromoCode) => {
    try {
      const response = await promoApi.admin.update(promo.id, {
        is_active: !promo.is_active,
      })
      setPromoCodes(promoCodes.map(p => p.id === response.data.id ? response.data : p))
      toast.success(response.data.is_active ? 'Промокод активирован' : 'Промокод деактивирован')
    } catch {
      toast.error('Ошибка обновления промокода')
    }
  }

  const handleViewRedemptions = async (promo: PromoCode) => {
    setViewingRedemptions(promo)
    setLoadingRedemptions(true)
    try {
      const response = await promoApi.admin.getRedemptions(promo.id)
      setRedemptions(response.data)
    } catch {
      toast.error('Ошибка загрузки использований')
    } finally {
      setLoadingRedemptions(false)
    }
  }

  const handleCopyCode = (code: string) => {
    navigator.clipboard.writeText(code)
    setCopiedCode(code)
    setTimeout(() => setCopiedCode(null), 2000)
  }

  const isPromoValid = (promo: PromoCode): boolean => {
    if (!promo.is_active) return false
    const now = new Date()
    if (promo.valid_from && new Date(promo.valid_from) > now) return false
    if (promo.valid_until && new Date(promo.valid_until) < now) return false
    if (promo.max_uses !== null && promo.uses_count >= promo.max_uses) return false
    return true
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="p-2 rounded-lg bg-yellow-500/20 border border-yellow-500/30">
            <Gift className="w-6 h-6 text-yellow-400" />
          </div>
          <div>
            <h1 className="text-2xl font-bold text-white">Промокоды</h1>
            <p className="text-sm text-gray-400">Управление промокодами на монеты</p>
          </div>
        </div>

        <div className="flex items-center gap-3">
          <label className="flex items-center gap-2 text-sm text-gray-400 cursor-pointer">
            <input
              type="checkbox"
              checked={includeInactive}
              onChange={(e) => setIncludeInactive(e.target.checked)}
              className="rounded border-dark-600 bg-dark-700 text-neon-500 focus:ring-neon-500"
            />
            Показать неактивные
          </label>

          <NeonButton
            onClick={() => setShowCreateModal(true)}
            icon={<Plus className="w-4 h-4" />}
          >
            Создать
          </NeonButton>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <GlassCard className="p-4">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-lg bg-yellow-500/20 flex items-center justify-center">
              <Gift className="w-5 h-5 text-yellow-400" />
            </div>
            <div>
              <p className="text-2xl font-bold text-white">{promoCodes.length}</p>
              <p className="text-sm text-gray-400">Всего кодов</p>
            </div>
          </div>
        </GlassCard>
        <GlassCard className="p-4">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-lg bg-green-500/20 flex items-center justify-center">
              <Check className="w-5 h-5 text-green-400" />
            </div>
            <div>
              <p className="text-2xl font-bold text-white">
                {promoCodes.filter(p => isPromoValid(p)).length}
              </p>
              <p className="text-sm text-gray-400">Активных</p>
            </div>
          </div>
        </GlassCard>
        <GlassCard className="p-4">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-lg bg-blue-500/20 flex items-center justify-center">
              <Users className="w-5 h-5 text-blue-400" />
            </div>
            <div>
              <p className="text-2xl font-bold text-white">
                {promoCodes.reduce((sum, p) => sum + p.uses_count, 0)}
              </p>
              <p className="text-sm text-gray-400">Использований</p>
            </div>
          </div>
        </GlassCard>
        <GlassCard className="p-4">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-lg bg-purple-500/20 flex items-center justify-center">
              <Coins className="w-5 h-5 text-purple-400" />
            </div>
            <div>
              <p className="text-2xl font-bold text-white">
                {promoCodes.reduce((sum, p) => sum + p.coins_amount * p.uses_count, 0)}
              </p>
              <p className="text-sm text-gray-400">Выдано монет</p>
            </div>
          </div>
        </GlassCard>
      </div>

      {/* Table */}
      <GlassCard className="overflow-hidden">
        {loading ? (
          <div className="flex items-center justify-center py-12">
            <Loader2 className="w-8 h-8 text-neon-500 animate-spin" />
          </div>
        ) : promoCodes.length === 0 ? (
          <div className="text-center py-12">
            <Gift className="w-12 h-12 text-gray-600 mx-auto mb-3" />
            <p className="text-gray-400">Промокоды не найдены</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-dark-600">
                  <th className="text-left p-4 text-sm font-medium text-gray-400">Код</th>
                  <th className="text-left p-4 text-sm font-medium text-gray-400">Монет</th>
                  <th className="text-left p-4 text-sm font-medium text-gray-400">Лимит</th>
                  <th className="text-left p-4 text-sm font-medium text-gray-400">Использований</th>
                  <th className="text-left p-4 text-sm font-medium text-gray-400">Срок</th>
                  <th className="text-left p-4 text-sm font-medium text-gray-400">Статус</th>
                  <th className="text-left p-4 text-sm font-medium text-gray-400">Создан</th>
                  <th className="text-right p-4 text-sm font-medium text-gray-400">Действия</th>
                </tr>
              </thead>
              <tbody>
                {promoCodes.map((promo) => (
                  <tr key={promo.id} className="border-b border-dark-600/50 hover:bg-dark-700/30">
                    <td className="p-4">
                      <div className="flex items-center gap-2">
                        <code className="px-2 py-1 bg-dark-700 rounded text-yellow-400 font-mono text-sm">
                          {promo.code}
                        </code>
                        <button
                          onClick={() => handleCopyCode(promo.code)}
                          className="p-1 text-gray-400 hover:text-white transition-colors"
                          title="Копировать"
                        >
                          {copiedCode === promo.code ? (
                            <Check className="w-4 h-4 text-green-400" />
                          ) : (
                            <Copy className="w-4 h-4" />
                          )}
                        </button>
                      </div>
                    </td>
                    <td className="p-4">
                      <span className="text-white font-medium">{promo.coins_amount}</span>
                    </td>
                    <td className="p-4">
                      <span className="text-gray-400">
                        {promo.max_uses !== null ? promo.max_uses : '∞'}
                      </span>
                    </td>
                    <td className="p-4">
                      <button
                        onClick={() => handleViewRedemptions(promo)}
                        className="text-neon-400 hover:text-neon-300 transition-colors"
                      >
                        {promo.uses_count}
                      </button>
                    </td>
                    <td className="p-4 text-sm text-gray-400">
                      {promo.valid_until ? formatDate(promo.valid_until) : '—'}
                    </td>
                    <td className="p-4">
                      {isPromoValid(promo) ? (
                        <span className="px-2 py-1 rounded-full bg-green-500/20 text-green-400 text-xs">
                          Активен
                        </span>
                      ) : (
                        <span className="px-2 py-1 rounded-full bg-red-500/20 text-red-400 text-xs">
                          Неактивен
                        </span>
                      )}
                    </td>
                    <td className="p-4 text-sm text-gray-400">
                      {formatDate(promo.created_at)}
                    </td>
                    <td className="p-4">
                      <div className="flex items-center justify-end gap-2">
                        <button
                          onClick={() => handleToggleActive(promo)}
                          className={clsx(
                            'p-1.5 rounded-lg transition-colors',
                            promo.is_active
                              ? 'bg-green-500/20 text-green-400 hover:bg-green-500/30'
                              : 'bg-gray-500/20 text-gray-400 hover:bg-gray-500/30'
                          )}
                          title={promo.is_active ? 'Деактивировать' : 'Активировать'}
                        >
                          {promo.is_active ? <Check className="w-4 h-4" /> : <X className="w-4 h-4" />}
                        </button>
                        <button
                          onClick={() => handleViewRedemptions(promo)}
                          className="p-1.5 rounded-lg bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 transition-colors"
                          title="Использования"
                        >
                          <Eye className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => handleEdit(promo)}
                          className="p-1.5 rounded-lg bg-neon-500/20 text-neon-400 hover:bg-neon-500/30 transition-colors"
                          title="Редактировать"
                        >
                          <Edit className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => handleDelete(promo)}
                          className="p-1.5 rounded-lg bg-red-500/20 text-red-400 hover:bg-red-500/30 transition-colors"
                          title="Удалить"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </GlassCard>

      {/* Create Modal */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-dark-900/80 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="glass rounded-2xl p-6 w-full max-w-md border border-dark-600 shadow-xl">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-xl font-bold text-white">Создать промокод</h2>
              <button
                onClick={() => {
                  setShowCreateModal(false)
                  resetCreateForm()
                }}
                className="p-1 text-gray-400 hover:text-white transition-colors"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="space-y-4">
              {/* Auto generate toggle */}
              <label className="flex items-center gap-3 p-3 bg-dark-700/50 rounded-xl cursor-pointer">
                <input
                  type="checkbox"
                  checked={autoGenerate}
                  onChange={(e) => setAutoGenerate(e.target.checked)}
                  className="rounded border-dark-600 bg-dark-700 text-neon-500 focus:ring-neon-500"
                />
                <div>
                  <p className="text-white font-medium">Автогенерация кода</p>
                  <p className="text-sm text-gray-400">Создать случайный код</p>
                </div>
              </label>

              {/* Manual code input */}
              {!autoGenerate && (
                <div>
                  <label className="block text-sm text-gray-400 mb-1">Код</label>
                  <Input
                    placeholder="Введите код (A-Z, 0-9)"
                    value={createData.code || ''}
                    onChange={(e) => setCreateData({ ...createData, code: e.target.value.toUpperCase() })}
                  />
                </div>
              )}

              {/* Coins amount */}
              <div>
                <label className="block text-sm text-gray-400 mb-1">Количество монет</label>
                <Input
                  type="number"
                  min={1}
                  max={100000}
                  value={createData.coins_amount}
                  onChange={(e) => setCreateData({ ...createData, coins_amount: parseInt(e.target.value) || 0 })}
                />
              </div>

              {/* Max uses */}
              <div>
                <label className="block text-sm text-gray-400 mb-1">Лимит использований (пусто = безлимит)</label>
                <Input
                  type="number"
                  min={1}
                  placeholder="Без ограничений"
                  value={createData.max_uses || ''}
                  onChange={(e) => setCreateData({ ...createData, max_uses: e.target.value ? parseInt(e.target.value) : null })}
                />
              </div>

              {/* Valid until */}
              <div>
                <label className="block text-sm text-gray-400 mb-1">Действует до (пусто = бессрочно)</label>
                <Input
                  type="datetime-local"
                  value={createData.valid_until || ''}
                  onChange={(e) => setCreateData({ ...createData, valid_until: e.target.value || null })}
                />
              </div>

              <div className="flex gap-3 pt-2">
                <NeonButton
                  onClick={handleCreate}
                  isLoading={creating}
                  className="flex-1"
                  icon={<Plus className="w-4 h-4" />}
                >
                  Создать
                </NeonButton>
                <NeonButton
                  variant="ghost"
                  onClick={() => {
                    setShowCreateModal(false)
                    resetCreateForm()
                  }}
                >
                  Отмена
                </NeonButton>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Edit Modal */}
      {editingPromo && (
        <div className="fixed inset-0 bg-dark-900/80 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="glass rounded-2xl p-6 w-full max-w-md border border-dark-600 shadow-xl">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-xl font-bold text-white">Редактировать промокод</h2>
              <button
                onClick={() => setEditingPromo(null)}
                className="p-1 text-gray-400 hover:text-white transition-colors"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="space-y-4">
              {/* Code display */}
              <div className="p-3 bg-dark-700/50 rounded-xl">
                <p className="text-sm text-gray-400 mb-1">Код</p>
                <code className="text-yellow-400 font-mono text-lg">{editingPromo.code}</code>
              </div>

              {/* Active toggle */}
              <label className="flex items-center justify-between p-3 bg-dark-700/50 rounded-xl cursor-pointer">
                <div>
                  <p className="text-white font-medium">Активен</p>
                  <p className="text-sm text-gray-400">Код можно использовать</p>
                </div>
                <input
                  type="checkbox"
                  checked={editData.is_active}
                  onChange={(e) => setEditData({ ...editData, is_active: e.target.checked })}
                  className="rounded border-dark-600 bg-dark-700 text-neon-500 focus:ring-neon-500 w-5 h-5"
                />
              </label>

              {/* Max uses */}
              <div>
                <label className="block text-sm text-gray-400 mb-1">Лимит использований</label>
                <Input
                  type="number"
                  min={1}
                  placeholder="Без ограничений"
                  value={editData.max_uses || ''}
                  onChange={(e) => setEditData({ ...editData, max_uses: e.target.value ? parseInt(e.target.value) : null })}
                />
              </div>

              {/* Valid until */}
              <div>
                <label className="block text-sm text-gray-400 mb-1">Действует до</label>
                <Input
                  type="datetime-local"
                  value={editData.valid_until}
                  onChange={(e) => setEditData({ ...editData, valid_until: e.target.value })}
                />
              </div>

              <div className="flex gap-3 pt-2">
                <NeonButton
                  onClick={handleSaveEdit}
                  isLoading={saving}
                  className="flex-1"
                  icon={<Check className="w-4 h-4" />}
                >
                  Сохранить
                </NeonButton>
                <NeonButton
                  variant="ghost"
                  onClick={() => setEditingPromo(null)}
                >
                  Отмена
                </NeonButton>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Redemptions Modal */}
      {viewingRedemptions && (
        <div className="fixed inset-0 bg-dark-900/80 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="glass rounded-2xl p-6 w-full max-w-lg border border-dark-600 shadow-xl max-h-[80vh] overflow-hidden flex flex-col">
            <div className="flex items-center justify-between mb-6">
              <div>
                <h2 className="text-xl font-bold text-white">Использования промокода</h2>
                <p className="text-sm text-gray-400">
                  <code className="text-yellow-400">{viewingRedemptions.code}</code>
                  {' • '}
                  {viewingRedemptions.uses_count} использований
                </p>
              </div>
              <button
                onClick={() => {
                  setViewingRedemptions(null)
                  setRedemptions([])
                }}
                className="p-1 text-gray-400 hover:text-white transition-colors"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="flex-1 overflow-y-auto">
              {loadingRedemptions ? (
                <div className="flex items-center justify-center py-12">
                  <Loader2 className="w-6 h-6 text-neon-500 animate-spin" />
                </div>
              ) : redemptions.length === 0 ? (
                <div className="text-center py-12">
                  <Users className="w-10 h-10 text-gray-600 mx-auto mb-3" />
                  <p className="text-gray-400">Пока никто не использовал этот код</p>
                </div>
              ) : (
                <div className="space-y-2">
                  {redemptions.map((r) => (
                    <div
                      key={r.id}
                      className="flex items-center justify-between p-3 bg-dark-700/50 rounded-xl"
                    >
                      <div className="flex items-center gap-3">
                        <div className="w-8 h-8 rounded-lg bg-neon-500/20 flex items-center justify-center">
                          <Users className="w-4 h-4 text-neon-400" />
                        </div>
                        <div>
                          <p className="text-white font-medium">{r.user.nickname}</p>
                          <p className="text-xs text-gray-400">{formatDate(r.redeemed_at)}</p>
                        </div>
                      </div>
                      <div className="text-yellow-400 font-medium">
                        +{r.coins_awarded}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>

            <div className="pt-4 border-t border-dark-600 mt-4">
              <NeonButton
                variant="ghost"
                onClick={() => {
                  setViewingRedemptions(null)
                  setRedemptions([])
                }}
                className="w-full"
              >
                Закрыть
              </NeonButton>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
