import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Layout } from '@/components/layout/Layout'
import { Button } from '@/components/common/Button'
import { Input } from '@/components/common/Input'
import { Loading } from '@/components/common/Loading'
import { adminApi, type CreateEventData } from '@/api/admin'
import { SportType } from '@/types/sport-event'
import { toast } from 'react-hot-toast'
import { Plus, Trash2 } from 'lucide-react'

export const Admin = () => {
  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: settings } = useQuery({
    queryKey: ['admin-settings'],
    queryFn: adminApi.getSettings,
  })

  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'] })
      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'] })
    },
    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 (
    <Layout>
      <div className="space-y-6">
        <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-2">Manage sporting events and platform settings</p>
          </div>
          <Button onClick={() => setShowCreateForm(!showCreateForm)}>
            <Plus size={20} className="mr-2" />
            {showCreateForm ? 'Cancel' : 'Create Event'}
          </Button>
        </div>

        {settings && (
          <div className="bg-white p-6 rounded-lg shadow">
            <h2 className="text-xl font-semibold mb-4">Platform Settings</h2>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
              <div>
                <p className="text-gray-600">House Commission</p>
                <p className="font-semibold">{settings.default_house_commission_percent}%</p>
              </div>
              <div>
                <p className="text-gray-600">Min Bet</p>
                <p className="font-semibold">${settings.default_min_bet_amount}</p>
              </div>
              <div>
                <p className="text-gray-600">Max Bet</p>
                <p className="font-semibold">${settings.default_max_bet_amount}</p>
              </div>
              <div>
                <p className="text-gray-600">Spread Range</p>
                <p className="font-semibold">
                  {settings.default_min_spread} to {settings.default_max_spread}
                </p>
              </div>
            </div>
          </div>
        )}

        {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>
        )}

        <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>
    </Layout>
  )
}
