import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Layout } from '@/components/layout/Layout'
import { Loading } from '@/components/common/Loading'
import { adminApi } from '@/api/admin'
import { AdminDataTools } from '@/components/admin/AdminDataTools'
import { AdminSimulation } from '@/components/admin/AdminSimulation'
import { AdminUsers } from '@/components/admin/AdminUsers'
import { AdminAuditLog } from '@/components/admin/AdminAuditLog'
import {
  LayoutDashboard,
  Users,
  Calendar,
  Database,
  Activity,
  ClipboardList,
  Settings,
  TrendingUp,
  DollarSign,
  Percent,
} from 'lucide-react'

type TabType = 'dashboard' | 'users' | 'events' | 'data' | 'simulation' | 'audit'

export const Admin = () => {
  const [activeTab, setActiveTab] = useState<TabType>('dashboard')

  const { data: dashboard, isLoading: isDashboardLoading } = useQuery({
    queryKey: ['admin-dashboard'],
    queryFn: adminApi.getDashboard,
  })

  const { data: settings } = useQuery({
    queryKey: ['admin-settings'],
    queryFn: adminApi.getSettings,
  })

  const tabs: { id: TabType; label: string; icon: React.ReactNode }[] = [
    { id: 'dashboard', label: 'Dashboard', icon: <LayoutDashboard size={18} /> },
    { id: 'users', label: 'Users', icon: <Users size={18} /> },
    { id: 'events', label: 'Events', icon: <Calendar size={18} /> },
    { id: 'data', label: 'Data Tools', icon: <Database size={18} /> },
    { id: 'simulation', label: 'Simulation', icon: <Activity size={18} /> },
    { id: 'audit', label: 'Audit Log', icon: <ClipboardList size={18} /> },
  ]

  return (
    <Layout>
      <div className="space-y-6">
        {/* Header */}
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">Admin Panel</h1>
            <p className="text-gray-600 mt-1">Manage the H2H platform</p>
          </div>
          {dashboard?.simulation_running && (
            <div className="flex items-center gap-2 px-4 py-2 bg-green-100 text-green-800 rounded-lg">
              <Activity size={18} className="animate-pulse" />
              <span className="font-medium">Simulation Running</span>
            </div>
          )}
        </div>

        {/* Tabs */}
        <div className="bg-white rounded-lg shadow">
          <div className="flex border-b overflow-x-auto">
            {tabs.map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`flex items-center gap-2 px-6 py-4 text-sm font-medium whitespace-nowrap transition-colors ${
                  activeTab === tab.id
                    ? 'text-blue-600 border-b-2 border-blue-600 bg-blue-50/50'
                    : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                }`}
              >
                {tab.icon}
                {tab.label}
              </button>
            ))}
          </div>
        </div>

        {/* Tab Content */}
        <div>
          {activeTab === 'dashboard' && (
            <DashboardTab dashboard={dashboard} settings={settings} isLoading={isDashboardLoading} />
          )}
          {activeTab === 'users' && <AdminUsers />}
          {activeTab === 'events' && <EventsTab />}
          {activeTab === 'data' && <AdminDataTools />}
          {activeTab === 'simulation' && <AdminSimulation />}
          {activeTab === 'audit' && <AdminAuditLog />}
        </div>
      </div>
    </Layout>
  )
}

