"use client"

import { useEffect, useState, useMemo } from 'react'
import { useTranslations } from 'next-intl'
import { Hash, Search, Filter, Lock, Unlock, Home, User, Tag } from 'lucide-react'
import { Button } from '@/components/ui/button'

interface InteriorRow {
  id: number
  name: string
  owner: number // character id or -1 for sale
  locked: number
  owner_username?: string // charactername
  owner_account_id?: number // account id
}

export default function AdminInteriors() {
  const t = useTranslations('interiors')
  const [interiors, setInteriors] = useState<InteriorRow[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [searchQuery, setSearchQuery] = useState('')
  const [filterLocked, setFilterLocked] = useState<'all' | 'locked' | 'unlocked'>('all')
  const [page, setPage] = useState(1)
  const pageSize = 20

  useEffect(() => {
    fetchAllInteriors()
  }, [])

  const fetchAllInteriors = async () => {
    try {
      setLoading(true)
      const res = await fetch('/api/admin/interiors')
      if (!res.ok) throw new Error(t('error'))
      const data = await res.json()
      setInteriors(data.interiors || [])
    } catch (e) {
      setError(t('error'))
    } finally {
      setLoading(false)
    }
  }

  const filtered = useMemo(() => interiors.filter((i) => {
    const matchesText =
      i.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      i.owner.toString().includes(searchQuery) ||
      (i.owner_username || '').toLowerCase().includes(searchQuery.toLowerCase()) ||
      (i.owner_account_id ? i.owner_account_id.toString().includes(searchQuery) : false) ||
      i.id.toString().includes(searchQuery)

    const matchesLock =
      filterLocked === 'all' ||
      (filterLocked === 'locked' && i.locked === 1) ||
      (filterLocked === 'unlocked' && i.locked === 0)

    return matchesText && matchesLock
  }), [interiors, searchQuery, filterLocked])

  const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize))
  const currentPage = Math.min(page, totalPages)
  const paged = filtered.slice((currentPage - 1) * pageSize, currentPage * pageSize)

  if (loading) {
    return (
      <div className="bg-black/60 rounded-2xl p-4 border border-gray-700/50">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-green-500 mx-auto mb-3"></div>
          <p className="text-gray-400 text-sm">{t('loading')}</p>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="bg-black/60 rounded-2xl p-4 border border-red-500/30">
        <div className="text-center">
          <p className="text-red-400 mb-2">{error}</p>
          <button onClick={fetchAllInteriors} className="text-sm text-gray-400 hover:text-white">{t('tryAgain')}</button>
        </div>
      </div>
    )
  }

  return (
    <div className="bg-black/60 rounded-2xl p-4 border border-gray-700/50">
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-semibold text-white">Server Interiors</h3>
        <p className="text-sm text-gray-400">{interiors.length} interiors found</p>
      </div>

      {/* Search and Filters */}
      <div className="mb-4 space-y-3">
        <div className="flex flex-col md:flex-row gap-4">
          <div className="flex-1 flex items-center bg-gray-800/60 rounded-xl border border-gray-700 px-3">
            <Search className="w-4 h-4 text-gray-400 mr-2" />
            <input
              value={searchQuery}
              onChange={(e) => { setSearchQuery(e.target.value); setPage(1) }}
              placeholder="Search by name, character ID, account ID, or interior ID..."
              className="bg-transparent text-gray-200 w-full px-2 py-3 outline-none text-sm"
            />
          </div>

          <div className="flex items-center bg-gray-800/60 rounded-xl border border-gray-700 px-3">
            <Filter className="w-4 h-4 text-gray-400 mr-2" />
            <select
              value={filterLocked}
              onChange={(e) => { setFilterLocked(e.target.value as any); setPage(1) }}
              className="bg-transparent text-gray-200 outline-none cursor-pointer text-sm"
            >
              <option value="all">All Lock States</option>
              <option value="unlocked">Unlocked</option>
              <option value="locked">Locked</option>
            </select>
          </div>

          <Button onClick={fetchAllInteriors} size="sm" className="bg-green-600/20 text-green-400 border border-green-600/30 hover:bg-green-600/30">Refresh</Button>
        </div>

        <div className="text-xs text-gray-400">
          <span>{filtered.length} interiors found</span>
        </div>
      </div>

      {/* Interiors Table */}
      {paged.length > 0 ? (
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead>
              <tr className="text-gray-400 text-xs border-b border-gray-700/50">
                <th className="py-2 px-2 font-medium">Interior ID</th>
                <th className="py-2 px-2 font-medium">Interior</th>
                <th className="py-2 px-2 font-medium">Character ID / Status</th>
                <th className="py-2 px-2 font-medium">Character Name</th>
                <th className="py-2 px-2 font-medium">Account ID</th>
                <th className="py-2 px-2 font-medium">Locked</th>
              </tr>
            </thead>
            <tbody>
              {paged.map((i) => (
                <tr key={i.id} className="text-gray-200 text-sm border-b border-gray-800/30 hover:bg-gray-800/20 transition-colors duration-200">
                  <td className="py-2 px-2">
                    <div className="flex items-center space-x-2">
                      <div className="w-5 h-5 bg-gray-700/40 rounded-xl flex items-center justify-center">
                        <Hash className="w-2.5 h-2.5 text-gray-400" />
                      </div>
                      <span className="font-mono font-semibold text-sm">{i.id}</span>
                    </div>
                  </td>
                  <td className="py-2 px-2">
                    <div className="flex items-center space-x-2">
                      <div className="w-12 h-12 rounded-xl overflow-hidden border border-gray-700/30 bg-gray-800/40 flex-shrink-0 relative">
                        <img src="/interiors/image1.png" alt="Interior" className="w-full h-full object-cover" />
                      </div>
                      <div className="flex flex-col">
                        <span className="font-semibold text-white text-sm">{i.name}</span>
                        <span className="text-xs text-gray-400">ID: {i.id}</span>
                      </div>
                    </div>
                  </td>
                  <td className="py-2 px-2">
                    <div className="flex items-center space-x-2">
                      <div className="w-6 h-6 rounded-xl overflow-hidden border border-gray-700/30 bg-gray-800/40 flex-shrink-0 relative">
                        <div className="fallback-icon absolute inset-0 w-full h-full flex items-center justify-center bg-gradient-to-br from-gray-700/60 to-gray-800/60">
                          {i.owner === -1 ? (
                            <Tag className="w-3 h-3 text-yellow-400" />
                          ) : (
                            <User className="w-3 h-3 text-gray-400" />
                          )}
                        </div>
                      </div>
                      {i.owner === -1 ? (
                        <span className="text-xs font-medium text-yellow-400">For Sale</span>
                      ) : (
                        <span className="font-mono font-semibold text-sm">{i.owner}</span>
                      )}
                    </div>
                  </td>
                  <td className="py-2 px-2">
                    {i.owner === -1 ? (
                      <span className="px-2 py-1 rounded-xl text-xs font-medium bg-yellow-600/20 text-yellow-400 border border-yellow-600/30">Unowned</span>
                    ) : i.owner_username ? (
                      <span className="px-2 py-1 rounded-xl text-xs font-medium bg-blue-600/20 text-blue-400 border border-blue-600/30">{i.owner_username}</span>
                    ) : (
                      <span className="px-2 py-1 rounded-xl text-xs font-medium bg-gray-600/20 text-gray-400 border border-gray-600/30">Unknown</span>
                    )}
                  </td>
                  <td className="py-2 px-2">
                    {i.owner !== -1 && i.owner_account_id ? (
                      <span className="px-2 py-1 rounded-xl text-xs font-medium bg-purple-600/20 text-purple-300 border border-purple-600/30">{i.owner_account_id}</span>
                    ) : (
                      <span className="px-2 py-1 rounded-xl text-xs font-medium bg-gray-600/20 text-gray-400 border border-gray-600/30">-</span>
                    )}
                  </td>
                  <td className="py-2 px-2">
                    <div className="flex items-center space-x-2">
                      {i.locked === 1 ? (
                        <Lock className="w-3 h-3 text-red-400" />
                      ) : (
                        <Unlock className="w-3 h-3 text-green-400" />
                      )}
                      <span className={`text-xs font-medium ${i.locked === 1 ? 'text-red-400' : 'text-green-400'}`}>{i.locked === 1 ? 'Locked' : 'Unlocked'}</span>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <div className="text-center py-8">
          <div className="w-16 h-16 bg-gray-700/40 rounded-full flex items-center justify-center mx-auto mb-4">
            <Home className="w-8 h-8 text-gray-400" />
          </div>
          <h4 className="text-lg font-semibold text-white mb-2">{t('noInteriors')}</h4>
          <p className="text-gray-400 text-sm">No interiors match your search criteria</p>
        </div>
      )}

      {/* Pagination */}
      <div className="flex items-center justify-between mt-3 text-xs text-gray-400">
        <span>Page {currentPage} of {totalPages}</span>
        <div className="space-x-2">
          <Button size="sm" variant="outline" className="border-gray-700 text-gray-300 hover:text-white" onClick={() => setPage(p => Math.max(1, p - 1))}>
            Previous
          </Button>
          <Button size="sm" variant="outline" className="border-gray-700 text-gray-300 hover:text-white" onClick={() => setPage(p => Math.min(totalPages, p + 1))}>
            Next
          </Button>
        </div>
      </div>

      {/* Summary */}
      <div className="mt-4 pt-3 border-t border-gray-700/50">
        <div className="grid grid-cols-3 gap-3 text-center">
          <div className="bg-gray-800/40 rounded-xl p-3 border border-gray-700/30">
            <p className="text-xl font-bold text-white">{interiors.length}</p>
            <p className="text-gray-400 text-xs">Total Interiors</p>
          </div>
          <div className="bg-gray-800/40 rounded-xl p-3 border border-gray-700/30">
            <p className="text-xl font-bold text-green-400">{interiors.filter(i => i.locked === 0).length}</p>
            <p className="text-gray-400 text-xs">Unlocked</p>
          </div>
          <div className="bg-gray-800/40 rounded-xl p-3 border border-gray-700/30">
            <p className="text-xl font-bold text-red-400">{interiors.filter(i => i.locked === 1).length}</p>
            <p className="text-gray-400 text-xs">Locked</p>
          </div>
        </div>
      </div>
    </div>
  )
}
