"use client"

import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Switch } from "@/components/ui/switch"
import { Textarea } from "@/components/ui/textarea"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { useToast } from "@/components/ui/toast"
import { DataAPI } from "@/lib/data-api"
import { 
  Search, 
  Loader2,
  RefreshCw,
  CheckCircle, 
  XCircle, 
  Clock, 
  Star, 
  MapPin, 
  Building
} from "lucide-react"

export default function AdminFacilitiesPage() {
  const toast = useToast()
  
  // Data states
  const [facilities, setFacilities] = useState<any[]>([])
  const [stats, setStats] = useState({ total: 0, active: 0, pending: 0, suspended: 0, averageRating: 0 })
  
  // Loading states
  const [loading, setLoading] = useState(true)
  const [statsLoading, setStatsLoading] = useState(true)
  const [updatingId, setUpdatingId] = useState<string | null>(null)
  
  // Filter states
  const [searchTerm, setSearchTerm] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")
  const [typeFilter, setTypeFilter] = useState("all")
  const [sortBy, setSortBy] = useState("createdAt")
  const [sortOrder, setSortOrder] = useState("desc")
  
  // Pagination
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [totalPages, setTotalPages] = useState(1)
  
  // Dialog states
  const [showConfirmDialog, setShowConfirmDialog] = useState(false)
  const [showReasonDialog, setShowReasonDialog] = useState(false)
  const [dialogAction, setDialogAction] = useState<{ type: 'approve' | 'suspend' | 'verify'; facilityId: string; facilityName: string } | null>(null)
  const [suspensionReason, setSuspensionReason] = useState("")

  // Load facilities
  const loadFacilities = async () => {
    try {
      setLoading(true)
      
      const response = await DataAPI.admin.getFacilities({
        page: currentPage,
        limit: pageSize,
        status: statusFilter !== 'all' ? statusFilter : undefined,
        search: searchTerm || undefined,
        sortBy,
        sortOrder
      })

      if (response.success && response.data) {
        setFacilities(response.data.facilities)
        if (response.data.pagination) {
          setTotalPages(response.data.pagination.totalPages)
        }
      }
    } catch (error: any) {
      toast.error("Failed to load facilities", { title: "Error" })
    } finally {
      setLoading(false)
    }
  }

  // Load stats
  const loadStats = async () => {
    try {
      setStatsLoading(true)
      const response = await DataAPI.admin.getFacilityStats()
      
      if (response.success && response.data) {
        setStats(response.data)
      }
    } catch (error) {
      console.error('Failed to load stats:', error)
    } finally {
      setStatsLoading(false)
    }
  }

  // Load on mount and when filters change
  useEffect(() => {
    loadFacilities()
  }, [currentPage, pageSize, statusFilter, sortBy, sortOrder])

  // Load stats on mount
  useEffect(() => {
    loadStats()
  }, [])

  // Debounced search
  useEffect(() => {
    const timer = setTimeout(() => {
      if (currentPage === 1) {
        loadFacilities()
      } else {
        setCurrentPage(1)
      }
    }, 500)

    return () => clearTimeout(timer)
  }, [searchTerm])

  // Handle status toggle
  const handleStatusToggle = (facilityId: string, facilityName: string, currentStatus: string) => {
    const newStatus = currentStatus === 'active' ? 'suspended' : 'active'
    
    if (newStatus === 'suspended') {
      setDialogAction({ type: 'suspend', facilityId, facilityName })
      setShowReasonDialog(true)
    } else {
      setDialogAction({ type: 'approve', facilityId, facilityName })
      setShowConfirmDialog(true)
    }
  }

  // Confirm status change
  const confirmStatusChange = async () => {
    if (!dialogAction) return

    setUpdatingId(dialogAction.facilityId)
    setShowConfirmDialog(false)
    setShowReasonDialog(false)

    try {
      const newStatus = dialogAction.type === 'approve' ? 'active' : 'suspended'
      
      const response = await DataAPI.admin.updateFacilityStatus(
        dialogAction.facilityId,
        newStatus
      )

      if (response.success) {
        toast.success(`Facility ${dialogAction.type === 'approve' ? 'approved' : 'suspended'} successfully`, {
          title: "Success!"
        })
        
        await loadFacilities()
        await loadStats()
      }
    } catch (error: any) {
      toast.error(error.message || "Failed to update facility status", { title: "Error" })
    } finally {
      setUpdatingId(null)
      setSuspensionReason("")
      setDialogAction(null)
    }
  }

  // Render loading skeleton
  if (loading && facilities.length === 0) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-blue-50/30 p-6">
        <div className="space-y-6">
          <div className="h-8 w-64 bg-gray-200 animate-pulse rounded" />
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            {[...Array(4)].map((_, i) => (
              <div key={i} className="h-24 bg-gray-200 animate-pulse rounded-lg" />
            ))}
          </div>
          <div className="h-96 bg-gray-200 animate-pulse rounded-lg" />
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-blue-50/30">
      <div className="p-6 lg:p-8 space-y-6">
        {/* Header */}
        <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
          <div>
            <h1 className="text-3xl lg:text-4xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
              Facility Management
            </h1>
            <p className="text-gray-600 mt-2">Manage and monitor all senior care facilities</p>
          </div>
          <Button onClick={() => { loadFacilities(); loadStats(); }} variant="outline">
            <RefreshCw className={`h-4 w-4 mr-2 ${loading ? 'animate-spin' : ''}`} />
            Refresh
          </Button>
        </div>

        {/* Statistics Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <Card className="bg-gradient-to-br from-blue-50 to-blue-100 border-blue-200">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-blue-600 text-sm font-medium">Total Facilities</p>
                  <p className="text-2xl font-bold text-blue-900">
                    {statsLoading ? <Loader2 className="h-6 w-6 animate-spin" /> : stats.total}
                  </p>
                </div>
                <Building className="h-8 w-8 text-blue-600" />
              </div>
            </CardContent>
          </Card>
          
          <Card className="bg-gradient-to-br from-green-50 to-green-100 border-green-200">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-green-600 text-sm font-medium">Active</p>
                  <p className="text-2xl font-bold text-green-900">
                    {statsLoading ? <Loader2 className="h-6 w-6 animate-spin" /> : stats.active}
                  </p>
                </div>
                <CheckCircle className="h-8 w-8 text-green-600" />
              </div>
            </CardContent>
          </Card>
          
          <Card className="bg-gradient-to-br from-yellow-50 to-yellow-100 border-yellow-200">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-yellow-600 text-sm font-medium">Pending Review</p>
                  <p className="text-2xl font-bold text-yellow-900">
                    {statsLoading ? <Loader2 className="h-6 w-6 animate-spin" /> : stats.pending}
                  </p>
                </div>
                <Clock className="h-8 w-8 text-yellow-600" />
              </div>
            </CardContent>
          </Card>
          
          <Card className="bg-gradient-to-br from-purple-50 to-purple-100 border-purple-200">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-purple-600 text-sm font-medium">Avg Rating</p>
                  <p className="text-2xl font-bold text-purple-900">
                    {statsLoading ? <Loader2 className="h-6 w-6 animate-spin" /> : stats.averageRating.toFixed(1)}
                  </p>
                </div>
                <Star className="h-8 w-8 text-purple-600" />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Filters */}
        <Card className="bg-white/50 backdrop-blur-sm border-white/20">
          <CardContent className="p-6">
            <div className="flex flex-col lg:flex-row gap-4">
              <div className="flex-1 relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                <Input
                  placeholder="Search facilities by name or location..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10 bg-white/80 border-gray-200"
                />
              </div>
              
              <Select value={statusFilter} onValueChange={setStatusFilter}>
                <SelectTrigger className="w-full lg:w-[180px] bg-white/80">
                  <SelectValue placeholder="All Status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Status</SelectItem>
                  <SelectItem value="active">Active</SelectItem>
                  <SelectItem value="pending">Pending</SelectItem>
                  <SelectItem value="suspended">Suspended</SelectItem>
                </SelectContent>
              </Select>
              
              <Select value={sortBy} onValueChange={setSortBy}>
                <SelectTrigger className="w-full lg:w-[160px] bg-white/80">
                  <SelectValue placeholder="Sort by" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="createdAt">Newest</SelectItem>
                  <SelectItem value="name">Name</SelectItem>
                  <SelectItem value="rating">Rating</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </CardContent>
        </Card>

        {/* Facilities Table */}
        <Card className="bg-white/70 backdrop-blur-sm border-white/20">
          <CardHeader className="pb-4">
            <CardTitle className="text-xl font-semibold text-gray-900">
              Facilities ({facilities.length})
            </CardTitle>
          </CardHeader>
          
          <CardContent className="p-0">
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-50/80 border-b">
                  <tr>
                    <th className="text-left p-4 font-semibold text-gray-900">Facility</th>
                    <th className="text-left p-4 font-semibold text-gray-900">Type</th>
                    <th className="text-left p-4 font-semibold text-gray-900">Location</th>
                    <th className="text-left p-4 font-semibold text-gray-900">Status</th>
                    <th className="text-left p-4 font-semibold text-gray-900">Approval</th>
                    <th className="text-left p-4 font-semibold text-gray-900">Rating</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100">
                  {loading ? (
                    [...Array(5)].map((_, i) => (
                      <tr key={i}>
                        <td colSpan={6} className="p-4">
                          <div className="h-12 bg-gray-200 animate-pulse rounded" />
                        </td>
                      </tr>
                    ))
                  ) : facilities.length === 0 ? (
                    <tr>
                      <td colSpan={6} className="p-8 text-center text-gray-500">
                        No facilities found
                      </td>
                    </tr>
                  ) : (
                    facilities.map((facility) => (
                      <tr key={facility._id} className="hover:bg-gray-50/50 transition-colors">
                        <td className="p-4">
                          <div className="flex items-center gap-3">
                            {facility.images?.[0] && (
                              <img 
                                src={facility.images[0]}
                                alt={facility.name}
                                className="w-12 h-12 rounded-lg object-cover"
                              />
                            )}
                            <div>
                              <p className="font-semibold text-gray-900">{facility.name}</p>
                              {facility.verified && (
                                <Badge variant="secondary" className="bg-green-100 text-green-700 text-xs mt-1">
                                  <CheckCircle className="h-3 w-3 mr-1" />
                                  Verified
                                </Badge>
                              )}
                            </div>
                          </div>
                        </td>
                        <td className="p-4">
                          <Badge variant="outline">
                            {facility.careTypes?.[0] || 'N/A'}
                          </Badge>
                        </td>
                        <td className="p-4">
                          <div className="flex items-center gap-1 text-gray-600">
                            <MapPin className="h-4 w-4" />
                            {facility.address?.city}, {facility.address?.state}
                          </div>
                        </td>
                        <td className="p-4">
                          <Badge
                            className={
                              facility.status === "active" ? "bg-green-100 text-green-800" :
                              facility.status === "pending" ? "bg-yellow-100 text-yellow-800" :
                              "bg-red-100 text-red-800"
                            }
                          >
                            {facility.status === "active" && <CheckCircle className="h-3 w-3 mr-1" />}
                            {facility.status === "pending" && <Clock className="h-3 w-3 mr-1" />}
                            {facility.status === "suspended" && <XCircle className="h-3 w-3 mr-1" />}
                            {facility.status.charAt(0).toUpperCase() + facility.status.slice(1)}
                          </Badge>
                        </td>
                        <td className="p-4">
                          <div className="flex items-center gap-2">
                            <Switch
                              checked={facility.status === 'active'}
                              onCheckedChange={() => handleStatusToggle(facility._id, facility.name, facility.status)}
                              disabled={updatingId === facility._id}
                            />
                            {updatingId === facility._id && (
                              <Loader2 className="h-4 w-4 animate-spin text-blue-600" />
                            )}
                          </div>
                        </td>
                        <td className="p-4">
                          <div className="flex items-center gap-1">
                            <Star className="h-4 w-4 fill-yellow-400 text-yellow-400" />
                            <span className="font-medium">{facility.rating?.toFixed(1) || '0.0'}</span>
                          </div>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </CardContent>
        </Card>

        {/* Pagination */}
        <div className="flex items-center justify-between">
          <p className="text-sm text-gray-700">
            Page {currentPage} of {totalPages}
          </p>
          <div className="flex items-center gap-2">
            <Button 
              variant="outline" 
              size="sm" 
              disabled={currentPage === 1}
              onClick={() => setCurrentPage(p => p - 1)}
            >
              Previous
            </Button>
            {[...Array(Math.min(totalPages, 5))].map((_, i) => {
              const pageNum = i + 1
              return (
                <Button
                  key={pageNum}
                  variant="outline"
                  size="sm"
                  className={currentPage === pageNum ? "bg-blue-600 text-white" : ""}
                  onClick={() => setCurrentPage(pageNum)}
                >
                  {pageNum}
                </Button>
              )
            })}
            <Button 
              variant="outline" 
              size="sm"
              disabled={currentPage === totalPages}
              onClick={() => setCurrentPage(p => p + 1)}
            >
              Next
            </Button>
          </div>
        </div>
      </div>

      {/* Confirm Dialog */}
      <AlertDialog open={showConfirmDialog} onOpenChange={setShowConfirmDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Approve Facility?</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to approve "{dialogAction?.facilityName}"? 
              The facility owner will be notified via email.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={confirmStatusChange}>
              Approve
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Reason Dialog */}
      <Dialog open={showReasonDialog} onOpenChange={setShowReasonDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Suspend Facility</DialogTitle>
            <DialogDescription>
              Please provide a reason for suspending "{dialogAction?.facilityName}"
            </DialogDescription>
          </DialogHeader>
          <Textarea
            placeholder="Enter suspension reason..."
            value={suspensionReason}
            onChange={(e) => setSuspensionReason(e.target.value)}
            rows={4}
          />
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowReasonDialog(false)}>
              Cancel
            </Button>
            <Button onClick={confirmStatusChange} disabled={!suspensionReason.trim()}>
              Suspend
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}

