import React, { useState, useRef, useEffect } from 'react'
import {
  Modal,
  Button,
  ModalHeader,
  ModalBody,
  ModalFooter,
} from 'flowbite-react'
import { LuSearch, LuStore } from 'react-icons/lu'
import { Marketplace } from '@/app/(dashboard)/marketplaces/types'

interface MarketplaceSearchModalProps {
  isOpen: boolean
  marketplaces: Marketplace[]
  isLoading: boolean
  selectedMarketplace?: Marketplace | null
  onClose: () => void
  onSelectMarketplace: (marketplace: Marketplace) => void
}

export default function MarketplaceSearchModal({
  isOpen,
  marketplaces,
  selectedMarketplace,
  isLoading,
  onSelectMarketplace,
  onClose,
}: MarketplaceSearchModalProps) {
  const [searchValue, setSearchValue] = useState('')
  const [filteredMarketplaces, setFilteredMarketplaces] =
    useState<Marketplace[]>(marketplaces)
  const inputRef = useRef<HTMLInputElement>(null)

  // Filter marketplaces based on search value
  useEffect(() => {
    if (searchValue.trim() === '') {
      setFilteredMarketplaces(marketplaces)
    } else {
      const filtered = marketplaces.filter((marketplace) =>
        marketplace.name.toLowerCase().includes(searchValue.toLowerCase()),
      )
      setFilteredMarketplaces(filtered)
    }
  }, [searchValue, marketplaces])

  // Reset search when modal opens/closes
  useEffect(() => {
    if (isOpen) {
      setSearchValue('')
      setTimeout(() => {
        inputRef.current?.focus()
      }, 100)
    } else {
      setSearchValue('')
    }
  }, [isOpen])

  const handleSelectMarketplace = (marketplace: Marketplace) => {
    onSelectMarketplace(marketplace)
    onClose()
    setSearchValue('')
  }

  const handleSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSearchValue(event.target.value)
  }

  const handleCancel = () => {
    onClose()
    setSearchValue('')
  }

  const renderOption = (marketplace: Marketplace, index: number) => (
    <button
      key={marketplace.id}
      type="button"
      onClick={() => handleSelectMarketplace(marketplace)}
      className={`w-full px-4 py-3 flex items-center gap-3 hover:bg-gray-50 focus:outline-none focus:bg-orange-50 text-left transition-colors duration-200 ${
        selectedMarketplace?.id === marketplace.id
          ? 'bg-orange-50 border-l-4 border-orange-500'
          : ''
      } ${index !== filteredMarketplaces.length - 1 ? 'border-b border-gray-100' : ''}`}
    >
      {/* Marketplace Icon */}
      <div className="flex-shrink-0 w-8 h-8 bg-orange-100 rounded-full flex items-center justify-center">
        <LuStore className="w-4 h-4 text-orange-600" />
      </div>

      {/* Marketplace Details */}
      <div className="flex-1 min-w-0 flex items-center justify-between">
        <div>
          <h3 className="font-medium text-gray-900 truncate">
            {marketplace.name}
          </h3>
        </div>

        {selectedMarketplace?.id === marketplace.id && (
          <div className="w-2 h-2 rounded-full bg-orange-500 flex-shrink-0" />
        )}
      </div>
    </button>
  )

  const renderNoResultsFound = () => (
    <div className="px-4 py-8 text-center text-gray-500">
      <LuStore className="w-12 h-12 mx-auto mb-3 text-gray-300" />
      <p className="text-lg font-medium mb-1">No marketplaces found</p>
      <p className="text-sm">Try adjusting your search criteria</p>
    </div>
  )

  const renderSkeletonComponent = () => (
    <div className="p-4 space-y-3">
      {[...Array(5)].map((_, i) => (
        <div key={i} className="flex items-center gap-3">
          <div className="w-8 h-8 bg-gray-200 rounded-full animate-pulse" />
          <div className="flex-1">
            <div className="h-4 bg-gray-200 rounded animate-pulse w-3/4" />
          </div>
        </div>
      ))}
    </div>
  )

  return (
    <Modal show={isOpen} onClose={handleCancel} size="xl" position="center">
      <ModalHeader className="border-b-gray-200">
        <div className="flex items-center gap-3">
          <div className="w-8 h-8 bg-orange-100 rounded-full flex items-center justify-center">
            <LuSearch className="w-4 h-4 text-orange-600" />
          </div>
          <div>
            <h3 className="text-xl font-semibold text-gray-900">
              Select Marketplace
            </h3>
            <p className="text-sm text-gray-500 mt-1">
              Search and select a marketplace for this booking
            </p>
          </div>
        </div>
      </ModalHeader>

      <ModalBody className="p-0">
        <div className="relative">
          {/* Search Input */}
          <div className="p-6 border-b border-gray-200">
            <div className="relative">
              <LuSearch className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                type="text"
                placeholder="Search marketplace by name..."
                value={searchValue}
                ref={inputRef}
                onChange={handleSearch}
                className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500 focus:border-orange-500 text-sm"
              />
            </div>
          </div>

          {/* Marketplace List */}
          <div className="max-h-80 overflow-y-auto">
            {isLoading ? (
              renderSkeletonComponent()
            ) : filteredMarketplaces.length > 0 ? (
              <div>
                {filteredMarketplaces.map((marketplace, index) =>
                  renderOption(marketplace, index),
                )}
              </div>
            ) : (
              renderNoResultsFound()
            )}
          </div>
        </div>
      </ModalBody>

      <ModalFooter className="flex justify-end gap-3">
        <Button color="light" onClick={handleCancel}>
          Cancel
        </Button>
        <Button
          color="orange"
          disabled={!selectedMarketplace}
          onClick={() =>
            selectedMarketplace && handleSelectMarketplace(selectedMarketplace)
          }
        >
          {selectedMarketplace
            ? `Select ${selectedMarketplace.name}`
            : 'Select Marketplace'}
        </Button>
      </ModalFooter>
    </Modal>
  )
}
