import { useState, useEffect } 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 { Play, Square, Settings, Activity } from 'lucide-react'
import toast from 'react-hot-toast'
import type { SimulationConfig } from '@/types/admin'

export const AdminSimulation = () => {
  const queryClient = useQueryClient()
  const [showConfig, setShowConfig] = useState(false)
  const [config, setConfig] = useState<SimulationConfig>({
    delay_seconds: 2.0,
    actions_per_iteration: 3,
    create_users: true,
    create_bets: true,
    take_bets: true,
    add_comments: true,
    cancel_bets: true,
  })

  const { data: status, isLoading, refetch } = useQuery({
    queryKey: ['simulation-status'],
    queryFn: adminApi.getSimulationStatus,
    refetchInterval: (query) => (query.state.data?.is_running ? 2000 : false),
  })

  // Update config when status loads
  useEffect(() => {
    if (status?.config) {
      setConfig(status.config)
    }
  }, [status?.config])

  const startMutation = useMutation({
    mutationFn: () => adminApi.startSimulation(config),
    onSuccess: (data) => {
      toast.success(data.message)
      queryClient.invalidateQueries({ queryKey: ['simulation-status'] })
      queryClient.invalidateQueries({ queryKey: ['admin-dashboard'] })
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.detail || 'Failed to start simulation')
    },
  })

  const stopMutation = useMutation({
    mutationFn: adminApi.stopSimulation,
    onSuccess: (data) => {
      toast.success(`${data.message} (${data.total_iterations} iterations, ${data.ran_for_seconds.toFixed(1)}s)`)
      queryClient.invalidateQueries({ queryKey: ['simulation-status'] })
      queryClient.invalidateQueries({ queryKey: ['admin-dashboard'] })
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.detail || 'Failed to stop simulation')
    },
  })

  if (isLoading) {
    return <Loading />
  }

  return (
    <div className="space-y-6">
      {/* Status Card */}
      <div className="bg-white rounded-lg shadow p-6">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-3">
            <Activity className={status?.is_running ? 'text-green-500 animate-pulse' : 'text-gray-400'} size={24} />
            <h2 className="text-xl font-semibold text-gray-900">Activity Simulation</h2>
          </div>
          <span
            className={`px-3 py-1 rounded-full text-sm font-medium ${
              status?.is_running ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-600'
            }`}
          >
            {status?.is_running ? 'Running' : 'Stopped'}
          </span>
        </div>

        <p className="text-gray-600 mb-6">
          Simulate random user activity including creating users, placing bets, matching bets, and adding comments.
        </p>

        {status?.is_running && (
          <div className="bg-green-50 border border-green-200 rounded-lg p-4 mb-6">
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div>
                <p className="text-gray-600 text-sm">Started By</p>
                <p className="font-semibold text-gray-900">{status.started_by}</p>
              </div>
              <div>
                <p className="text-gray-600 text-sm">Iterations</p>
                <p className="font-semibold text-gray-900">{status.iterations_completed}</p>
              </div>
              <div>
                <p className="text-gray-600 text-sm">Started At</p>
                <p className="font-semibold text-gray-900">
                  {status.started_at ? new Date(status.started_at).toLocaleTimeString() : '-'}
                </p>
              </div>
              <div>
                <p className="text-gray-600 text-sm">Last Activity</p>
                <p className="font-semibold text-gray-900 truncate">{status.last_activity || '-'}</p>
              </div>
            </div>
          </div>
        )}

        <div className="flex gap-3">
          {status?.is_running ? (
            <Button
              onClick={() => stopMutation.mutate()}
              disabled={stopMutation.isPending}
              className="bg-red-600 hover:bg-red-700"
            >
              <Square size={18} className="mr-2" />
              {stopMutation.isPending ? 'Stopping...' : 'Stop Simulation'}
            </Button>
          ) : (
            <>
              <Button onClick={() => startMutation.mutate()} disabled={startMutation.isPending}>
                <Play size={18} className="mr-2" />
                {startMutation.isPending ? 'Starting...' : 'Start Simulation'}
              </Button>
              <Button variant="secondary" onClick={() => setShowConfig(!showConfig)}>
                <Settings size={18} className="mr-2" />
                Configure
              </Button>
            </>
          )}
        </div>
      </div>

      {/* Configuration */}
      {showConfig && !status?.is_running && (
        <div className="bg-white rounded-lg shadow p-6">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Simulation Configuration</h3>

          <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">Delay (seconds)</label>
              <input
                type="number"
                value={config.delay_seconds}
                onChange={(e) => setConfig({ ...config, delay_seconds: parseFloat(e.target.value) || 0.5 })}
                min={0.5}
                max={30}
                step={0.5}
                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">Actions per Iteration</label>
              <input
                type="number"
                value={config.actions_per_iteration}
                onChange={(e) => setConfig({ ...config, actions_per_iteration: parseInt(e.target.value) || 1 })}
                min={1}
                max={10}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg"
              />
            </div>
          </div>

          <div className="space-y-3">
            <p className="text-gray-700 font-medium">Enabled Actions:</p>
            <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
              <label className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={config.create_users}
                  onChange={(e) => setConfig({ ...config, create_users: e.target.checked })}
                  className="rounded"
                />
                <span className="text-gray-700">Create Users</span>
              </label>

              <label className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={config.create_bets}
                  onChange={(e) => setConfig({ ...config, create_bets: e.target.checked })}
                  className="rounded"
                />
                <span className="text-gray-700">Create Bets</span>
              </label>

              <label className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={config.take_bets}
                  onChange={(e) => setConfig({ ...config, take_bets: e.target.checked })}
                  className="rounded"
                />
                <span className="text-gray-700">Take/Match Bets</span>
              </label>

              <label className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={config.add_comments}
                  onChange={(e) => setConfig({ ...config, add_comments: e.target.checked })}
                  className="rounded"
                />
                <span className="text-gray-700">Add Comments</span>
              </label>

              <label className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={config.cancel_bets}
                  onChange={(e) => setConfig({ ...config, cancel_bets: e.target.checked })}
                  className="rounded"
                />
                <span className="text-gray-700">Cancel Bets</span>
              </label>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
