import { useQuery } from '@tanstack/react-query'
import { useBreadcrumb } from '../hooks/useBreadcrumb'
import { breadcrumbConfig } from '../config/breadcrumbConfig'
import { Users, CheckCircle, XCircle, TrendingUp, Clock, ScanFace } from 'lucide-react'
import { api } from '../lib/api'
import { formatDate } from '../lib/utils'

export default function FaceRecognitionDashboard() {
  useBreadcrumb(breadcrumbConfig['/faces'])
  // Get platform/source color for badges
  const getSourceColor = (source: string) => {
    const lowerSource = source.toLowerCase()
    const colors: Record<string, string> = {
      instagram: 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200',
      tiktok: 'bg-pink-100 text-pink-800 dark:bg-pink-900 dark:text-pink-200',
      fastdl: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200',
      toolzu: 'bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200',
      imginn: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200',
      youtube: 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200',
      twitter: 'bg-sky-100 text-sky-800 dark:bg-sky-900 dark:text-sky-200',
      reddit: 'bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200',
      imgur: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900 dark:text-emerald-200',
    }

    // Check if it's a forum source
    if (lowerSource.startsWith('forum:')) {
      return 'bg-indigo-100 text-indigo-800 dark:bg-indigo-900 dark:text-indigo-200'
    }

    return colors[lowerSource] || 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'
  }

  // Format source name for display
  const formatSourceName = (source: string) => {
    if (!source || source === 'unknown') return 'Unknown'
    if (source.startsWith('forum:')) {
      return source.replace('forum:', '').split('/')[0] // Get forum name
    }
    return source.charAt(0).toUpperCase() + source.slice(1)
  }

  const { data: stats, isLoading } = useQuery({
    queryKey: ['face-dashboard-stats'],
    queryFn: () => api.getFaceDashboardStats(),
    refetchInterval: 30000, // Refresh every 30 seconds
  })

  if (isLoading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <h1 className="text-2xl sm:text-3xl font-bold flex items-center gap-2 sm:gap-3">
            <ScanFace className="w-8 h-8 text-sky-500" />
            Face Recognition Dashboard
          </h1>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          {[...Array(3)].map((_, i) => (
            <div key={i} className="bg-white dark:bg-gray-800 rounded-lg shadow p-6 animate-pulse">
              <div className="h-20 bg-slate-200 dark:bg-slate-700 rounded"></div>
            </div>
          ))}
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold flex items-center gap-2 sm:gap-3">
            <ScanFace className="w-8 h-8 text-sky-500" />
            Face Recognition Dashboard
          </h1>
          <p className="text-slate-600 dark:text-slate-400 mt-1">
            Analytics and insights for face recognition scans
          </p>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
        {/* Total Scans */}
        <div className="card-glass-hover rounded-xl p-6 border stat-card-blue shadow-blue-glow">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-muted-foreground">Total Scans</p>
              <p className="text-2xl font-bold text-foreground mt-1 animate-count-up">
                {stats?.total_scans?.toLocaleString() || 0}
              </p>
            </div>
            <div className="p-3 bg-blue-500/20 rounded-xl">
              <Users className="w-6 h-6 text-blue-600 dark:text-blue-400" />
            </div>
          </div>
        </div>

        {/* Matches */}
        <div className="card-glass-hover rounded-xl p-6 border stat-card-green shadow-green-glow">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-muted-foreground">Matches</p>
              <p className="text-2xl font-bold text-emerald-600 dark:text-emerald-400 mt-1">
                {stats?.total_matches?.toLocaleString() || 0}
              </p>
            </div>
            <div className="p-3 bg-emerald-500/20 rounded-xl">
              <CheckCircle className="w-6 h-6 text-emerald-600 dark:text-emerald-400" />
            </div>
          </div>
        </div>

        {/* No Matches */}
        <div className="card-glass-hover rounded-xl p-6 border stat-card-red shadow-red-glow">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-muted-foreground">No Matches</p>
              <p className="text-2xl font-bold text-red-600 dark:text-red-400 mt-1">
                {stats?.total_no_matches?.toLocaleString() || 0}
              </p>
            </div>
            <div className="p-3 bg-red-500/20 rounded-xl">
              <XCircle className="w-6 h-6 text-red-600 dark:text-red-400" />
            </div>
          </div>
        </div>

        {/* Match Rate */}
        <div className="card-glass-hover rounded-xl p-6 border stat-card-purple shadow-purple-glow">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-muted-foreground">Match Rate</p>
              <p className="text-2xl font-bold text-violet-600 dark:text-violet-400 mt-1">
                {stats?.match_rate ? `${stats.match_rate.toFixed(1)}%` : '0%'}
              </p>
            </div>
            <div className="p-3 bg-violet-500/20 rounded-xl">
              <TrendingUp className="w-6 h-6 text-violet-600 dark:text-violet-400" />
            </div>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Matches by Person */}
        <div className="card-glass-hover rounded-xl">
          <div className="px-6 py-4 border-b border-border">
            <h3 className="text-lg font-semibold text-foreground">Matches by Person</h3>
          </div>
          <div className="p-6">
            {stats?.by_person && stats.by_person.length > 0 ? (
              <div className="space-y-4">
                {stats.by_person.slice(0, 10).map((person, index) => (
                  <div key={index} className="flex items-center justify-between">
                    <div className="flex-1">
                      <div className="flex items-center justify-between mb-1">
                        <span className="text-sm font-medium text-slate-900 dark:text-slate-100">
                          {person.person}
                        </span>
                        <span className="text-sm text-slate-600 dark:text-slate-400">
                          {person.count} matches
                        </span>
                      </div>
                      <div className="w-full bg-slate-200 dark:bg-slate-700 rounded-full h-1.5 sm:h-2">
                        <div
                          className="bg-blue-600 dark:bg-blue-500 h-1.5 sm:h-2 rounded-full"
                          style={{
                            width: `${(person.count / (stats.by_person[0]?.count || 1)) * 100}%`
                          }}
                        ></div>
                      </div>
                      <div className="flex items-center justify-between mt-1">
                        <span className="text-xs text-slate-500 dark:text-slate-400">
                          Avg: {person.avg_confidence.toFixed(1)}%
                        </span>
                        <span className="text-xs text-slate-500 dark:text-slate-400">
                          Range: {person.min_confidence.toFixed(1)}% - {person.max_confidence.toFixed(1)}%
                        </span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <p className="text-center text-slate-500 dark:text-slate-400 py-8">No matches found yet</p>
            )}
          </div>
        </div>

        {/* Confidence Distribution */}
        <div className="card-glass-hover rounded-xl">
          <div className="px-6 py-4 border-b border-border">
            <h3 className="text-lg font-semibold text-foreground">Confidence Distribution</h3>
          </div>
          <div className="p-6">
            {stats?.confidence_distribution ? (
              <div className="space-y-3">
                {Object.entries(stats.confidence_distribution).map(([range, count]) => {
                  const total = Object.values(stats.confidence_distribution).reduce((a: number, b: number) => a + b, 0)
                  const percentage = total > 0 ? (count / total) * 100 : 0
                  return (
                    <div key={range}>
                      <div className="flex items-center justify-between mb-1">
                        <span className="text-sm font-medium text-slate-700 dark:text-slate-300">{range}</span>
                        <span className="text-sm text-slate-600 dark:text-slate-400">
                          {count} ({percentage.toFixed(1)}%)
                        </span>
                      </div>
                      <div className="w-full bg-slate-200 dark:bg-slate-700 rounded-full h-1.5 sm:h-2">
                        <div
                          className="bg-gradient-to-r from-red-500 via-yellow-500 to-green-500 h-1.5 sm:h-2 rounded-full"
                          style={{ width: `${percentage}%` }}
                        ></div>
                      </div>
                    </div>
                  )
                })}
              </div>
            ) : (
              <p className="text-center text-slate-500 dark:text-slate-400 py-8">No distribution data available</p>
            )}
          </div>
        </div>
      </div>

      {/* Recent Matches */}
      <div className="card-glass-hover rounded-xl overflow-hidden">
        <div className="px-6 py-4 border-b border-border">
          <h3 className="text-lg font-semibold text-foreground">Recent Matches</h3>
        </div>
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-border">
            <thead className="bg-secondary/50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                  File
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                  Person
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                  Confidence
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                  Source
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider">
                  Date
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {stats?.recent_matches && stats.recent_matches.length > 0 ? (
                stats.recent_matches.map((match, index) => (
                  <tr key={index} className="table-row-hover-stripe">
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-foreground">
                      <span className="truncate max-w-xs inline-block" title={match.file_path}>
                        {match.file_path.split('/').pop()}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-foreground">
                      {match.person}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                        match.confidence >= 80
                          ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'
                          : match.confidence >= 60
                          ? 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200'
                          : 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200'
                      }`}>
                        {match.confidence.toFixed(1)}%
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getSourceColor(match.source || 'unknown')}`}>
                        {formatSourceName(match.source || 'unknown')}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-muted-foreground">
                      <div className="flex items-center">
                        <Clock className="w-4 h-4 mr-1" />
                        {formatDate(match.scan_date)}
                      </div>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={5} className="px-6 py-8 text-center text-muted-foreground">
                    No recent matches
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Scans Over Time */}
      {stats?.scans_over_time && stats.scans_over_time.length > 0 && (
        <div className="card-glass-hover rounded-xl">
          <div className="px-6 py-4 border-b border-border">
            <h3 className="text-lg font-semibold text-foreground">Scans Over Time (Last 30 Days)</h3>
          </div>
          <div className="p-6">
            <div className="space-y-2">
              {stats.scans_over_time.slice(-14).map((day, index) => {
                const maxScans = Math.max(...stats.scans_over_time.map(d => d.total_scans))
                const width = maxScans > 0 ? (day.total_scans / maxScans) * 100 : 0
                return (
                  <div key={index} className="flex items-center">
                    <div className="w-20 text-xs text-slate-600 dark:text-slate-400">
                      {new Date(day.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
                    </div>
                    <div className="flex-1 ml-4">
                      <div className="flex items-center">
                        <div className="w-full bg-slate-200 dark:bg-slate-700 rounded-full h-6 relative">
                          <div
                            className="bg-blue-600 dark:bg-blue-500 h-6 rounded-full flex items-center justify-end pr-2"
                            style={{ width: `${width}%`, minWidth: day.total_scans > 0 ? '40px' : '0' }}
                          >
                            {day.total_scans > 0 && (
                              <span className="text-xs font-medium text-white">
                                {day.total_scans}
                              </span>
                            )}
                          </div>
                        </div>
                        <span className="ml-2 text-xs text-slate-600 dark:text-slate-400 w-16">
                          {day.match_rate.toFixed(0)}% match
                        </span>
                      </div>
                    </div>
                  </div>
                )
              })}
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
