"use client"

import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { 
  CheckCircle, 
  XCircle, 
  Clock,
  RefreshCw,
  AlertCircle,
  Copy,
  Filter,
  Search,
  Edit,
  Zap,
  Files,
  Bell,
  BarChart3
} from 'lucide-react'
import { adminApi, formatDate, getStatusColor, getComplexityColor } from '@/lib/api/admin'
import { AdminFeature, AdminTemplate, AdminStats } from '@/types/admin.types'
import { FeatureReviewDialog } from './feature-review-dialog'
import { AdminNotificationsPanel } from './admin-notifications-panel'
import { FeatureEditDialog } from './feature-edit-dialog'
import { TemplateEditDialog } from './template-edit-dialog'
import { RejectDialog } from './reject-dialog'
import { Input } from '@/components/ui/input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { AdminNotificationProvider, useAdminNotifications } from '@/contexts/AdminNotificationContext'
import { useSearchParams } from 'next/navigation'

function AdminDashboardContent() {
  const searchParams = useSearchParams()
  const activeTab = searchParams.get('tab') || 'dashboard'
  const filterParam = searchParams.get('filter') || 'all'
  
  const [pendingFeatures, setPendingFeatures] = useState<AdminFeature[]>([])
  const [customTemplates, setCustomTemplates] = useState<AdminTemplate[]>([])
  const [stats, setStats] = useState<AdminStats | null>(null)
  const [templateStats, setTemplateStats] = useState<AdminStats | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [selectedFeature, setSelectedFeature] = useState<AdminFeature | null>(null)
  const [selectedTemplate, setSelectedTemplate] = useState<AdminTemplate | null>(null)
  const [showReviewDialog, setShowReviewDialog] = useState(false)
  const [showFeatureEditDialog, setShowFeatureEditDialog] = useState(false)
  const [showTemplateEditDialog, setShowTemplateEditDialog] = useState(false)
  const [showRejectDialog, setShowRejectDialog] = useState(false)
  const [rejectItem, setRejectItem] = useState<{ id: string; name: string; type: 'feature' | 'template' } | null>(null)
  const [showNotifications, setShowNotifications] = useState(false)
  const [searchQuery, setSearchQuery] = useState('')
  const [statusFilter, setStatusFilter] = useState<string>(filterParam)
  
  const { unreadCount, removeByReference } = useAdminNotifications()

  // Load dashboard data
  const loadDashboardData = async () => {
    try {
      setLoading(true)
      setError(null)

      const [featuresResponse, templatesResponse, featureStatsResponse, templateStatsResponse] = await Promise.all([
        adminApi.getCustomFeatures('pending'),
        adminApi.getCustomTemplates('pending'),
        adminApi.getCustomFeatureStats(),
        adminApi.getTemplateStats()
      ])

      setPendingFeatures(featuresResponse || [])
      setCustomTemplates(templatesResponse || [])
      setStats(featureStatsResponse)
      setTemplateStats(templateStatsResponse)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load dashboard data')
      console.error('Error loading dashboard data:', err)
    } finally {
      setLoading(false)
    }
  }

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

  // Handle feature review
  const handleFeatureReview = async (featureId: string, reviewData: { status: 'approved' | 'rejected' | 'duplicate'; admin_notes?: string; admin_reviewed_by: string }) => {
    try {
      await adminApi.reviewFeature(featureId, reviewData)
      
      // Update the feature in the list
      setPendingFeatures(prev => prev.map(f => 
        f.id === featureId ? { ...f, status: reviewData.status as AdminFeature['status'], admin_notes: reviewData.admin_notes } : f
      ))
      
      // Reload stats
      const newStats = await adminApi.getFeatureStats()
      setStats(newStats)
      
      setShowReviewDialog(false)
      setSelectedFeature(null)
    } catch (err) {
      console.error('Error reviewing feature:', err)
      // Handle error (show toast notification, etc.)
      alert('Error reviewing feature')
    }
  }

  // Handle template review
  const handleTemplateReview = async (templateId: string, reviewData: { status: 'pending' | 'approved' | 'rejected' | 'duplicate'; admin_notes?: string }) => {
    try {
      await adminApi.reviewTemplate(templateId, reviewData)
      
      // Update the template in the list
      setCustomTemplates(prev => prev.map(t => 
        t.id === templateId ? { ...t, status: reviewData.status as AdminTemplate['status'], admin_notes: reviewData.admin_notes } : t
      ))
      
      // Reload stats
      const newStats = await adminApi.getTemplateStats()
      setTemplateStats(newStats)
      
    } catch (err) {
      console.error('Error reviewing template:', err)
      // Handle error (show toast notification, etc.)
      alert('Error reviewing template')
    }
  }

  // Handle feature update
  const handleFeatureUpdate = (featureId: string, updatedFeature: AdminFeature) => {
    setPendingFeatures(prev => prev.map(f => 
      f.id === featureId ? updatedFeature : f
    ))
  }

  // Handle template update
  const handleTemplateUpdate = (templateId: string, updatedTemplate: AdminTemplate) => {
    // Hide the edited item from the pending list immediately
    setCustomTemplates(prev => prev.filter(t => t.id !== templateId))
  }

  // Handle reject action
  const handleReject = async (adminNotes: string) => {
    if (!rejectItem) return

    try {
      if (rejectItem.type === 'feature') {
        await adminApi.rejectCustomFeature(rejectItem.id, adminNotes)
        setPendingFeatures(prev => prev.map(f => 
          f.id === rejectItem.id ? { ...f, status: 'rejected', admin_notes: adminNotes } : f
        ))
        // Reload feature stats
        const newStats = await adminApi.getCustomFeatureStats()
        setStats(newStats)
      } else {
        await adminApi.rejectTemplate(rejectItem.id, adminNotes)
        setCustomTemplates(prev => prev.map(t => 
          t.id === rejectItem.id ? { ...t, status: 'rejected', admin_notes: adminNotes } : t
        ))
        // Reload template stats
        const newStats = await adminApi.getTemplateStats()
        setTemplateStats(newStats)
      }
    } catch (err) {
      console.error(`Error rejecting ${rejectItem.type}:`, err)
      // Handle error (show toast notification, etc.)
      alert(`Error rejecting ${rejectItem.type}`)
    }
  }

  // Handle approve action
  const handleApprove = async (item: { id: string; type: 'feature' | 'template' }) => {
    // Optimistic UI: remove immediately
    if (item.type === 'feature') {
      setPendingFeatures(prev => prev.filter(f => f.id !== item.id))
    } else {
      setCustomTemplates(prev => prev.filter(t => t.id !== item.id))
    }
    try {
      if (item.type === 'feature') {
        // Get the feature details first
        const feature = pendingFeatures.find(f => f.id === item.id)
        if (feature) {
          // Create new approved feature in main template_features table
          await adminApi.createApprovedFeature({
            template_id: feature.template_id,
            name: feature.name,
            description: feature.description,
            complexity: feature.complexity,
            business_rules: feature.business_rules,
            technical_requirements: feature.technical_requirements
          })
          
          // Update the custom feature status to approved
          await adminApi.reviewCustomFeature(item.id, { status: 'approved', admin_notes: 'Approved and created in main templates' })
          
          // already optimistically removed
          // Remove related notifications for this feature
          removeByReference('custom_feature', item.id)
        }
        
        // Reload feature stats
        const newStats = await adminApi.getCustomFeatureStats()
        setStats(newStats)
      } else {
        // Get the template details first
        const template = customTemplates.find(t => t.id === item.id)
        if (template) {
          // Create new approved template in main templates table
          await adminApi.createApprovedTemplate(item.id, {
            title: template.title || '',
            description: template.description,
            category: template.category || '',
            type: template.type || '',
            icon: template.icon,
            gradient: template.gradient,
            border: template.border,
            text: template.text,
            subtext: template.subtext
          })
          
          // Update the custom template status to approved
          await adminApi.reviewTemplate(item.id, { status: 'approved', admin_notes: 'Approved and created in main templates' })
          
          // already optimistically removed
          // Remove related notifications for this template
          removeByReference('custom_template', item.id)
        }
        
        // Reload template stats
        const newStats = await adminApi.getTemplateStats()
        setTemplateStats(newStats)
      }
    } catch (err) {
      console.error(`Error approving ${item.type}:`, err)
      // Handle error (show toast notification, etc.)
      // Recover UI by reloading if optimistic removal was wrong
      await loadDashboardData()
    }
  }

  // Filter features based on search and status
  const filteredFeatures = pendingFeatures.filter(feature => {
    const matchesSearch = feature.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         feature.description?.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         feature.template_title?.toLowerCase().includes(searchQuery.toLowerCase())
    
    const matchesStatus = statusFilter === 'all' || feature.status === statusFilter
    
    return matchesSearch && matchesStatus
  })

  // Get status counts for features
  const getFeatureStatusCount = (status: string) => {
    return stats?.features?.find(s => s.status === status)?.count || 0
  }

  // Get status counts for templates
  const getTemplateStatusCount = (status: string) => {
    return (templateStats as AdminStats & { templates?: Array<{ status: string; count: number }> })?.templates?.find((s) => s.status === status)?.count || 0
  }


  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="flex items-center space-x-2">
          <RefreshCw className="h-6 w-6 animate-spin" />
          <span>Loading admin dashboard...</span>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <Card className="w-full max-w-md">
          <CardContent className="pt-6">
            <div className="flex items-center space-x-2 text-red-600">
              <AlertCircle className="h-6 w-6" />
              <span>Error loading dashboard</span>
            </div>
            <p className="mt-2 text-sm text-gray-600">{error}</p>
            <Button onClick={loadDashboardData} className="mt-4">
              <RefreshCw className="h-4 w-4 mr-2" />
              Retry
            </Button>
          </CardContent>
        </Card>
      </div>
    )
  }

  const renderDashboardOverview = () => (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-white">Admin Dashboard</h1>
          <p className="text-white/70">Manage feature approvals and system notifications</p>
        </div>
        <div className="flex items-center space-x-2">
          <Button onClick={loadDashboardData} className="bg-orange-500 text-black hover:bg-orange-600">
            <RefreshCw className="h-4 w-4 mr-2" />
            Refresh
          </Button>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* Features Stats */}
        <Card className="bg-gray-900 border-gray-800">
          <CardHeader>
            <CardTitle className="text-lg font-semibold text-white">Custom Features</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 gap-4">
              <div className="flex items-center space-x-2">
                <Clock className="h-4 w-4 text-yellow-600" />
                <div>
                  <p className="text-xs text-white/60">Pending</p>
                  <p className="text-xl font-bold text-white">{getFeatureStatusCount('pending')}</p>
                </div>
              </div>
              <div className="flex items-center space-x-2">
                <CheckCircle className="h-4 w-4 text-green-500" />
                <div>
                  <p className="text-xs text-white/60">Approved</p>
                  <p className="text-xl font-bold text-white">{getFeatureStatusCount('approved')}</p>
                </div>
              </div>
              <div className="flex items-center space-x-2">
                <XCircle className="h-4 w-4 text-red-500" />
                <div>
                  <p className="text-xs text-white/60">Rejected</p>
                  <p className="text-xl font-bold text-white">{getFeatureStatusCount('rejected')}</p>
                </div>
              </div>
              <div className="flex items-center space-x-2">
                <Copy className="h-4 w-4 text-orange-500" />
                <div>
                  <p className="text-xs text-white/60">Duplicates</p>
                  <p className="text-xl font-bold text-white">{getFeatureStatusCount('duplicate')}</p>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Templates Stats */}
        <Card className="bg-gray-900 border-gray-800">
          <CardHeader>
            <CardTitle className="text-lg font-semibold text-white">Custom Templates</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 gap-4">
              <div className="flex items-center space-x-2">
                <Clock className="h-4 w-4 text-yellow-600" />
                <div>
                  <p className="text-xs text-white/60">Pending</p>
                  <p className="text-xl font-bold text-white">{getTemplateStatusCount('pending')}</p>
                </div>
              </div>
              <div className="flex items-center space-x-2">
                <CheckCircle className="h-4 w-4 text-green-500" />
                <div>
                  <p className="text-xs text-white/60">Approved</p>
                  <p className="text-xl font-bold text-white">{getTemplateStatusCount('approved')}</p>
                </div>
              </div>
              <div className="flex items-center space-x-2">
                <XCircle className="h-4 w-4 text-red-500" />
                <div>
                  <p className="text-xs text-white/60">Rejected</p>
                  <p className="text-xl font-bold text-white">{getTemplateStatusCount('rejected')}</p>
                </div>
              </div>
              <div className="flex items-center space-x-2">
                <Copy className="h-4 w-4 text-orange-500" />
                <div>
                  <p className="text-xs text-white/60">Duplicates</p>
                  <p className="text-xl font-bold text-white">{getTemplateStatusCount('duplicate')}</p>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Quick Actions */}
      <Card className="bg-gray-900 border-gray-800">
        <CardHeader>
          <CardTitle className="text-lg font-semibold text-white">Quick Actions</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <Button 
              variant="outline" 
              className="h-20 flex flex-col items-center justify-center space-y-2 border-white/20 text-white hover:bg-white/10"
              onClick={() => window.location.href = '/admin?tab=features'}
            >
              <Zap className="h-6 w-6" />
              <span className="text-sm">Review Features</span>
            </Button>
            <Button 
              variant="outline" 
              className="h-20 flex flex-col items-center justify-center space-y-2 border-white/20 text-white hover:bg-white/10"
              onClick={() => window.location.href = '/admin?tab=templates'}
            >
              <Files className="h-6 w-6" />
              <span className="text-sm">Review Templates</span>
            </Button>
            <Button 
              variant="outline" 
              className="h-20 flex flex-col items-center justify-center space-y-2 border-white/20 text-white hover:bg-white/10"
              onClick={() => setShowNotifications(true)}
            >
              <Bell className="h-6 w-6" />
              <span className="text-sm">Notifications</span>
              {unreadCount > 0 && (
                <Badge className="bg-red-500 text-white text-xs">{unreadCount}</Badge>
              )}
            </Button>
            <Button 
              variant="outline" 
              className="h-20 flex flex-col items-center justify-center space-y-2 border-white/20 text-white hover:bg-white/10"
            >
              <BarChart3 className="h-6 w-6" />
              <span className="text-sm">Analytics</span>
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  )

  return (
    <div className="space-y-6">
      {activeTab === 'dashboard' && renderDashboardOverview()}
      
      {(activeTab === 'features' || activeTab === 'templates') && (
        <>
          {/* Header */}
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-3xl font-bold text-white">
                {activeTab === 'features' ? 'Custom Features' : 'Custom Templates'}
              </h1>
              <p className="text-white/70">
                {activeTab === 'features' 
                  ? 'Review and manage custom feature requests' 
                  : 'Review and manage custom template submissions'
                }
              </p>
            </div>
            <div className="flex items-center space-x-2">
              <Button onClick={loadDashboardData} className="bg-orange-500 text-black hover:bg-orange-600">
                <RefreshCw className="h-4 w-4 mr-2" />
                Refresh
              </Button>
            </div>
          </div>
        </>
      )}

      {/* Main Content - Only show for features/templates tabs */}
      {activeTab === 'features' && (
        <div className="space-y-4">

          {/* Filters */}
          <div className="flex items-center space-x-4">
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
                <Input
                  placeholder="Search features..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-10"
                />
              </div>
            </div>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-48">
                <SelectValue placeholder="Filter by status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Status</SelectItem>
                <SelectItem value="pending">Pending</SelectItem>
                <SelectItem value="approved">Approved</SelectItem>
                <SelectItem value="rejected">Rejected</SelectItem>
                <SelectItem value="duplicate">Duplicate</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* Features List */}
          <div className="space-y-4">
            {filteredFeatures.length === 0 ? (
              <Card>
                <CardContent className="pt-6">
                  <div className="text-center text-gray-500">
                    <Clock className="h-12 w-12 mx-auto mb-4 text-gray-300" />
                    <p>No features found</p>
                    <p className="text-sm">All features have been reviewed or no features match your filters.</p>
                  </div>
                </CardContent>
              </Card>
            ) : (
              filteredFeatures.map((feature) => (
                <Card key={feature.id} className="hover:shadow-md transition-shadow">
                  <CardContent className="pt-6">
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center space-x-2 mb-2">
                          <h3 className="text-lg font-semibold">{feature.name}</h3>
                          <Badge className={getStatusColor(feature.status)}>
                            {feature.status}
                          </Badge>
                          <Badge className={getComplexityColor(feature.complexity)}>
                            {feature.complexity}
                          </Badge>
                        </div>
                        
                        {feature.description && (
                          <p className="text-gray-600 mb-2">{feature.description}</p>
                        )}
                        
                        <div className="flex items-center space-x-4 text-sm text-gray-500">
                          <span>Template: {feature.template_title || 'Unknown'}</span>
                          <span>Submitted: {formatDate(feature.created_at)}</span>
                          {feature.similarity_score && (
                            <span>Similarity: {(feature.similarity_score * 100).toFixed(1)}%</span>
                          )}
                        </div>

                        {feature.admin_notes && (
                          <div className="mt-2 p-2 bg-gray-50 rounded">
                            <p className="text-sm text-gray-600">
                              <strong>Admin Notes:</strong> {feature.admin_notes}
                            </p>
                          </div>
                        )}
                      </div>
                      
                      <div className="flex items-center space-x-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleApprove({ id: feature.id, type: 'feature' })}
                          className="text-green-600 hover:text-green-700 hover:bg-green-50"
                        >
                          <CheckCircle className="h-4 w-4 mr-1" />
                          Approve
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => {
                            setRejectItem({ id: feature.id, name: feature.name, type: 'feature' })
                            setShowRejectDialog(true)
                          }}
                          className="text-red-600 hover:text-red-700 hover:bg-red-50"
                        >
                          <XCircle className="h-4 w-4 mr-1" />
                          Reject
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => {
                            setSelectedFeature(feature)
                            setShowFeatureEditDialog(true)
                          }}
                          className="text-blue-600 hover:text-blue-700 hover:bg-blue-50"
                        >
                          <Edit className="h-4 w-4 mr-1" />
                          Edit
                        </Button>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ))
            )}
          </div>
        </div>
      )}

      {/* Feature Edit Dialog */}
      {selectedFeature && (
        <FeatureEditDialog
          feature={selectedFeature}
          open={showFeatureEditDialog}
          onOpenChange={setShowFeatureEditDialog}
          onUpdate={handleFeatureUpdate}
        />
      )}

      {/* Reject Dialog */}
      {rejectItem && (
        <RejectDialog
          open={showRejectDialog}
          onOpenChange={setShowRejectDialog}
          onReject={handleReject}
          title={`Reject ${rejectItem.type === 'feature' ? 'Feature' : 'Template'}`}
          itemName={rejectItem.name}
          itemType={rejectItem.type}
        />
      )}
    </div>
  )
}

export function AdminDashboard() {
  return (
    <AdminNotificationProvider>
      <AdminDashboardContent />
    </AdminNotificationProvider>
  )
}
