"use client"

import { useState, useCallback } from "react"
import { Button } from "@/components/ui/button"
import { AnimatedButton } from "@/components/ui/animated-button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { AnimatedCard } from "@/components/ui/animated-card"
import { Badge } from "@/components/ui/badge"
import { Progress } from "@/components/ui/progress"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { 
  Upload, 
  File, 
  FileSpreadsheet,
  CheckCircle, 
  AlertCircle,
  XCircle,
  Download,
  Eye,
  Trash2,
  RefreshCw,
  ArrowRight,
  Database,
  MapPin,
  Building,
  Users,
  Calendar,
  Filter
} from "lucide-react"
import { motion, AnimatePresence } from "framer-motion"
import { useDropzone } from "react-dropzone"

// Mock data for uploaded files
const mockUploadHistory = [
  {
    id: 1,
    fileName: "HHS_Facilities_January_2024.xlsx",
    uploadDate: "2024-01-15T10:30:00Z",
    status: "completed",
    recordsProcessed: 1247,
    recordsAdded: 1156,
    recordsUpdated: 91,
    duplicatesFound: 23,
    errorsFound: 0
  },
  {
    id: 2,
    fileName: "HHS_Facilities_December_2023.csv",
    uploadDate: "2024-01-02T14:20:00Z",
    status: "completed",
    recordsProcessed: 1198,
    recordsAdded: 1089,
    recordsUpdated: 109,
    duplicatesFound: 31,
    errorsFound: 2
  },
  {
    id: 3,
    fileName: "HHS_Facilities_November_2023.xlsx",
    uploadDate: "2023-12-15T09:45:00Z",
    status: "error",
    recordsProcessed: 0,
    recordsAdded: 0,
    recordsUpdated: 0,
    duplicatesFound: 0,
    errorsFound: 15
  }
]

// Mock column mapping data
const mockColumns = [
  { field: "name", label: "Facility Name", required: true, type: "text" },
  { field: "address", label: "Address", required: true, type: "text" },
  { field: "city", label: "City", required: true, type: "text" },
  { field: "state", label: "State", required: true, type: "text" },
  { field: "zipCode", label: "ZIP Code", required: true, type: "text" },
  { field: "phone", label: "Phone Number", required: false, type: "text" },
  { field: "email", label: "Email", required: false, type: "email" },
  { field: "licenseNumber", label: "License Number", required: true, type: "text" },
  { field: "careTypes", label: "Care Types", required: true, type: "array" },
  { field: "capacity", label: "Capacity", required: false, type: "number" },
  { field: "website", label: "Website", required: false, type: "url" }
]

interface UploadFile {
  file: File
  id: string
  status: "uploading" | "processing" | "mapping" | "completed" | "error"
  progress: number
  preview?: any[]
  mapping?: Record<string, string>
  errors?: string[]
  importResults?: {
    totalRows: number
    validRows: number
    imported: number
    duplicates: number
    validationErrors: number
    importErrors: number
    summary: {
      imported: number
      skippedDuplicates: number
      validationErrors: number
      importErrors: number
    }
  }
}