// Dashboard Tab Component
const DashboardTab = ({
  dashboard,
  settings,
  isLoading,
}: {
  dashboard: any
  settings: any
  isLoading: boolean
}) => {
  if (isLoading) {
    return <Loading />
  }

  return (
    <div className="space-y-6">
      {/* Stats Grid */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <StatCard
          title="Total Users"
          value={dashboard?.total_users || 0}
          subtitle={`${dashboard?.active_users || 0} active`}
          icon={<Users className="text-blue-500" size={24} />}
        />
        <StatCard
          title="Total Events"
          value={dashboard?.total_events || 0}
          subtitle={`${dashboard?.upcoming_events || 0} upcoming`}
          icon={<Calendar className="text-green-500" size={24} />}
        />
        <StatCard
          title="Total Bets"
          value={dashboard?.total_bets || 0}
          subtitle={`${dashboard?.open_bets || 0} open, ${dashboard?.matched_bets || 0} matched`}
          icon={<TrendingUp className="text-purple-500" size={24} />}
        />
        <StatCard
          title="Total Volume"
          value={`$${(dashboard?.total_volume || 0).toLocaleString()}`}
          subtitle={`$${(dashboard?.escrow_locked || 0).toLocaleString()} in escrow`}
          icon={<DollarSign className="text-yellow-500" size={24} />}
        />
      </div>

      {/* Settings */}
      {settings && (
        <div className="bg-white rounded-lg shadow p-6">
          <div className="flex items-center gap-3 mb-4">
            <Settings className="text-gray-400" size={24} />
            <h2 className="text-xl font-semibold text-gray-900">Platform Settings</h2>
          </div>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className="bg-gray-50 rounded-lg p-3">
              <div className="flex items-center gap-2 text-gray-600 text-sm mb-1">
                <Percent size={14} />
                <span>House Commission</span>
              </div>
              <p className="text-xl font-bold text-gray-900">{settings.default_house_commission_percent}%</p>
            </div>
            <div className="bg-gray-50 rounded-lg p-3">
              <p className="text-gray-600 text-sm mb-1">Min Bet</p>
              <p className="text-xl font-bold text-gray-900">${settings.default_min_bet_amount}</p>
            </div>
            <div className="bg-gray-50 rounded-lg p-3">
              <p className="text-gray-600 text-sm mb-1">Max Bet</p>
              <p className="text-xl font-bold text-gray-900">${settings.default_max_bet_amount}</p>
            </div>
            <div className="bg-gray-50 rounded-lg p-3">
              <p className="text-gray-600 text-sm mb-1">Spread Range</p>
              <p className="text-xl font-bold text-gray-900">
                {settings.default_min_spread} to {settings.default_max_spread}
              </p>
            </div>
          </div>
        </div>
      )}

      {/* Quick Stats */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div className="bg-white rounded-lg shadow p-6">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">User Status</h3>
          <div className="space-y-3">
            <div className="flex justify-between items-center">
              <span className="text-gray-600">Active</span>
              <span className="font-semibold text-green-600">{dashboard?.active_users || 0}</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-gray-600">Suspended</span>
              <span className="font-semibold text-red-600">{dashboard?.suspended_users || 0}</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-gray-600">Admins</span>
              <span className="font-semibold text-blue-600">{dashboard?.admin_users || 0}</span>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-lg shadow p-6">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Event Status</h3>
          <div className="space-y-3">
            <div className="flex justify-between items-center">
              <span className="text-gray-600">Upcoming</span>
              <span className="font-semibold text-blue-600">{dashboard?.upcoming_events || 0}</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-gray-600">Live</span>
              <span className="font-semibold text-green-600">{dashboard?.live_events || 0}</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-gray-600">Total</span>
              <span className="font-semibold text-gray-900">{dashboard?.total_events || 0}</span>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-lg shadow p-6">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Bet Status</h3>
          <div className="space-y-3">
            <div className="flex justify-between items-center">
              <span className="text-gray-600">Open</span>
              <span className="font-semibold text-yellow-600">{dashboard?.open_bets || 0}</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-gray-600">Matched</span>
              <span className="font-semibold text-green-600">{dashboard?.matched_bets || 0}</span>
            </div>
            <div className="flex justify-between items-center">
              <span className="text-gray-600">Total</span>
              <span className="font-semibold text-gray-900">{dashboard?.total_bets || 0}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

// Stat Card Component
const StatCard = ({
  title,
  value,
  subtitle,
  icon,
}: {
  title: string
  value: string | number
  subtitle: string
  icon: React.ReactNode
}) => (
  <div className="bg-white rounded-lg shadow p-6">
    <div className="flex items-center justify-between mb-2">
      <span className="text-gray-600 text-sm">{title}</span>
      {icon}
    </div>
    <p className="text-2xl font-bold text-gray-900">{value}</p>
    <p className="text-sm text-gray-500 mt-1">{subtitle}</p>
  </div>
)

// Events Tab Component (keeping existing functionality)
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { Button } from '@/components/common/Button'
import { Input } from '@/components/common/Input'
import { SportType } from '@/types/sport-event'
import { toast } from 'react-hot-toast'
import { Plus, Trash2 } from 'lucide-react'
import type { CreateEventData } from '@/api/admin'

const EventsTab = () => {
  const queryClient = useQueryClient()
  const [showCreateForm, setShowCreateForm] = useState(false)
  const [formData, setFormData] = useState<CreateEventData>({
    sport: SportType.FOOTBALL,
    home_team: '',
    away_team: '',
    official_spread: 0,
    game_time: '',
    venue: '',
    league: '',
  })

  const { data: events, isLoading } = useQuery({
    queryKey: ['admin-events'],
    queryFn: () => adminApi.getEvents(),
  })

  const createEventMutation = useMutation({
    mutationFn: adminApi.createEvent,
    onSuccess: () => {
      toast.success('Event created successfully!')
      queryClient.invalidateQueries({ queryKey: ['admin-events'] })
      queryClient.invalidateQueries({ queryKey: ['sport-events'] })
      queryClient.invalidateQueries({ queryKey: ['admin-dashboard'] })
      setShowCreateForm(false)
      setFormData({
        sport: SportType.FOOTBALL,
        home_team: '',
        away_team: '',
        official_spread: 0,
        game_time: '',
        venue: '',
        league: '',
      })
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.detail || 'Failed to create event')
    },
  })

  const deleteEventMutation = useMutation({
    mutationFn: adminApi.deleteEvent,
    onSuccess: () => {
      toast.success('Event deleted successfully!')
      queryClient.invalidateQueries({ queryKey: ['admin-events'] })
      queryClient.invalidateQueries({ queryKey: ['sport-events'] })
      queryClient.invalidateQueries({ queryKey: ['admin-dashboard'] })
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.detail || 'Failed to delete event')
    },
  })

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    createEventMutation.mutate(formData)
  }

  const handleDelete = (eventId: number) => {
    if (window.confirm('Are you sure you want to delete this event?')) {
      deleteEventMutation.mutate(eventId)
    }
  }

  return (
    <div className="space-y-6">
      {/* Create Button */}
      <div className="flex justify-end">
        <Button onClick={() => setShowCreateForm(!showCreateForm)}>
          <Plus size={20} className="mr-2" />
          {showCreateForm ? 'Cancel' : 'Create Event'}
        </Button>
      </div>

      {/* Create Form */}
      {showCreateForm && (
        <div className="bg-white p-6 rounded-lg shadow">
          <h2 className="text-xl font-semibold mb-4">Create New Event</h2>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Sport</label>
                <select
                  value={formData.sport}
                  onChange={(e) => setFormData({ ...formData, sport: e.target.value as SportType })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent"
                >
                  {Object.values(SportType).map((sport) => (
                    <option key={sport} value={sport}>
                      {sport.charAt(0).toUpperCase() + sport.slice(1)}
                    </option>
                  ))}
                </select>
              </div>

              <Input
                label="League"
                value={formData.league || ''}
                onChange={(e) => setFormData({ ...formData, league: e.target.value })}
                placeholder="e.g., NFL, NBA, NCAA"
              />

              <Input
                label="Home Team"
                value={formData.home_team}
                onChange={(e) => setFormData({ ...formData, home_team: e.target.value })}
                required
              />

              <Input
                label="Away Team"
                value={formData.away_team}
                onChange={(e) => setFormData({ ...formData, away_team: e.target.value })}
                required
              />

              <Input
                label="Official Spread"
                type="number"
                step="0.5"
                value={formData.official_spread}
                onChange={(e) => setFormData({ ...formData, official_spread: parseFloat(e.target.value) })}
                required
              />

              <Input
                label="Game Time"
                type="datetime-local"
                value={formData.game_time}
                onChange={(e) => setFormData({ ...formData, game_time: e.target.value })}
                required
              />

              <Input
                label="Venue"
                value={formData.venue || ''}
                onChange={(e) => setFormData({ ...formData, venue: e.target.value })}
                placeholder="Stadium/Arena name"
              />
            </div>

            <div className="flex gap-3 pt-4">
              <Button
                type="button"
                variant="secondary"
                onClick={() => setShowCreateForm(false)}
                disabled={createEventMutation.isPending}
                className="flex-1"
              >
                Cancel
              </Button>
              <Button type="submit" disabled={createEventMutation.isPending} className="flex-1">
                {createEventMutation.isPending ? 'Creating...' : 'Create Event'}
              </Button>
            </div>
          </form>
        </div>
      )}

      {/* Events List */}
      <div className="bg-white rounded-lg shadow">
        <div className="p-6 border-b border-gray-200">
          <h2 className="text-xl font-semibold">All Events</h2>
        </div>

        {isLoading ? (
          <div className="p-6">
            <Loading />
          </div>
        ) : !events || events.length === 0 ? (
          <div className="p-6 text-center text-gray-600">No events created yet</div>
        ) : (
          <div className="divide-y divide-gray-200">
            {events.map((event) => (
              <div key={event.id} className="p-6 hover:bg-gray-50 transition-colors">
                <div className="flex justify-between items-start">
                  <div className="flex-1">
                    <div className="flex items-center gap-3 mb-2">
                      <span className="px-2 py-1 bg-blue-100 text-blue-800 rounded text-xs font-semibold uppercase">
                        {event.sport}
                      </span>
                      <span className="px-2 py-1 bg-gray-100 text-gray-700 rounded text-xs">
                        {event.status}
                      </span>
                    </div>

                    <h3 className="font-bold text-lg text-gray-900">
                      {event.home_team} vs {event.away_team}
                    </h3>

                    <div className="mt-2 grid grid-cols-2 md:grid-cols-4 gap-2 text-sm text-gray-600">
                      <div>
                        <span className="font-medium">Spread:</span> {event.home_team}{' '}
                        {event.official_spread > 0 ? '+' : ''}
                        {event.official_spread}
                      </div>
                      <div>
                        <span className="font-medium">Time:</span>{' '}
                        {new Date(event.game_time).toLocaleString()}
                      </div>
                      {event.venue && (
                        <div>
                          <span className="font-medium">Venue:</span> {event.venue}
                        </div>
                      )}
                      {event.league && (
                        <div>
                          <span className="font-medium">League:</span> {event.league}
                        </div>
                      )}
                    </div>
                  </div>

                  <Button
                    variant="secondary"
                    onClick={() => handleDelete(event.id)}
                    disabled={deleteEventMutation.isPending}
                    className="ml-4"
                  >
                    <Trash2 size={18} />
                  </Button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
