import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { adminApi } from '@/api/admin'
import { Button } from '@/components/common/Button'
import { Loading } from '@/components/common/Loading'
import { AlertTriangle, Database, Trash2, RefreshCw } from 'lucide-react'
import toast from 'react-hot-toast'
import type { SeedRequest } from '@/types/admin'

export const AdminDataTools = () => {
  const queryClient = useQueryClient()
  const [showWipeModal, setShowWipeModal] = useState(false)
  const [confirmPhrase, setConfirmPhrase] = useState('')
  const [preserveAdmins, setPreserveAdmins] = useState(true)
  const [preserveEvents, setPreserveEvents] = useState(false)

  const [seedConfig, setSeedConfig] = useState<SeedRequest>({
    num_users: 10,
    num_events: 5,
    num_bets_per_event: 3,
    starting_balance: 1000,
    create_admin: true,
  })

  const { data: wipePreview, isLoading: isLoadingPreview, refetch: refetchPreview } = useQuery({
    queryKey: ['wipe-preview'],
    queryFn: adminApi.getWipePreview,
  })

  const wipeMutation = useMutation({
    mutationFn: adminApi.executeWipe,
    onSuccess: (data) => {
      toast.success(data.message)
      setShowWipeModal(false)
      setConfirmPhrase('')
      queryClient.invalidateQueries()
      refetchPreview()
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.detail || 'Wipe failed')
    },
  })

  const seedMutation = useMutation({
    mutationFn: adminApi.seedDatabase,
    onSuccess: (data) => {
      console.log('Seed success:', data)
      toast.success(data.message)
      if (data.test_admin) {
        toast.success(`Test admin created: ${data.test_admin.username} / ${data.test_admin.password}`, {
          duration: 10000,
        })
      }
      // Show what was created
      const counts = data.created_counts
      toast.success(`Created: ${counts.users} users, ${counts.events} events, ${counts.bets} bets`, {
        duration: 5000,
      })
      queryClient.invalidateQueries()
      refetchPreview()
    },
    onError: (error: any) => {
      console.error('Seed error:', error)
      const message = error.response?.data?.detail || error.message || 'Seed failed'
      toast.error(message)
    },
  })

  const handleWipe = () => {
    wipeMutation.mutate({
      confirmation_phrase: confirmPhrase,
      preserve_admin_users: preserveAdmins,
      preserve_events: preserveEvents,
    })
  }

  const handleSeed = () => {
    seedMutation.mutate(seedConfig)
  }

  if (isLoadingPreview) {
    return <Loading />
  }

  return (
    <div className="space-y-6">
      {/* Wipe Preview */}
      <div className="bg-white rounded-lg shadow p-6">
        <div className="flex items-center gap-3 mb-4">
          <Trash2 className="text-red-500" size={24} />
          <h2 className="text-xl font-semibold text-gray-900">Data Wiper</h2>
        </div>

        <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-4">
          <div className="flex items-start gap-3">
            <AlertTriangle className="text-red-500 flex-shrink-0 mt-0.5" size={20} />
            <div>
              <p className="text-red-800 font-medium">Danger Zone</p>
              <p className="text-red-600 text-sm">
                This action will permanently delete data from the database. Admin users and settings are preserved by default.
              </p>
            </div>
          </div>
        </div>

        {wipePreview && (
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
            <div className="bg-gray-50 rounded-lg p-3">
              <p className="text-gray-600 text-sm">Users</p>
              <p className="text-2xl font-bold text-gray-900">{wipePreview.users_count}</p>
            </div>
            <div className="bg-gray-50 rounded-lg p-3">
              <p className="text-gray-600 text-sm">Spread Bets</p>
              <p className="text-2xl font-bold text-gray-900">{wipePreview.spread_bets_count}</p>
            </div>
            <div className="bg-gray-50 rounded-lg p-3">
              <p className="text-gray-600 text-sm">Events</p>
              <p className="text-2xl font-bold text-gray-900">{wipePreview.events_count}</p>
            </div>
            <div className="bg-gray-50 rounded-lg p-3">
              <p className="text-gray-600 text-sm">Transactions</p>
              <p className="text-2xl font-bold text-gray-900">{wipePreview.transactions_count}</p>
            </div>
          </div>
        )}

        {wipePreview && !wipePreview.can_wipe && (
          <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-4">
            <p className="text-yellow-800">
              Cooldown active. Please wait {wipePreview.cooldown_remaining_seconds} seconds before wiping again.
            </p>
          </div>
        )}

        <Button
          variant="secondary"
          onClick={() => setShowWipeModal(true)}
          disabled={!wipePreview?.can_wipe}
          className="bg-red-600 hover:bg-red-700 text-white border-red-600"
        >
          <Trash2 size={18} className="mr-2" />
          Wipe Database
        </Button>
      </div>

      {/* Wipe Confirmation Modal */}
      {showWipeModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl max-w-md w-full mx-4 p-6">
            <h3 className="text-xl font-bold text-red-600 mb-4">Confirm Database Wipe</h3>

            <div className="space-y-4 mb-6">
              <label className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={preserveAdmins}
                  onChange={(e) => setPreserveAdmins(e.target.checked)}
                  className="rounded"
                />
                <span className="text-gray-700">Preserve admin users</span>
              </label>

              <label className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={preserveEvents}
                  onChange={(e) => setPreserveEvents(e.target.checked)}
                  className="rounded"
                />
                <span className="text-gray-700">Preserve events (delete bets only)</span>
              </label>

              <div>
                <label className="block text-gray-700 font-medium mb-2">
                  Type <span className="font-mono bg-gray-100 px-2 py-1 rounded">CONFIRM WIPE</span> to proceed:
                </label>
                <input
                  type="text"
                  value={confirmPhrase}
                  onChange={(e) => setConfirmPhrase(e.target.value)}
                  placeholder="CONFIRM WIPE"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-red-500 focus:border-transparent"
                />
              </div>
            </div>

            <div className="flex gap-3">
              <Button
                variant="secondary"
                onClick={() => {
                  setShowWipeModal(false)
                  setConfirmPhrase('')
                }}
                className="flex-1"
              >
                Cancel
              </Button>
              <Button
                onClick={handleWipe}
                disabled={confirmPhrase !== 'CONFIRM WIPE' || wipeMutation.isPending}
                className="flex-1 bg-red-600 hover:bg-red-700"
              >
                {wipeMutation.isPending ? 'Wiping...' : 'Wipe Data'}
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* Seeder */}
      <div className="bg-white rounded-lg shadow p-6">
        <div className="flex items-center gap-3 mb-4">
          <Database className="text-blue-500" size={24} />
          <h2 className="text-xl font-semibold text-gray-900">Data Seeder</h2>
        </div>

        <p className="text-gray-600 mb-4">
          Populate the database with test data for development and testing.
        </p>

        <div className="grid grid-cols-2 md:grid-cols-3 gap-4 mb-6">
          <div>
            <label className="block text-gray-700 text-sm font-medium mb-1">Number of Users</label>
            <input
              type="number"
              value={seedConfig.num_users}
              onChange={(e) => setSeedConfig({ ...seedConfig, num_users: Math.max(1, parseInt(e.target.value) || 1) })}
              min={1}
              max={100}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg"
            />
          </div>

          <div>
            <label className="block text-gray-700 text-sm font-medium mb-1">Number of Events</label>
            <input
              type="number"
              value={seedConfig.num_events}
              onChange={(e) => setSeedConfig({ ...seedConfig, num_events: Math.max(0, parseInt(e.target.value) || 0) })}
              min={0}
              max={50}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg"
            />
          </div>

          <div>
            <label className="block text-gray-700 text-sm font-medium mb-1">Bets per Event</label>
            <input
              type="number"
              value={seedConfig.num_bets_per_event}
              onChange={(e) => setSeedConfig({ ...seedConfig, num_bets_per_event: Math.max(0, parseInt(e.target.value) || 0) })}
              min={0}
              max={20}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg"
            />
          </div>

          <div>
            <label className="block text-gray-700 text-sm font-medium mb-1">Starting Balance</label>
            <input
              type="number"
              value={seedConfig.starting_balance}
              onChange={(e) => setSeedConfig({ ...seedConfig, starting_balance: parseInt(e.target.value) || 100 })}
              min={100}
              max={10000}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg"
            />
          </div>

          <div className="flex items-end">
            <label className="flex items-center gap-2">
              <input
                type="checkbox"
                checked={seedConfig.create_admin}
                onChange={(e) => setSeedConfig({ ...seedConfig, create_admin: e.target.checked })}
                className="rounded"
              />
              <span className="text-gray-700">Create test admin</span>
            </label>
          </div>
        </div>

        <Button onClick={handleSeed} disabled={seedMutation.isPending}>
          <RefreshCw size={18} className={`mr-2 ${seedMutation.isPending ? 'animate-spin' : ''}`} />
          {seedMutation.isPending ? 'Seeding...' : 'Seed Database'}
        </Button>
      </div>
    </div>
  )
}