export default function AdminDataUploadPage() {
  const [uploadedFiles, setUploadedFiles] = useState<UploadFile[]>([])
  const [activeTab, setActiveTab] = useState("upload")
  const [isProcessing, setIsProcessing] = useState(false)

  const onDrop = useCallback((acceptedFiles: File[]) => {
    const newFiles: UploadFile[] = acceptedFiles.map(file => ({
      file,
      id: Math.random().toString(36).substr(2, 9),
      status: "uploading",
      progress: 0
    }))

    setUploadedFiles(prev => [...prev, ...newFiles])

    // Simulate upload process
    newFiles.forEach(uploadFile => {
      simulateUpload(uploadFile.id)
    })
  }, [])

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept: {
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx'],
      'application/vnd.ms-excel': ['.xls'],
      'text/csv': ['.csv']
    },
    multiple: true
  })

  const simulateUpload = async (fileId: string) => {
    // Simulate upload progress
    for (let i = 0; i <= 100; i += 10) {
      await new Promise(resolve => setTimeout(resolve, 200))
      setUploadedFiles(prev => prev.map(f => 
        f.id === fileId ? { ...f, progress: i } : f
      ))
    }

    // Simulate file processing and preview generation
    await new Promise(resolve => setTimeout(resolve, 1000))
    setUploadedFiles(prev => prev.map(f => 
      f.id === fileId ? { 
        ...f, 
        status: "mapping",
        preview: generateMockPreview()
      } : f
    ))
  }

  const generateMockPreview = () => [
    { "Facility Name": "Sunrise Senior Living", "Address": "123 Oak St", "City": "Springfield", "State": "IL", "ZIP": "62701" },
    { "Facility Name": "Golden Years Care", "Address": "456 Maple Ave", "City": "Springfield", "State": "IL", "ZIP": "62702" },
    { "Facility Name": "Peaceful Pines", "Address": "789 Pine St", "City": "Springfield", "State": "IL", "ZIP": "62703" }
  ]

  const handleColumnMapping = (fileId: string, csvColumn: string, dbField: string) => {
    setUploadedFiles(prev => prev.map(f => 
      f.id === fileId ? {
        ...f,
        mapping: { ...f.mapping, [csvColumn]: dbField }
      } : f
    ))
  }

  const processFile = async (fileId: string) => {
    setIsProcessing(true)
    const fileToProcess = uploadedFiles.find(f => f.id === fileId)
    
    if (!fileToProcess) {
      setIsProcessing(false)
      return
    }

    setUploadedFiles(prev => prev.map(f => 
      f.id === fileId ? { ...f, status: "processing" } : f
    ))

    try {
      // Create form data
      const formData = new FormData()
      formData.append('file', fileToProcess.file)

      // Get authentication token from localStorage
      const token = typeof window !== 'undefined' ? localStorage.getItem('geezer_guide_token') : null
      
      console.log('[Data Upload] Preparing import request:', {
        hasToken: !!token,
        tokenLength: token?.length,
        fileName: fileToProcess.file.name
      })
      
      // Prepare headers - Note: Don't set Content-Type for FormData, browser will set it with boundary
      const headers: HeadersInit = {}
      if (token) {
        headers.Authorization = `Bearer ${token}`
        console.log('[Data Upload] Authorization header set')
      } else {
        console.warn('[Data Upload] No token found in localStorage')
      }

      // Call import API
      const response = await fetch('/api/admin/facilities/import', {
        method: 'POST',
        headers,
        credentials: 'include', // Include cookies for authentication
        body: formData
      })

      console.log('[Data Upload] Import response:', {
        status: response.status,
        statusText: response.statusText,
        ok: response.ok
      })

      const result = await response.json()
      
      console.log('[Data Upload] Import result:', result)

      if (!response.ok) {
        // Handle HTTP errors
        const errorMessage = result.message || `HTTP ${response.status}: ${response.statusText}`
        console.error('[Data Upload] Import failed with status:', response.status, errorMessage)
        throw new Error(errorMessage)
      }

      if (result.success) {
        setUploadedFiles(prev => prev.map(f => 
          f.id === fileId ? { 
            ...f, 
            status: "completed",
            // Store import results for display
            importResults: result.data
          } : f
        ))
        
        // Show success toast with details
        alert(`Import Successful!\n\nImported: ${result.data.imported} facilities\nDuplicates skipped: ${result.data.duplicates}\nValidation errors: ${result.data.validationErrors}`)
      } else {
        throw new Error(result.message || 'Import failed')
      }
    } catch (error: any) {
      console.error('[Data Upload] Import error:', error)
      const errorMessage = error.message || 'Unknown error occurred'
      
      setUploadedFiles(prev => prev.map(f => 
        f.id === fileId ? { 
          ...f, 
          status: "error",
          errors: [errorMessage]
        } : f
      ))
      
      alert(`Import Failed: ${errorMessage}`)
    } finally {
      setIsProcessing(false)
    }
  }

  const removeFile = (fileId: string) => {
    setUploadedFiles(prev => prev.filter(f => f.id !== fileId))
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case "completed": return "text-green-700 bg-green-100"
      case "error": return "text-red-700 bg-red-100"
      case "processing": return "text-blue-700 bg-blue-100"
      case "uploading": return "text-yellow-700 bg-yellow-100"
      default: return "text-gray-700 bg-gray-100"
    }
  }

  const getStatusIcon = (status: string) => {
    switch (status) {
      case "completed": return <CheckCircle className="h-4 w-4" />
      case "error": return <XCircle className="h-4 w-4" />
      case "processing": return <RefreshCw className="h-4 w-4 animate-spin" />
      case "uploading": return <Upload className="h-4 w-4" />
      default: return <File className="h-4 w-4" />
    }
  }

  return (
    <div className="p-3 md:p-6 lg:p-8 space-y-4 md:space-y-6">
      {/* Header */}
      <div>
        <h1 className="font-primary text-2xl md:text-3xl lg:text-4xl font-bold text-gray-900 mb-2">
          Data Upload Center
        </h1>
        <p className="font-body text-sm md:text-base lg:text-lg text-gray-600">
          Upload and process HHS facility data spreadsheets
        </p>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 md:gap-6">
        <AnimatedCard className="bg-gradient-to-br from-blue-50 to-indigo-50 border-blue-200">
          <CardContent className="p-3 md:p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="font-body text-xs md:text-sm text-blue-700">Total Facilities</p>
                <p className="font-primary text-lg md:text-2xl font-bold text-blue-900">3,421</p>
              </div>
              <Building className="h-6 w-6 md:h-8 md:w-8 text-blue-600" />
            </div>
          </CardContent>
        </AnimatedCard>

        <AnimatedCard className="bg-gradient-to-br from-green-50 to-emerald-50 border-green-200">
          <CardContent className="p-3 md:p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="font-body text-xs md:text-sm text-green-700">Added This Month</p>
                <p className="font-primary text-lg md:text-2xl font-bold text-green-900">156</p>
              </div>
              <ArrowRight className="h-6 w-6 md:h-8 md:w-8 text-green-600" />
            </div>
          </CardContent>
        </AnimatedCard>

        <AnimatedCard className="bg-gradient-to-br from-orange-50 to-red-50 border-orange-200">
          <CardContent className="p-3 md:p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="font-body text-xs md:text-sm text-orange-700">Updated Records</p>
                <p className="font-primary text-lg md:text-2xl font-bold text-orange-900">91</p>
              </div>
              <RefreshCw className="h-6 w-6 md:h-8 md:w-8 text-orange-600" />
            </div>
          </CardContent>
        </AnimatedCard>

        <AnimatedCard className="bg-gradient-to-br from-purple-50 to-pink-50 border-purple-200">
          <CardContent className="p-3 md:p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="font-body text-xs md:text-sm text-purple-700">Processing Queue</p>
                <p className="font-primary text-lg md:text-2xl font-bold text-purple-900">{uploadedFiles.filter(f => f.status === "processing").length}</p>
              </div>
              <Database className="h-6 w-6 md:h-8 md:w-8 text-purple-600" />
            </div>
          </CardContent>
        </AnimatedCard>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
        <TabsList className="grid w-full grid-cols-3 h-12 md:h-16 bg-white border border-blue-200/50 rounded-xl shadow-sm">
          <TabsTrigger value="upload" className="text-xs md:text-lg font-body data-[state=active]:bg-[#3F5CEA] data-[state=active]:text-white">
            <Upload className="h-3 w-3 md:h-4 md:w-4 md:mr-2" />
            <span className="hidden sm:inline">Upload Files</span>
            <span className="sm:hidden">Upload</span>
          </TabsTrigger>
          <TabsTrigger value="processing" className="text-xs md:text-lg font-body data-[state=active]:bg-[#3F5CEA] data-[state=active]:text-white">
            <RefreshCw className="h-3 w-3 md:h-4 md:w-4 md:mr-2" />
            <span className="hidden sm:inline">Processing Queue</span>
            <span className="sm:hidden">Processing</span>
          </TabsTrigger>
          <TabsTrigger value="history" className="text-xs md:text-lg font-body data-[state=active]:bg-[#3F5CEA] data-[state=active]:text-white">
            <Calendar className="h-3 w-3 md:h-4 md:w-4 md:mr-2" />
            <span className="hidden sm:inline">Upload History</span>
            <span className="sm:hidden">History</span>
          </TabsTrigger>
        </TabsList>

        {/* Upload Tab */}
        <TabsContent value="upload" className="mt-8">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
            {/* File Upload Area */}
            <AnimatedCard>
              <CardHeader>
                <CardTitle className="font-primary text-xl text-gray-900">Upload Spreadsheet</CardTitle>
                <p className="font-body text-gray-600">
                  Upload HHS facility data files (Excel or CSV format)
                </p>
              </CardHeader>
              <CardContent>
                <div
                  {...getRootProps()}
                  className={`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-all duration-300 ${
                    isDragActive 
                      ? "border-[#3F5CEA] bg-blue-50" 
                      : "border-gray-300 hover:border-[#3F5CEA] hover:bg-gray-50"
                  }`}
                >
                  <input {...getInputProps()} />
                  <div className="space-y-4">
                    <div className="mx-auto w-16 h-16 bg-gradient-to-br from-[#3F5CEA] to-[#09183D] rounded-full flex items-center justify-center">
                      <Upload className="h-8 w-8 text-white" />
                    </div>
                    
                    {isDragActive ? (
                      <div>
                        <p className="font-body text-lg font-medium text-[#3F5CEA]">
                          Drop the files here...
                        </p>
                      </div>
                    ) : (
                      <div>
                        <p className="font-body text-lg font-medium text-gray-900 mb-2">
                          Drag & drop files here
                        </p>
                        <p className="font-body text-gray-600 mb-4">
                          or click to browse files
                        </p>
                        <AnimatedButton className="bg-gradient-to-r from-[#3F5CEA] to-[#5B73F0] hover:from-[#09183D] hover:to-[#3F5CEA] text-white">
                          Choose Files
                        </AnimatedButton>
                      </div>
                    )}
                  </div>
                </div>

                <div className="mt-4 p-4 bg-gray-50 rounded-lg">
                  <h4 className="font-body font-medium text-gray-900 mb-2">Supported Formats:</h4>
                  <div className="flex flex-wrap gap-2">
                    <Badge variant="secondary" className="bg-green-100 text-green-800">
                      <FileSpreadsheet className="h-3 w-3 mr-1" />
                      .xlsx
                    </Badge>
                    <Badge variant="secondary" className="bg-green-100 text-green-800">
                      <FileSpreadsheet className="h-3 w-3 mr-1" />
                      .xls
                    </Badge>
                    <Badge variant="secondary" className="bg-green-100 text-green-800">
                      <File className="h-3 w-3 mr-1" />
                      .csv
                    </Badge>
                  </div>
                </div>
              </CardContent>
            </AnimatedCard>

            {/* Upload Guidelines */}
            <AnimatedCard>
              <CardHeader>
                <CardTitle className="font-primary text-xl text-gray-900">Upload Guidelines</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-3">
                  <div className="flex items-start gap-3">
                    <CheckCircle className="h-5 w-5 text-green-600 mt-0.5" />
                    <div>
                      <p className="font-body font-medium text-gray-900">Required Columns</p>
                      <p className="font-body text-sm text-gray-600">
                        Facility name, address, city, state, ZIP code, license number
                      </p>
                    </div>
                  </div>

                  <div className="flex items-start gap-3">
                    <CheckCircle className="h-5 w-5 text-green-600 mt-0.5" />
                    <div>
                      <p className="font-body font-medium text-gray-900">File Size Limit</p>
                      <p className="font-body text-sm text-gray-600">
                        Maximum 50MB per file, up to 10,000 records
                      </p>
                    </div>
                  </div>

                  <div className="flex items-start gap-3">
                    <CheckCircle className="h-5 w-5 text-green-600 mt-0.5" />
                    <div>
                      <p className="font-body font-medium text-gray-900">Data Validation</p>
                      <p className="font-body text-sm text-gray-600">
                        Automatic duplicate detection and data quality checks
                      </p>
                    </div>
                  </div>

                  <div className="flex items-start gap-3">
                    <AlertCircle className="h-5 w-5 text-yellow-600 mt-0.5" />
                    <div>
                      <p className="font-body font-medium text-gray-900">Processing Time</p>
                      <p className="font-body text-sm text-gray-600">
                        Large files may take several minutes to process
                      </p>
                    </div>
                  </div>
                </div>

                <div className="pt-4 border-t border-gray-200">
                  <Button variant="outline" className="w-full border-[#3F5CEA] text-[#3F5CEA] hover:bg-[#3F5CEA] hover:text-white">
                    <Download className="h-4 w-4 mr-2" />
                    Download Template
                  </Button>
                </div>
              </CardContent>
            </AnimatedCard>
          </div>

          {/* Current Uploads */}
          <AnimatePresence>
            {uploadedFiles.length > 0 && (
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -20 }}
                className="mt-8"
              >
                <AnimatedCard>
                  <CardHeader>
                    <CardTitle className="font-primary text-xl text-gray-900">Current Uploads</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      {uploadedFiles.map(file => (
                        <div key={file.id} className="border border-gray-200 rounded-lg p-4">
                          <div className="flex items-center justify-between mb-3">
                            <div className="flex items-center gap-3">
                              <FileSpreadsheet className="h-6 w-6 text-[#3F5CEA]" />
                              <div>
                                <p className="font-body font-medium text-gray-900">{file.file.name}</p>
                                <p className="font-body text-sm text-gray-600">
                                  {(file.file.size / 1024 / 1024).toFixed(2)} MB
                                </p>
                              </div>
                            </div>
                            <div className="flex items-center gap-2">
                              <Badge className={getStatusColor(file.status)}>
                                {getStatusIcon(file.status)}
                                <span className="ml-1 capitalize">{file.status}</span>
                              </Badge>
                              <Button 
                                variant="outline" 
                                size="sm"
                                onClick={() => removeFile(file.id)}
                                className="border-red-300 text-red-700 hover:bg-red-50"
                              >
                                <Trash2 className="h-4 w-4" />
                              </Button>
                            </div>
                          </div>

                          {file.status === "uploading" && (
                            <Progress value={file.progress} className="mb-3" />
                          )}

                          {file.status === "mapping" && file.preview && (
                            <div className="space-y-4">
                              <div className="bg-gray-50 p-3 rounded-lg">
                                <h4 className="font-body font-medium text-gray-900 mb-2">
                                  Column Mapping Required
                                </h4>
                                <p className="font-body text-sm text-gray-600 mb-3">
                                  Map your spreadsheet columns to database fields
                                </p>
                                
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                  {Object.keys(file.preview[0]).map(column => (
                                    <div key={column} className="flex items-center gap-2">
                                      <span className="font-body text-sm font-medium text-gray-700 w-24 truncate">
                                        {column}:
                                      </span>
                                      <Select
                                        value={file.mapping?.[column] || "none"}
                                        onValueChange={(value) => {
                                          // Only update mapping if value is not "none"
                                          if (value !== "none") {
                                            handleColumnMapping(file.id, column, value)
                                          } else {
                                            // Remove mapping if "none" is selected
                                            const newMapping = { ...file.mapping }
                                            delete newMapping[column]
                                            setUploadedFiles(prev => prev.map(f => 
                                              f.id === file.id ? {
                                                ...f,
                                                mapping: newMapping
                                              } : f
                                            ))
                                          }
                                        }}
                                      >
                                        <SelectTrigger className="flex-1">
                                          <SelectValue placeholder="Select field" />
                                        </SelectTrigger>
                                        <SelectContent>
                                          <SelectItem value="none">-- No mapping --</SelectItem>
                                          {mockColumns.map(col => (
                                            <SelectItem key={col.field} value={col.field}>
                                              {col.label} {col.required && "*"}
                                            </SelectItem>
                                          ))}
                                        </SelectContent>
                                      </Select>
                                    </div>
                                  ))}
                                </div>
                              </div>

                              <div className="flex justify-end gap-2">
                                <Button variant="outline" onClick={() => removeFile(file.id)}>
                                  Cancel
                                </Button>
                                <AnimatedButton 
                                  onClick={() => processFile(file.id)}
                                  disabled={isProcessing}
                                  className="bg-gradient-to-r from-[#3F5CEA] to-[#5B73F0] hover:from-[#09183D] hover:to-[#3F5CEA] text-white"
                                >
                                  Process File
                                </AnimatedButton>
                              </div>
                            </div>
                          )}

                          {file.status === "completed" && (
                            <div className="bg-green-50 p-3 rounded-lg space-y-3">
                              <p className="font-body text-sm font-semibold text-green-800">
                                ✅ File processed successfully!
                              </p>
                              {file.importResults && (
                                <div className="grid grid-cols-2 md:grid-cols-4 gap-2">
                                  <div className="text-center bg-white p-2 rounded">
                                    <p className="font-primary text-lg font-bold text-green-700">{file.importResults.imported}</p>
                                    <p className="font-body text-xs text-gray-600">Imported</p>
                                  </div>
                                  <div className="text-center bg-white p-2 rounded">
                                    <p className="font-primary text-lg font-bold text-orange-700">{file.importResults.duplicates}</p>
                                    <p className="font-body text-xs text-gray-600">Duplicates</p>
                                  </div>
                                  <div className="text-center bg-white p-2 rounded">
                                    <p className="font-primary text-lg font-bold text-blue-700">{file.importResults.totalRows}</p>
                                    <p className="font-body text-xs text-gray-600">Total Rows</p>
                                  </div>
                                  <div className="text-center bg-white p-2 rounded">
                                    <p className="font-primary text-lg font-bold text-red-700">{file.importResults.validationErrors}</p>
                                    <p className="font-body text-xs text-gray-600">Errors</p>
                                  </div>
                                </div>
                              )}
                            </div>
                          )}

                          {file.status === "error" && file.errors && file.errors.length > 0 && (
                            <div className="bg-red-50 p-3 rounded-lg">
                              <p className="font-body text-sm font-semibold text-red-800 mb-2">
                                ❌ Import failed
                              </p>
                              <ul className="list-disc list-inside text-xs text-red-700 space-y-1">
                                {file.errors.map((error, idx) => (
                                  <li key={idx}>{error}</li>
                                ))}
                              </ul>
                            </div>
                          )}
                        </div>
                      ))}
                    </div>
                  </CardContent>
                </AnimatedCard>
              </motion.div>
            )}
          </AnimatePresence>
        </TabsContent>

        {/* Processing Queue Tab */}
        <TabsContent value="processing" className="mt-8">
          <AnimatedCard>
            <CardHeader>
              <CardTitle className="font-primary text-xl text-gray-900">Processing Queue</CardTitle>
              <p className="font-body text-gray-600">Files currently being processed</p>
            </CardHeader>
            <CardContent>
              {uploadedFiles.filter(f => f.status === "processing").length === 0 ? (
                <div className="text-center py-12">
                  <RefreshCw className="h-16 w-16 text-gray-300 mx-auto mb-4" />
                  <h3 className="font-body text-lg font-medium text-gray-900 mb-2">No files processing</h3>
                  <p className="font-body text-gray-600">Upload files to see them in the processing queue</p>
                </div>
              ) : (
                <div className="space-y-4">
                  {uploadedFiles.filter(f => f.status === "processing").map(file => (
                    <div key={file.id} className="border border-gray-200 rounded-lg p-4">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-3">
                          <RefreshCw className="h-6 w-6 text-[#3F5CEA] animate-spin" />
                          <div>
                            <p className="font-body font-medium text-gray-900">{file.file.name}</p>
                            <p className="font-body text-sm text-gray-600">Processing facility data...</p>
                          </div>
                        </div>
                        <Badge className="text-blue-700 bg-blue-100">
                          <RefreshCw className="h-4 w-4 mr-1 animate-spin" />
                          Processing
                        </Badge>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </AnimatedCard>
        </TabsContent>

        {/* History Tab */}
        <TabsContent value="history" className="mt-8">
          <AnimatedCard>
            <CardHeader>
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle className="font-primary text-xl text-gray-900">Upload History</CardTitle>
                  <p className="font-body text-gray-600">Previous data uploads and processing results</p>
                </div>
                <Button variant="outline" className="border-[#3F5CEA] text-[#3F5CEA] hover:bg-[#3F5CEA] hover:text-white">
                  <Filter className="h-4 w-4 mr-2" />
                  Filter
                </Button>
              </div>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {mockUploadHistory.map(upload => (
                  <div key={upload.id} className="border border-gray-200 rounded-lg p-4">
                    <div className="flex items-start justify-between mb-3">
                      <div className="flex items-center gap-3">
                        <FileSpreadsheet className="h-6 w-6 text-[#3F5CEA]" />
                        <div>
                          <p className="font-body font-medium text-gray-900">{upload.fileName}</p>
                          <p className="font-body text-sm text-gray-600">
                            {new Date(upload.uploadDate).toLocaleDateString()} at{" "}
                            {new Date(upload.uploadDate).toLocaleTimeString()}
                          </p>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        <Badge className={getStatusColor(upload.status)}>
                          {getStatusIcon(upload.status)}
                          <span className="ml-1 capitalize">{upload.status}</span>
                        </Badge>
                        <Button variant="outline" size="sm">
                          <Eye className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>

                    {upload.status === "completed" && (
                      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 bg-gray-50 p-3 rounded-lg">
                        <div className="text-center">
                          <p className="font-primary text-lg font-bold text-gray-900">{upload.recordsProcessed}</p>
                          <p className="font-body text-xs text-gray-600">Processed</p>
                        </div>
                        <div className="text-center">
                          <p className="font-primary text-lg font-bold text-green-700">{upload.recordsAdded}</p>
                          <p className="font-body text-xs text-gray-600">Added</p>
                        </div>
                        <div className="text-center">
                          <p className="font-primary text-lg font-bold text-blue-700">{upload.recordsUpdated}</p>
                          <p className="font-body text-xs text-gray-600">Updated</p>
                        </div>
                        <div className="text-center">
                          <p className="font-primary text-lg font-bold text-orange-700">{upload.duplicatesFound}</p>
                          <p className="font-body text-xs text-gray-600">Duplicates</p>
                        </div>
                      </div>
                    )}

                    {upload.status === "error" && (
                      <div className="bg-red-50 p-3 rounded-lg">
                        <p className="font-body text-sm text-red-800">
                          Processing failed with {upload.errorsFound} errors. 
                          <Button variant="link" className="text-red-700 p-0 h-auto ml-1">
                            View error details
                          </Button>
                        </p>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </CardContent>
          </AnimatedCard>
        </TabsContent>
      </Tabs>
    </div>
  )
}