import { useState } from 'react'
import { Link } from 'react-router-dom'
import { useAuthStore } from '@/store'
import type { SportEventWithBets, SpreadGridBet } from '@/types/sport-event'
import { CreateSpreadBetModal } from './CreateSpreadBetModal'
import { TakeBetModal } from './TakeBetModal'
import { Button } from '@/components/common/Button'

interface SpreadGridProps {
  event: SportEventWithBets
  onBetCreated?: () => void
  onBetTaken?: () => void
}

interface SpreadDetailModalProps {
  isOpen: boolean
  onClose: () => void
  spread: number
  bets: SpreadGridBet[]
  event: SportEventWithBets
  onCreateBet: () => void
  onTakeBet: (betId: number) => void
  isAuthenticated: boolean
}

const SpreadDetailModal = ({
  isOpen,
  onClose,
  spread,
  bets,
  event,
  onCreateBet,
  onTakeBet,
  isAuthenticated,
}: SpreadDetailModalProps) => {
  if (!isOpen) return null

  const openBets = bets.filter((b) => b.status === 'open')
  const matchedBets = bets.filter((b) => b.status === 'matched')
  const takeable = openBets.filter((b) => b.can_take)

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg shadow-xl max-w-lg w-full max-h-[80vh] overflow-hidden">
        <div className="p-4 border-b bg-gray-50">
          <div className="flex justify-between items-center">
            <h3 className="text-lg font-semibold">
              Spread: {spread > 0 ? '+' : ''}{spread}
            </h3>
            <button
              onClick={onClose}
              className="text-gray-500 hover:text-gray-700 text-2xl leading-none"
            >
              ×
            </button>
          </div>
          <p className="text-sm text-gray-600 mt-1">
            {event.home_team} vs {event.away_team}
          </p>
        </div>

        <div className="p-4 overflow-y-auto max-h-[50vh]">
          {/* Login prompt for non-authenticated users */}
          {!isAuthenticated ? (
            <div className="text-center py-6">
              <div className="bg-blue-50 rounded-lg p-6 mb-4">
                <h4 className="text-lg font-semibold text-gray-900 mb-2">
                  Login to Bet
                </h4>
                <p className="text-gray-600 mb-4">
                  Create an account or log in to place bets at this spread
                </p>
                <div className="flex gap-3 justify-center">
                  <Link to="/login">
                    <Button variant="secondary">Log In</Button>
                  </Link>
                  <Link to="/register">
                    <Button>Sign Up</Button>
                  </Link>
                </div>
              </div>

              {/* Still show existing bets for visibility */}
              {bets.length > 0 && (
                <div className="mt-4 text-left">
                  <h4 className="font-medium text-gray-700 mb-2 text-sm">
                    Current Bets at this Spread ({bets.length})
                  </h4>
                  <div className="space-y-2">
                    {bets.slice(0, 3).map((bet) => (
                      <div
                        key={bet.bet_id}
                        className="p-3 bg-gray-50 border border-gray-200 rounded-lg text-sm"
                      >
                        <span className="font-medium">${bet.stake.toFixed(2)}</span>
                        <span className="text-gray-500 ml-2">by {bet.creator_username}</span>
                        <span className={`ml-2 px-2 py-0.5 rounded-full text-xs ${
                          bet.status === 'open' ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'
                        }`}>
                          {bet.status}
                        </span>
                      </div>
                    ))}
                    {bets.length > 3 && (
                      <p className="text-xs text-gray-500 text-center">
                        +{bets.length - 3} more bet{bets.length - 3 !== 1 ? 's' : ''}
                      </p>
                    )}
                  </div>
                </div>
              )}
            </div>
          ) : (
            <>
              {/* Create new bet button */}
              <button
                onClick={onCreateBet}
                className="w-full mb-4 py-3 px-4 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium"
              >
                + Create New Bet at {spread > 0 ? '+' : ''}{spread}
              </button>

          {/* Available bets to take */}
          {takeable.length > 0 && (
            <div className="mb-4">
              <h4 className="font-medium text-gray-700 mb-2">
                Available to Take ({takeable.length})
              </h4>
              <div className="space-y-2">
                {takeable.map((bet) => (
                  <div
                    key={bet.bet_id}
                    className="flex items-center justify-between p-3 bg-green-50 border border-green-200 rounded-lg"
                  >
                    <div>
                      <p className="font-medium text-gray-900">
                        ${bet.stake.toFixed(2)}
                      </p>
                      <p className="text-sm text-gray-600">
                        by {bet.creator_username}
                      </p>
                    </div>
                    <button
                      onClick={() => onTakeBet(bet.bet_id)}
                      className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors text-sm font-medium"
                    >
                      Take Bet
                    </button>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Your open bets */}
          {openBets.filter((b) => !b.can_take).length > 0 && (
            <div className="mb-4">
              <h4 className="font-medium text-gray-700 mb-2">Your Open Bets</h4>
              <div className="space-y-2">
                {openBets
                  .filter((b) => !b.can_take)
                  .map((bet) => (
                    <div
                      key={bet.bet_id}
                      className="flex items-center justify-between p-3 bg-blue-50 border border-blue-200 rounded-lg"
                    >
                      <div>
                        <p className="font-medium text-gray-900">
                          ${bet.stake.toFixed(2)}
                        </p>
                        <p className="text-sm text-gray-600">Waiting for opponent</p>
                      </div>
                      <span className="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm">
                        Open
                      </span>
                    </div>
                  ))}
              </div>
            </div>
          )}

          {/* Matched bets */}
          {matchedBets.length > 0 && (
            <div>
              <h4 className="font-medium text-gray-700 mb-2">
                Matched Bets ({matchedBets.length})
              </h4>
              <div className="space-y-2">
                {matchedBets.map((bet) => (
                  <div
                    key={bet.bet_id}
                    className="flex items-center justify-between p-3 bg-gray-50 border border-gray-200 rounded-lg"
                  >
                    <div>
                      <p className="font-medium text-gray-900">
                        ${bet.stake.toFixed(2)}
                      </p>
                      <p className="text-sm text-gray-600">
                        by {bet.creator_username}
                      </p>
                    </div>
                    <span className="px-3 py-1 bg-yellow-100 text-yellow-800 rounded-full text-sm">
                      Matched
                    </span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {bets.length === 0 && (
            <p className="text-center text-gray-500 py-4">
              No bets at this spread yet. Be the first!
            </p>
          )}
            </>
          )}
        </div>
      </div>
    </div>
  )
}

export const SpreadGrid = ({ event, onBetCreated, onBetTaken }: SpreadGridProps) => {
  const { isAuthenticated } = useAuthStore()
  const [selectedSpread, setSelectedSpread] = useState<number | null>(null)
  const [isDetailModalOpen, setIsDetailModalOpen] = useState(false)
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false)
  const [selectedBetId, setSelectedBetId] = useState<number | null>(null)
  const [isTakeModalOpen, setIsTakeModalOpen] = useState(false)

  const handleSpreadClick = (spread: number) => {
    setSelectedSpread(spread)
    setIsDetailModalOpen(true)
  }

  const handleCreateBet = () => {
    setIsDetailModalOpen(false)
    setIsCreateModalOpen(true)
  }

  const handleTakeBet = (betId: number) => {
    setSelectedBetId(betId)
    setIsDetailModalOpen(false)
    setIsTakeModalOpen(true)
  }

  const handleCreateBetClose = () => {
    setIsCreateModalOpen(false)
    setSelectedSpread(null)
    onBetCreated?.()
  }

  const handleTakeBetClose = () => {
    setIsTakeModalOpen(false)
    setSelectedBetId(null)
    setSelectedSpread(null)
    onBetTaken?.()
  }

  const handleDetailModalClose = () => {
    setIsDetailModalOpen(false)
    setSelectedSpread(null)
  }

  const sortedSpreads = Object.keys(event.spread_grid)
    .map(Number)
    .sort((a, b) => a - b)

  return (
    <div className="space-y-6">
      <div className="bg-white p-6 rounded-lg shadow">
        <div className="mb-4">
          <h3 className="text-xl font-semibold text-gray-900">
            {event.home_team} vs {event.away_team}
          </h3>
          <p className="text-gray-600 mt-1">
            Official Line: {event.home_team} {event.official_spread > 0 ? '+' : ''}
            {event.official_spread} / {event.away_team}{' '}
            {-event.official_spread > 0 ? '+' : ''}
            {-event.official_spread}
          </p>
          <p className="text-sm text-gray-500 mt-1">
            {new Date(event.game_time).toLocaleString()}
          </p>
        </div>

        <div className="grid grid-cols-4 sm:grid-cols-6 md:grid-cols-8 lg:grid-cols-10 gap-2">
          {sortedSpreads.map((spread) => {
            const bets = event.spread_grid[spread.toString()] || []
            const isOfficialLine = spread === event.official_spread
            const openBets = bets.filter((b) => b.status === 'open')
            const takeableBets = openBets.filter((b) => b.can_take)
            const hasActivity = bets.length > 0

            return (
              <button
                key={spread}
                onClick={() => handleSpreadClick(spread)}
                className={`
                  relative p-3 rounded-lg border-2 transition-all cursor-pointer
                  ${
                    isOfficialLine
                      ? 'border-yellow-400 bg-yellow-50'
                      : 'border-gray-200'
                  }
                  ${
                    takeableBets.length > 0
                      ? 'bg-green-50 hover:bg-green-100 border-green-300'
                      : hasActivity
                      ? 'bg-blue-50 hover:bg-blue-100 border-blue-200'
                      : 'bg-white hover:bg-gray-50'
                  }
                `}
              >
                <div className="text-center">
                  <div className="font-bold text-lg">
                    {spread > 0 ? '+' : ''}
                    {spread}
                  </div>
                  {hasActivity && (
                    <div className="mt-1">
                      {takeableBets.length > 0 ? (
                        <div className="text-xs font-semibold text-green-600">
                          {takeableBets.length} open
                        </div>
                      ) : (
                        <div className="text-xs text-gray-500">
                          {bets.length} bet{bets.length !== 1 ? 's' : ''}
                        </div>
                      )}
                    </div>
                  )}
                  {isOfficialLine && (
                    <div className="absolute -top-1 -right-1">
                      <span className="inline-block px-1 py-0.5 text-xs font-bold bg-yellow-400 text-yellow-900 rounded">
                        ★
                      </span>
                    </div>
                  )}
                </div>
              </button>
            )
          })}
        </div>

        <div className="mt-4 p-4 bg-gray-50 rounded-lg">
          <h4 className="font-semibold text-sm text-gray-700 mb-2">Legend:</h4>
          <div className="grid grid-cols-1 sm:grid-cols-4 gap-2 text-xs">
            <div className="flex items-center gap-2">
              <div className="w-6 h-6 bg-white border-2 border-gray-200 rounded"></div>
              <span>No bets</span>
            </div>
            <div className="flex items-center gap-2">
              <div className="w-6 h-6 bg-green-50 border-2 border-green-300 rounded"></div>
              <span>Open bets available</span>
            </div>
            <div className="flex items-center gap-2">
              <div className="w-6 h-6 bg-blue-50 border-2 border-blue-200 rounded"></div>
              <span>Has bets (yours/matched)</span>
            </div>
            <div className="flex items-center gap-2">
              <div className="w-6 h-6 bg-yellow-50 border-2 border-yellow-400 rounded"></div>
              <span>Official line</span>
            </div>
          </div>
        </div>
      </div>

      {/* Spread Detail Modal */}
      {selectedSpread !== null && (
        <SpreadDetailModal
          isOpen={isDetailModalOpen}
          onClose={handleDetailModalClose}
          spread={selectedSpread}
          bets={event.spread_grid[selectedSpread.toString()] || []}
          event={event}
          onCreateBet={handleCreateBet}
          onTakeBet={handleTakeBet}
          isAuthenticated={isAuthenticated}
        />
      )}

      {/* Create Bet Modal */}
      {selectedSpread !== null && (
        <CreateSpreadBetModal
          isOpen={isCreateModalOpen}
          onClose={handleCreateBetClose}
          event={event}
          spread={selectedSpread}
        />
      )}

      {/* Take Bet Modal */}
      {selectedSpread !== null && selectedBetId !== null && (
        <TakeBetModal
          isOpen={isTakeModalOpen}
          onClose={handleTakeBetClose}
          betId={selectedBetId}
          spread={selectedSpread}
          event={event}
        />
      )}
    </div>
  )
}
