import React, { useRef } from 'react'
import { useGameStore } from '../store/useGameStore'
import { ITEMS, Item } from '../constants'
import FloatingMessage, { FloatingMessagesHandle } from './FloatingMessages'
import { styled } from '@linaria/react'

const MarketContainer = styled.div`
  padding: 1rem;
`

const Title = styled.h2`
  font-size: 1.5rem;
  font-weight: bold;
  margin-bottom: 1rem;
  text-align: center;
`

const CashDisplay = styled.div`
  text-align: center;
  margin-bottom: 1.5rem;
  padding: 1rem;
  background-color: #dcfce7;
  border-radius: 0.375rem;
`

const CashAmount = styled.h3`
  font-size: 1.25rem;
  font-weight: 500;
`

const SectionTitle = styled.h3`
  font-size: 1.25rem;
  font-weight: 500;
  margin-bottom: 0.5rem;
  margin-top: 1.5rem;
`

const MarketTable = styled.table`
  width: 100%;
  border-collapse: separate;
  border-spacing: 0 0.5rem;
`

const MarketItemRow = styled.tr`
  background-color: #f3f4f6;
  border-radius: 0.5rem;
`

const MarketItemCell = styled.td`
  padding: 0.75rem;
  text-align: center;
`

const TableHeader = styled.th`
  padding: 0.75rem;
  text-align: center;
`

const ItemIcon = styled.span`
  font-size: 1.5rem;
  margin-right: 0.5rem;
`

const ActionButton = styled.button<{ disabled?: boolean }>`
  padding: 0.5rem 1rem;
  border-radius: 0.25rem;
  background-color: ${(props) => (props.disabled ? '#9ca3af' : '#3b82f6')};
  color: white;
  font-weight: bold;
  cursor: ${(props) => (props.disabled ? 'not-allowed' : 'pointer')};
  border: none;
`

const MarketComponent: React.FC = () => {
  const { inventory, cash, buyItem, sellItem, landPurchases } = useGameStore()
  const floatingMessagesRef = useRef<FloatingMessagesHandle>(null)

  const getItemPrice = (item: Item) => {
    if (item.id === 'additional_land') {
      return Math.floor(100 * Math.pow(1.5, landPurchases))
    }
    return item.buyPrice
  }

  const handleBuy = (itemId: string, e: React.MouseEvent) => {
    const item = ITEMS[itemId]
    const price = getItemPrice(item)
    if (!item || price === null || cash < price) return

    buyItem(itemId)

    const rect = (e.target as HTMLElement).getBoundingClientRect()
    const position = { x: rect.left + rect.width / 2, y: rect.top }

    floatingMessagesRef.current?.addMessage(
      `+1 ${item.emoji} ${item.name}`,
      position,
    )
  }

  const handleSell = (itemId: string, e: React.MouseEvent) => {
    const item = ITEMS[itemId]
    if (
      !item ||
      item.sellPrice === null ||
      !inventory[itemId] ||
      inventory[itemId] <= 0
    )
      return

    sellItem(itemId)

    const rect = (e.target as HTMLElement).getBoundingClientRect()
    const position = { x: rect.left + rect.width / 2, y: rect.top }

    floatingMessagesRef.current?.addMessage(
      `-1 ${item.emoji} ${item.name}`,
      position,
    )
  }

  const sellableItems = Object.entries(ITEMS)
    .filter(
      ([_, item]) =>
        item.sellPrice !== null && inventory[item.id] && inventory[item.id] > 0,
    )
    .map(([_, item]) => item)

  const buyableItems = Object.entries(ITEMS)
    .filter(([_, item]) => item.buyPrice !== null)
    .map(([_, item]) => item)

  return (
    <MarketContainer>
      <Title>Market</Title>

      <CashDisplay>
        <CashAmount>Cash: ${cash.toFixed(2)}</CashAmount>
      </CashDisplay>

      {sellableItems.length > 0 && (
        <>
          <SectionTitle>Sell Items</SectionTitle>
          <MarketTable>
            <thead>
              <tr>
                <TableHeader>Item</TableHeader>
                <TableHeader>Sell Price</TableHeader>
                <TableHeader>Quantity</TableHeader>
                <TableHeader>Action</TableHeader>
              </tr>
            </thead>
            <tbody>
              {sellableItems.map((item) => (
                <MarketItemRow key={`sell-${item.id}`}>
                  <MarketItemCell>
                    <ItemIcon>{item.emoji}</ItemIcon>
                    {item.name}
                  </MarketItemCell>
                  <MarketItemCell>${item.sellPrice}</MarketItemCell>
                  <MarketItemCell>{inventory[item.id] || 0}</MarketItemCell>
                  <MarketItemCell>
                    <ActionButton
                      onClick={(e) => handleSell(item.id, e)}
                      disabled={!inventory[item.id] || inventory[item.id] <= 0}
                    >
                      Sell
                    </ActionButton>
                  </MarketItemCell>
                </MarketItemRow>
              ))}
            </tbody>
          </MarketTable>
        </>
      )}

      {buyableItems.length > 0 && (
        <>
          <SectionTitle>Buy Items</SectionTitle>
          <MarketTable>
            <thead>
              <tr>
                <TableHeader>Item</TableHeader>
                <TableHeader>Buy Price</TableHeader>
                <TableHeader>Action</TableHeader>
              </tr>
            </thead>
            <tbody>
              {buyableItems.map((item) => (
                <MarketItemRow key={`buy-${item.id}`}>
                  <MarketItemCell>
                    <ItemIcon>{item.emoji}</ItemIcon>
                    {item.name}
                  </MarketItemCell>
                  <MarketItemCell>${getItemPrice(item)}</MarketItemCell>
                  <MarketItemCell>
                    <ActionButton
                      onClick={(e) => handleBuy(item.id, e)}
                      disabled={
                        getItemPrice(item) ? cash < getItemPrice(item)! : true
                      }
                    >
                      Buy
                    </ActionButton>
                  </MarketItemCell>
                </MarketItemRow>
              ))}
            </tbody>
          </MarketTable>
        </>
      )}

      <FloatingMessage ref={floatingMessagesRef} />
    </MarketContainer>
  )
}

export default MarketComponent
