import { useState } from 'react'
import { Link } from 'react-router-dom'
import { Download, RefreshCw, Eye, Trash2, Search, Filter } from 'lucide-react'
import { useLeads, useUpdateLeadStatus, useDeleteLead } from '@/hooks/useLeads'
import { useLicense } from '@/hooks/useLicense'
import { exportApi } from '@/api/analytics'
import { PageHeader } from '@/components/layout/PageHeader'
import { Button } from '@/components/common/Button'
// Badge component available if needed
import { PageLoading } from '@/components/common/Spinner'
import { EmptyState } from '@/components/common/EmptyState'
import { formatDate, formatPhone } from '@/utils/formatters'
import { LEAD_STATUS_CONFIG, LEAD_STATUSES } from '@/utils/constants'
import type { LeadFilters, LeadStatus } from '@/types/lead'
import { t, sprintf } from '@/lib/i18n'
import { useLanguage } from '@/contexts/LanguageContext'

export function Leads() {
  
  const { isFeatureEnabled } = useLicense()
  const { currentLanguage } = useLanguage()
  
  // State
  const [page, setPage] = useState(1)
  const [filters, setFilters] = useState<LeadFilters>({})
  const [searchQuery, setSearchQuery] = useState('')
  
  // Queries & Mutations
  const { data, isLoading, isFetching, refetch } = useLeads(page, 20, filters, currentLanguage)
  const updateStatus = useUpdateLeadStatus()
  const deleteLead = useDeleteLead()
  
  // Export handler
  const handleExport = async () => {
    try {
      const response = await exportApi.exportLeads(filters as Record<string, unknown>)
      if (response.data?.download_url) {
        window.open(response.data.download_url, '_blank')
      }
    } catch (error) {
      console.error('Export failed:', error)
      alert(t('Error exporting data'))
    }
  }
  
  // Delete handler
  const handleDelete = (id: number) => {
    if (confirm(t('Are you sure you want to delete this lead?'))) {
      deleteLead.mutate(id)
    }
  }
  
  // Search handler
  const handleSearch = () => {
    setFilters(prev => ({ ...prev, search: searchQuery }))
    setPage(1)
  }
  
  // Status filter handler
  const handleStatusFilter = (status: LeadStatus | '') => {
    setFilters(prev => ({ ...prev, status: status || undefined }))
    setPage(1)
  }
  
  if (isLoading) {
    return <PageLoading />
  }
  
  const leads = data?.data?.leads || []
  const pagination = data?.data?.pagination
  
  return (
    <div className="space-y-6 animate-fade-in">
      <PageHeader 
        title={t('Lead Management')}
        subtitle={sprintf(t('Total %d leads'), pagination?.total ?? 0)}
      >
        <Button
          variant="outline"
          onClick={() => refetch()}
          disabled={isFetching}
        >
          <RefreshCw className={`w-4 h-4 me-2 ${isFetching ? 'animate-spin' : ''}`} />
          {t('Refresh')}
        </Button>
        {isFeatureEnabled('export') && (
          <Button onClick={handleExport}>
            <Download className="w-4 h-4 me-2" />
            {t('Export')}
          </Button>
        )}
      </PageHeader>
      
      {/* Filters */}
      <div className="bg-white rounded-xl shadow-card border border-gray-100 p-4">
        <div className="flex flex-wrap gap-4">
          {/* Search */}
          <div className="flex-1 min-w-[200px]">
            <div className="relative">
              <Search className="absolute start-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input
                type="text"
                placeholder={t('Search by name, email or phone...')}
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                className="w-full ps-10 pe-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
              />
            </div>
          </div>
          
          {/* Status Filter */}
          <div className="flex items-center gap-2">
            <Filter className="w-4 h-4 text-gray-400" />
            <select
              value={filters.status || ''}
              onChange={(e) => handleStatusFilter(e.target.value as LeadStatus | '')}
              className="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary-500"
            >
              <option value="">{t('All Statuses')}</option>
              {LEAD_STATUSES.map(status => (
                <option key={status} value={status}>
                  {LEAD_STATUS_CONFIG[status].label}
                </option>
              ))}
            </select>
          </div>
          
          <Button variant="secondary" onClick={handleSearch}>
            {t('Search')}
          </Button>
        </div>
      </div>
      
      {/* Table */}
      {leads.length === 0 ? (
        <EmptyState
          title={t('No Leads')}
          description={t('No leads created yet. New leads will appear here.')}
        />
      ) : (
        <div className="bg-white rounded-xl shadow-card border border-gray-100 overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-gray-50 border-b border-gray-200">
                <tr>
                  <th className="text-start px-6 py-3 text-sm font-medium text-gray-500">{t('Name')}</th>
                  <th className="text-start px-6 py-3 text-sm font-medium text-gray-500">{t('Email')}</th>
                  <th className="text-start px-6 py-3 text-sm font-medium text-gray-500">{t('Phone')}</th>
                  <th className="text-start px-6 py-3 text-sm font-medium text-gray-500">{t('Status')}</th>
                  <th className="text-start px-6 py-3 text-sm font-medium text-gray-500">{t('Score')}</th>
                  <th className="text-start px-6 py-3 text-sm font-medium text-gray-500">{t('Date')}</th>
                  <th className="text-start px-6 py-3 text-sm font-medium text-gray-500">{t('Actions')}</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200">
                {leads.map((lead) => (
                  <tr key={lead.id} className="hover:bg-gray-50 transition-colors">
                    <td className="px-6 py-4">
                      <span className="font-medium text-gray-900">
                        {lead.name || '-'}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-gray-600">
                      {lead.email || '-'}
                    </td>
                    <td className="px-6 py-4 text-gray-600">
                      {formatPhone(lead.phone)}
                    </td>
                    <td className="px-6 py-4">
                      <StatusDropdown
                        status={lead.lead_status}
                        onChange={(status) => updateStatus.mutate({ id: lead.id, status })}
                        disabled={updateStatus.isPending}
                      />
                    </td>
                    <td className="px-6 py-4">
                      <ScoreBadge score={lead.lead_score} />
                    </td>
                    <td className="px-6 py-4 text-gray-600 text-sm">
                      {formatDate(lead.created_at)}
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex gap-2">
                        <Link
                          to={`/leads/${lead.id}`}
                          className="p-2 text-gray-400 hover:text-primary-600 transition-colors"
                          title={t('View')}
                        >
                          <Eye className="w-4 h-4" />
                        </Link>
                        <button
                          onClick={() => handleDelete(lead.id)}
                          className="p-2 text-gray-400 hover:text-red-600 transition-colors"
                          title={t('Delete')}
                          disabled={deleteLead.isPending}
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          
          {/* Pagination */}
          {pagination && pagination.total_pages > 1 && (
            <div className="px-6 py-4 border-t border-gray-200 flex items-center justify-between">
              <p className="text-sm text-gray-500">
                {sprintf(t('Showing %d-%d of %d'), ((page - 1) * 20) + 1, Math.min(page * 20, pagination.total), pagination.total)}
              </p>
              <div className="flex gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  disabled={page === 1}
                  onClick={() => setPage(p => p - 1)}
                >
                  {t('Previous')}
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  disabled={page === pagination.total_pages}
                  onClick={() => setPage(p => p + 1)}
                >
                  {t('Next')}
                </Button>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  )
}

// Status Dropdown Component
function StatusDropdown({ 
  status, 
  onChange, 
  disabled 
}: { 
  status: LeadStatus
  onChange: (status: LeadStatus) => void
  disabled: boolean
}) {
  const config = LEAD_STATUS_CONFIG[status]
  
  return (
    <select
      value={status}
      onChange={(e) => onChange(e.target.value as LeadStatus)}
      disabled={disabled}
      className={`
        px-2.5 py-1 text-xs font-medium rounded-full border-0
        ${config.bgColor} ${config.color}
        cursor-pointer focus:ring-2 focus:ring-primary-500
        disabled:opacity-50
      `}
    >
      {LEAD_STATUSES.map(s => (
        <option key={s} value={s}>
          {LEAD_STATUS_CONFIG[s].label}
        </option>
      ))}
    </select>
  )
}

// Score Badge Component
function ScoreBadge({ score }: { score: number }) {
  const getColor = () => {
    if (score >= 80) return 'bg-green-100 text-green-700'
    if (score >= 50) return 'bg-yellow-100 text-yellow-700'
    return 'bg-gray-100 text-gray-700'
  }
  
  return (
    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getColor()}`}>
      {score}
    </span>
  )
}

