'use client'

import { useState, useEffect } from 'react'
import {
  Search,
  Users,
  Calendar,
  ArrowLeft,
  ChevronRight,
  Loader2,
} from 'lucide-react'
import Link from 'next/link'
import { useTranslations, useLocale } from 'next-intl'
import { AffiliatesListSkeleton } from './components/AffiliatesListSkeleton'
import { InviteAffiliatePopup } from './components/InviteAffiliatePopup'

interface Affiliate {
  id: number
  name: string
  country: string
  verified: number
  created_at: string
  updated_at: string
}

interface Pagination {
  current_page: number
  last_page: number
  per_page: number
  total: number
  from: number | null
  to: number | null
  has_more_pages: boolean
}

export default function MyAffiliatesPage() {
  const t = useTranslations('myAffiliates')
  const locale = useLocale()
  const [searchQuery, setSearchQuery] = useState('')
  const [affiliates, setAffiliates] = useState<Affiliate[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [pagination, setPagination] = useState<Pagination | null>(null)
  const [selectedAffiliate, setSelectedAffiliate] = useState<Affiliate | null>(
    null
  )
  const [isPopupOpen, setIsPopupOpen] = useState(false)

  // Charger les affiliés au montage du composant
  useEffect(() => {
    loadAffiliates(1)
  }, [])

  const loadAffiliates = async (page: number) => {
    try {
      setLoading(true)
      setError(null)

      const response = await fetch(`/api/my-affiliates?page=${page}`)
      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.error || 'Failed to load affiliates')
      }

      setAffiliates(data.data || [])
      setPagination(data.pagination)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An error occurred')
      console.error('Error loading affiliates:', err)
    } finally {
      setLoading(false)
    }
  }

  // Filtrage des affiliés
  const filteredAffiliates = affiliates.filter((affiliate) => {
    return affiliate.name.toLowerCase().includes(searchQuery.toLowerCase())
  })

  // Ouvrir le popup d'invitation
  const handleAffiliateClick = (affiliate: Affiliate) => {
    setSelectedAffiliate(affiliate)
    setIsPopupOpen(true)
  }

  // Fermer le popup
  const handleClosePopup = () => {
    setIsPopupOpen(false)
    setSelectedAffiliate(null)
  }

  return (
    <>
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 p-2 md:p-4">
        <div className="max-w-7xl mx-auto">
          {/* Header */}
          <div className="mb-8">
            <div className="flex items-center mb-6">
              <div>
                <p className="text-gray-600 dark:text-gray-300">
                  {t('description')}
                </p>
              </div>
            </div>
          </div>

          {/* Error state */}
          {error && !loading && (
            <div className="text-center py-12">
              <div className="w-16 h-16 bg-red-100 dark:bg-red-900 rounded-2xl flex items-center justify-center mx-auto mb-4">
                <Users className="w-8 h-8 text-red-500" />
              </div>
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
                {t('loadingError')}
              </h3>
              <p className="text-gray-500 dark:text-gray-400 mb-4">{error}</p>
              <button
                onClick={() => loadAffiliates(pagination?.current_page || 1)}
                className="px-4 py-2 bg-teal-500 text-white rounded-xl hover:bg-teal-600 transition-colors"
              >
                {t('retryButton')}
              </button>
            </div>
          )}

          {/* Barre de recherche */}
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-sm border border-gray-200 dark:border-gray-700 p-6 mb-6">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input
                type="text"
                placeholder={t('searchPlaceholder')}
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full pl-10 pr-4 py-3 border-0 rounded-xl bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-teal-500"
              />
            </div>
          </div>

          {/* Skeleton de chargement */}
          {loading && <AffiliatesListSkeleton />}

          {/* Liste des affiliés */}
          {!loading && (
            <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-2 lg:gap-6">
              {filteredAffiliates.map((affiliate) => (
                <div
                  key={affiliate.id}
                  onClick={() => handleAffiliateClick(affiliate)}
                  className="bg-white dark:bg-gray-800 rounded-2xl shadow-sm border border-gray-200 dark:border-gray-700 p-6 hover:shadow-lg transition-all duration-300 cursor-pointer"
                >
                  <div className="flex items-center space-x-4">
                    <div className="w-12 h-12 bg-teal-500 rounded-xl flex items-center justify-center text-white font-bold">
                      {affiliate.name
                        .split(' ')
                        .map((n) => n[0])
                        .join('')
                        .slice(0, 2)}
                    </div>
                    <div className="flex-1">
                      <h3 className="font-semibold text-gray-900 dark:text-white mb-2">
                        {affiliate.name}
                      </h3>
                      <div className="flex items-center space-x-1 text-sm text-gray-500 dark:text-gray-400">
                        <Calendar className="w-4 h-4" />
                        <span>
                          {t('registeredOn')}{' '}
                          {new Date(affiliate.created_at).toLocaleDateString(
                            locale === 'fr' ? 'fr-FR' : 'en-US'
                          )}
                        </span>
                      </div>
                    </div>
                    <div className="flex items-center justify-center">
                      <ChevronRight className="w-5 h-5 text-gray-400" />
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Message si aucun résultat */}
          {filteredAffiliates.length === 0 && !loading && !error && (
            <div className="text-center py-12">
              <div className="w-16 h-16 bg-gray-100 dark:bg-gray-700 rounded-2xl flex items-center justify-center mx-auto mb-4">
                <Users className="w-8 h-8 text-gray-400" />
              </div>
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
                {t('noResultTitle')}
              </h3>
              <p className="text-gray-500 dark:text-gray-400">
                {searchQuery ? t('noResultMessage') : t('noResultEmpty')}
              </p>
            </div>
          )}

          {/* Pagination */}
          {pagination && pagination.last_page > 1 && !loading && !error && (
            <div className="flex items-center justify-center space-x-2 mt-8">
              <button
                onClick={() => loadAffiliates(pagination.current_page - 1)}
                disabled={pagination.current_page === 1}
                className="px-4 py-2 rounded-xl bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {t('paginationPrevious')}
              </button>

              <span className="px-4 py-2 text-sm text-gray-600 dark:text-gray-400">
                {t('paginationPage', {
                  currentPage: pagination.current_page,
                  lastPage: pagination.last_page,
                })}
              </span>

              <button
                onClick={() => loadAffiliates(pagination.current_page + 1)}
                disabled={!pagination.has_more_pages}
                className="px-4 py-2 rounded-xl bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {t('paginationNext')}
              </button>
            </div>
          )}
        </div>
      </div>

      {/* Popup d'invitation */}
      {selectedAffiliate && isPopupOpen && (
        <InviteAffiliatePopup
          affiliate={selectedAffiliate}
          isOpen={isPopupOpen}
          onClose={handleClosePopup}
        />
      )}
    </>
  )
}
