"use client"

import { useState, useEffect } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Checkbox } from "@/components/ui/checkbox"
import { Badge } from "@/components/ui/badge"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { ClaimStatusBadge } from "@/components/ui/claim-status-badge"
import { DocumentUploader } from "@/components/ui/document-uploader"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Building, MapPin, Phone, Mail, Globe, FileText, Users, Bed, CheckCircle,
  Loader2, ArrowLeft, AlertCircle, Send, Calendar, Shield, Briefcase,
  Hash, MapPinned, Building2, User, Upload, CheckCircle2, Star, MessageSquare,
  Flag, Reply, ThumbsUp, Clock
} from "lucide-react"
import Link from "next/link"
import { useRouter, useParams } from "next/navigation"
import { DataAPI } from "@/lib/data-api"
import { useToast } from "@/components/ui/toast"
import { useSubscription } from "@/hooks/use-subscription"
import { SubscriptionPrompt } from "@/components/subscription/subscription-prompt"
import { validatePhoneNumber } from "@/lib/validation/facility-validator"
import { formatLocationDisplay } from "@/lib/location-utils"

export default function ClaimFacilityDetailPage() {
  const router = useRouter()
  const toast = useToast()
  const params = useParams()
  const facilityId = params?.id as string

  const [loading, setLoading] = useState(true)
  const [submitting, setSubmitting] = useState(false)
  const [uploadProgress, setUploadProgress] = useState(0)
  const [facility, setFacility] = useState<any>(null)
  const [claimInfo, setClaimInfo] = useState<any>(null)

  // Claim form state
  const [showClaimDialog, setShowClaimDialog] = useState(false)
  const [claimMessage, setClaimMessage] = useState('')
  const [documents, setDocuments] = useState<any[]>([])
  const [confirmAuthorized, setConfirmAuthorized] = useState(false)

  // Additional claim information
  const [claimantName, setClaimantName] = useState('')
  const [claimantPhone, setClaimantPhone] = useState('')
  const [phoneError, setPhoneError] = useState('')
  const [claimantPosition, setClaimantPosition] = useState('')
  const [relationship, setRelationship] = useState('')
  const [businessLicense, setBusinessLicense] = useState('')

  // Reviews state
  const [reviews, setReviews] = useState<any[]>([])
  const [loadingReviews, setLoadingReviews] = useState(false)
  const [replyingToReview, setReplyingToReview] = useState<string | null>(null)
  const [replyText, setReplyText] = useState('')
  const [submittingReply, setSubmittingReply] = useState(false)
  const [flaggingReview, setFlaggingReview] = useState<string | null>(null)

  // Report modal state
  const [showReportModal, setShowReportModal] = useState(false)
  const [reportReviewId, setReportReviewId] = useState<string | null>(null)
  const [reportReason, setReportReason] = useState('')

  // Subscription state
  const { canClaim: canClaimFromSubscription, canEdit, isLoading: subscriptionLoading, refresh: refreshSubscription } = useSubscription()
  const [showSubscriptionPrompt, setShowSubscriptionPrompt] = useState(false)
  const [subscriptionPromptFeature, setSubscriptionPromptFeature] = useState<'claim' | 'edit' | 'reply'>('claim')

  useEffect(() => {
    loadFacilityClaimInfo()
  }, [facilityId])

  useEffect(() => {
    if (facility) {
      loadReviews()
    }
  }, [facility])

  // Refresh claim info when subscription status changes
  useEffect(() => {
    if (!subscriptionLoading && canClaimFromSubscription !== undefined) {
      // Reload claim info to get updated canClaim status from backend
      loadFacilityClaimInfo()
    }
  }, [canClaimFromSubscription, subscriptionLoading])

  const loadFacilityClaimInfo = async () => {
    try {
      setLoading(true)
      const response = await DataAPI.facilities.getFacilityClaimInfo(facilityId)

      if (response.success && response.data) {
        setFacility(response.data.facility)
        setClaimInfo(response.data.claimInfo)
      } else {
        throw new Error(response.message || 'Failed to load facility information')
      }
    } catch (error) {
      console.error('Failed to load facility:', error)
      toast.error("Failed to load facility information. Please try again.", { title: "Error" })
    } finally {
      setLoading(false)
    }
  }

  const loadReviews = async () => {
    try {
      setLoadingReviews(true)
      const response = await DataAPI.reviews.getFacilityReviews(facilityId)

      if (response.success && response.data) {
        setReviews(response.data.reviews || [])
      }
    } catch (error) {
      console.error('Failed to load reviews:', error)
    } finally {
      setLoadingReviews(false)
    }
  }

  const handleReplyToReview = async (reviewId: string) => {
    if (!replyText.trim()) {
      toast.error("Please enter a reply message", { title: "Error" })
      return
    }

    // Check subscription before allowing reply
    if (!canEdit(facilityId) && !subscriptionLoading) {
      setSubscriptionPromptFeature('reply')
      setShowSubscriptionPrompt(true)
      return
    }

    try {
      setSubmittingReply(true)
      const response = await DataAPI.reviews.replyToReview(reviewId, replyText)

      if (response.success) {
        toast.success("Your reply has been posted successfully", { title: "Success" })
        setReplyText('')
        setReplyingToReview(null)
        loadReviews()
      } else {
        throw new Error(response.message || 'Failed to post reply')
      }
    } catch (error: any) {
      toast.error(error.message || "Failed to post reply. Please try again.", { title: "Error" })
    } finally {
      setSubmittingReply(false)
    }
  }

  const openReportModal = (reviewId: string) => {
    setReportReviewId(reviewId)
    setReportReason('')
    setShowReportModal(true)
  }

  const closeReportModal = () => {
    setShowReportModal(false)
    setReportReviewId(null)
    setReportReason('')
  }

  const handleSubmitReport = async () => {
    if (!reportReviewId) return

    if (!reportReason.trim()) {
      toast.error("Please provide a reason for reporting this review", { title: "Error" })
      return
    }

    try {
      setFlaggingReview(reportReviewId)
      const response = await DataAPI.reviews.flagReview(reportReviewId, reportReason)

      if (response.success) {
        toast.success("Review has been reported to admin for moderation", { title: "Success" })
        closeReportModal()
        loadReviews()
      } else {
        throw new Error(response.message || 'Failed to report review')
      }
    } catch (error: any) {
      toast.error(error.message || "Failed to report review. Please try again.", { title: "Error" })
    } finally {
      setFlaggingReview(null)
    }
  }

  const scrollToTop = () => {
    const dialogContent = document.querySelector('[role="dialog"]')
    if (dialogContent) {
      dialogContent.scrollTo({ top: 0, behavior: 'smooth' })
    }
  }

  const handlePhoneChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const inputValue = e.target.value

    // Allow empty input
    if (inputValue === '') {
      setClaimantPhone('')
      setPhoneError('')
      return
    }

    // Remove all non-digit characters for validation
    const digits = inputValue.replace(/\D/g, '')

    // Limit to 11 digits max
    if (digits.length > 11) {
      return
    }

    // Update the state with the input value
    setClaimantPhone(inputValue)

    // Real-time validation
    const validation = validatePhoneNumber(inputValue)

    if (digits.length === 0) {
      setPhoneError('')
    } else if (digits.length < 10) {
      setPhoneError(`Need ${10 - digits.length} more digit${10 - digits.length === 1 ? '' : 's'}`)
    } else if (!validation.isValid) {
      setPhoneError(validation.message || 'Invalid phone number')
    } else {
      setPhoneError('')
      // Auto-format when valid
      if (validation.formatted) {
        setClaimantPhone(validation.formatted)
      }
    }
  }

  const handleSubmitClaim = async () => {
    console.log('=== CLAIM SUBMISSION ATTEMPT ===')
    console.log('Claimant Name:', claimantName)
    console.log('Claimant Phone:', claimantPhone)
    console.log('Claimant Position:', claimantPosition)
    console.log('Relationship:', relationship)
    console.log('Claim Message Length:', claimMessage.length)
    console.log('Documents Count:', documents.length)
    console.log('Confirm Authorized:', confirmAuthorized)
    console.log('================================')

    // Validation with scroll to error
    if (!claimantName.trim()) {
      scrollToTop()
      toast.error("Please scroll up and provide your full name in the Contact Information section.", {
        title: "⚠️ Missing Required Field",
        duration: 5000
      })
      return
    }

    if (!claimantPhone.trim()) {
      scrollToTop()
      toast.error("Please scroll up and provide your phone number in the Contact Information section.", {
        title: "⚠️ Missing Required Field",
        duration: 5000
      })
      return
    }

    if (!claimantPosition.trim()) {
      scrollToTop()
      toast.error("Please scroll up and provide your position/title in the Contact Information section.", {
        title: "⚠️ Missing Required Field",
        duration: 5000
      })
      return
    }

    if (!relationship) {
      scrollToTop()
      toast.error("Please scroll up and select your relationship to the facility in the Contact Information section.", {
        title: "⚠️ Missing Required Field",
        duration: 5000
      })
      return
    }

    if (!claimMessage.trim() || claimMessage.length < 20) {
      scrollToTop()
      toast.error(`Your claim reason is only ${claimMessage.length} characters. Please provide at least 20 characters explaining why you should manage this facility.`, {
        title: "⚠️ Claim Reason Too Short",
        duration: 7000
      })
      // Focus on the textarea
      setTimeout(() => {
        const textarea = document.getElementById('claim-message')
        if (textarea) {
          textarea.focus()
          textarea.scrollIntoView({ behavior: 'smooth', block: 'center' })
        }
      }, 100)
      return
    }

    if (documents.length === 0) {
      toast.error("Please upload at least one supporting document.", {
        title: "⚠️ Missing Required Field",
        duration: 5000
      })
      return
    }

    if (!confirmAuthorized) {
      toast.error("Please check the confirmation checkbox to confirm you are authorized.", {
        title: "⚠️ Missing Required Field",
        duration: 5000
      })
      return
    }

    console.log('✅ All validations passed! Starting submission...')

    try {
      setSubmitting(true)
      setUploadProgress(10)

      // Simulate progress for better UX
      const progressInterval = setInterval(() => {
        setUploadProgress((prev) => {
          if (prev < 90) return prev + 10
          return prev
        })
      }, 300)

      console.log('📤 Sending claim request to API...')
      console.log('Facility ID:', facilityId)
      console.log('Documents to submit:', documents)

      // Use cleaned phone number (digits only) for database storage
      const response = await DataAPI.facilities.submitClaimRequest(facilityId, {
        message: claimMessage,
        documents,
        claimantInfo: {
          name: claimantName,
          phone: claimantPhone.replace(/\D/g, ''),
          position: claimantPosition,
          relationship: relationship,
          businessLicense: businessLicense
        }
      })

      console.log('📥 API Response:', response)

      clearInterval(progressInterval)
      setUploadProgress(100)

      console.log('📥 API Response received:', response)

      if (response.success) {
        console.log('✅ Claim submitted successfully!')
        console.log('Claim Request ID:', response.data?.claimRequestId)
        console.log('Facility ID:', response.data?.facilityId)
        console.log('Status:', response.data?.status)

        toast.success("Your claim request has been submitted and is under review. Redirecting to your claims...", { title: "✅ Claim Submitted Successfully" })

        // Wait a bit to show success message
        await new Promise(resolve => setTimeout(resolve, 1000))

        setShowClaimDialog(false)

        // Redirect to claims page
        setTimeout(() => {
          router.push('/facility-owner/facilities/claims')
        }, 500)
      } else {
        console.error('❌ API returned error:', response.message)
        throw new Error(response.message || 'Failed to submit claim request')
      }
    } catch (error: any) {
      console.error('❌ Claim submission error:', error)
      console.error('Error details:', {
        message: error.message,
        stack: error.stack,
        response: error.response
      })

      toast.error(error.message || 'Failed to submit claim request. Please try again.', {
        title: "❌ Submission Failed",
        duration: 7000
      })
    } finally {
      setSubmitting(false)
      setUploadProgress(0)
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[500px]">
        <div className="text-center">
          <Loader2 className="h-10 w-10 animate-spin mx-auto mb-4 text-[#3F5CEA]" />
          <p className="text-gray-600">Loading facility information...</p>
        </div>
      </div>
    )
  }

  if (!facility || !claimInfo) {
    return (
      <div className="text-center py-16">
        <AlertCircle className="h-16 w-16 text-red-500 mx-auto mb-4" />
        <h3 className="text-xl font-semibold text-gray-900 mb-2">
          Facility Not Found
        </h3>
        <p className="text-gray-600 mb-6">
          The facility you're looking for doesn't exist or has been removed.
        </p>
        <Link href="/facility-owner/facilities/claim">
          <Button className="bg-[#3F5CEA] hover:bg-[#3F5CEA]/90">
            <ArrowLeft className="h-4 w-4 mr-2" />
            Back to Search
          </Button>
        </Link>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <Link href="/facility-owner/facilities/claim">
            <Button variant="outline" size="sm" className="mb-3">
              <ArrowLeft className="h-4 w-4 mr-2" />
              Back to Search
            </Button>
          </Link>
          <h1 className="text-3xl font-bold text-gray-900">
            {facility.name}
          </h1>
          <p className="text-gray-600 mt-1">
            {formatLocationDisplay(facility)}
          </p>
        </div>
        <ClaimStatusBadge status={claimInfo.claimStatus} />
      </div>

      {/* Claim Status Alert */}
      <Card className={`border-2 ${claimInfo.canClaim
          ? 'border-green-200 bg-green-50'
          : claimInfo.hasPendingClaim
            ? 'border-yellow-200 bg-yellow-50'
            : 'border-gray-200 bg-gray-50'
        }`}>
        <CardContent className="pt-6">
          <div className="flex items-start gap-4">
            {claimInfo.canClaim ? (
              <CheckCircle className="h-6 w-6 text-green-600 flex-shrink-0 mt-0.5" />
            ) : claimInfo.hasPendingClaim ? (
              <Loader2 className="h-6 w-6 text-yellow-600 flex-shrink-0 mt-0.5 animate-spin" />
            ) : (
              <AlertCircle className="h-6 w-6 text-gray-600 flex-shrink-0 mt-0.5" />
            )}
            <div className="flex-1">
              <h3 className={`font-semibold mb-1 ${claimInfo.canClaim
                  ? 'text-green-900'
                  : claimInfo.hasPendingClaim
                    ? 'text-yellow-900'
                    : 'text-gray-900'
                }`}>
                {claimInfo.message}
              </h3>
              {claimInfo.canClaim && (
                <p className="text-sm text-green-800">
                  You can submit a claim request for this facility. Please provide supporting documentation.
                </p>
              )}
              {claimInfo.hasPendingClaim && (
                <p className="text-sm text-yellow-800">
                  Our admin team is reviewing your claim request. You'll receive an email once it's processed.
                </p>
              )}
            </div>
            {claimInfo.canClaim && (
              <Button
                onClick={() => {
                  // Double-check subscription on frontend
                  if (!canClaimFromSubscription && !subscriptionLoading) {
                    setShowSubscriptionPrompt(true)
                  } else {
                    setShowClaimDialog(true)
                  }
                }}
                className="bg-[#3F5CEA] hover:bg-[#3F5CEA]/90"
                disabled={subscriptionLoading}
              >
                Claim This Facility
              </Button>
            )}
            {claimInfo.requiresSubscription && (
              <Button
                onClick={() => setShowSubscriptionPrompt(true)}
                className="bg-[#3F5CEA] hover:bg-[#3F5CEA]/90"
              >
                Subscribe to Claim
              </Button>
            )}
            {claimInfo.isOwner && (
              <Link href={`/facility-owner/facilities/${facilityId}/edit`}>
                <Button className="bg-[#3F5CEA] hover:bg-[#3F5CEA]/90">
                  Edit Facility
                </Button>
              </Link>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Description */}
      {facility.description && (
        <Card className="bg-gradient-to-br from-blue-50 to-indigo-50 border-blue-200">
          <CardContent className="pt-6">
            <p className="text-gray-700 leading-relaxed">{facility.description}</p>
          </CardContent>
        </Card>
      )}

      {/* Facility Information */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Location & Contact */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <MapPin className="h-5 w-5 text-blue-600" />
              Location & Contact
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label className="text-sm font-medium text-gray-700">Address</Label>
              <p className="text-gray-900 mt-1">
                {facility.location.address}<br />
                {formatLocationDisplay(facility)} {facility.location.zipCode}
              </p>
            </div>

            {facility.location?.county && (
              <div>
                <Label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                  <MapPinned className="h-4 w-4" />
                  County
                </Label>
                <p className="text-gray-900 mt-1">{facility.location.county}</p>
              </div>
            )}

            <div className="border-t pt-4 mt-4">
              {facility.contact?.phone && (
                <div className="mb-3">
                  <Label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                    <Phone className="h-4 w-4" />
                    Phone
                  </Label>
                  <p className="text-gray-900 mt-1">{facility.contact.phone}</p>
                </div>
              )}

              {facility.contact?.fax && (
                <div className="mb-3">
                  <Label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                    <Phone className="h-4 w-4" />
                    Fax
                  </Label>
                  <p className="text-gray-900 mt-1">{facility.contact.fax}</p>
                </div>
              )}

              {facility.contact?.email && (
                <div className="mb-3">
                  <Label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                    <Mail className="h-4 w-4" />
                    Email
                  </Label>
                  <p className="text-gray-900 mt-1">{facility.contact.email}</p>
                </div>
              )}

              {facility.contact?.providerEmail && facility.contact.providerEmail !== facility.contact.email && (
                <div className="mb-3">
                  <Label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                    <Mail className="h-4 w-4" />
                    Provider Email
                  </Label>
                  <p className="text-gray-900 mt-1">{facility.contact.providerEmail}</p>
                </div>
              )}

              {facility.contact?.website && (
                <div>
                  <Label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                    <Globe className="h-4 w-4" />
                    Website
                  </Label>
                  <a
                    href={facility.contact.website}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-[#3F5CEA] hover:underline mt-1 block"
                  >
                    {facility.contact.website}
                  </a>
                </div>
              )}
            </div>
          </CardContent>
        </Card>

        {/* Licensing */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <FileText className="h-5 w-5 text-purple-600" />
              Licensing Information
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label className="text-sm font-medium text-gray-700">License Number</Label>
              <p className="text-gray-900 mt-1 font-mono text-lg">{facility.licensing.licenseNumber}</p>
            </div>

            {facility.licensing.effectiveDate && (
              <div>
                <Label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                  <Calendar className="h-4 w-4" />
                  Effective Date
                </Label>
                <p className="text-gray-900 mt-1">
                  {new Date(facility.licensing.effectiveDate).toLocaleDateString('en-US', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                  })}
                </p>
              </div>
            )}

            {facility.licensing.expirationDate && (
              <div>
                <Label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                  <Calendar className="h-4 w-4" />
                  Expiration Date
                </Label>
                <p className="text-gray-900 mt-1">
                  {new Date(facility.licensing.expirationDate).toLocaleDateString('en-US', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                  })}
                </p>
              </div>
            )}

            <div className="border-t pt-4 mt-4 space-y-2">
              <div className="flex items-center justify-between">
                <Label className="text-sm font-medium text-gray-700">Licensed</Label>
                <Badge variant={facility.licensing.facilityLicensed ? "default" : "secondary"}>
                  {facility.licensing.facilityLicensed ? "Yes" : "No"}
                </Badge>
              </div>
              <div className="flex items-center justify-between">
                <Label className="text-sm font-medium text-gray-700">Certified</Label>
                <Badge variant={facility.licensing.facilityCertified ? "default" : "secondary"}>
                  {facility.licensing.facilityCertified ? "Yes" : "No"}
                </Badge>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Facility Details & Operations */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Facility Type & IDs */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Building2 className="h-5 w-5 text-green-600" />
              Facility Type
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {facility.programType && (
              <div>
                <Label className="text-sm font-medium text-gray-700">Program Type</Label>
                <p className="text-gray-900 mt-1 font-medium">{facility.programType}</p>
              </div>
            )}

            {facility.serviceType && (
              <div>
                <Label className="text-sm font-medium text-gray-700">Service Type</Label>
                <p className="text-gray-900 mt-1">{facility.serviceType}</p>
              </div>
            )}

            {facility.facilityId && (
              <div>
                <Label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                  <Hash className="h-4 w-4" />
                  Facility ID
                </Label>
                <p className="text-gray-900 mt-1 font-mono">{facility.facilityId}</p>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Administrator */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <User className="h-5 w-5 text-orange-600" />
              Management
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {facility.staffing?.administrator && (
              <div>
                <Label className="text-sm font-medium text-gray-700">Administrator</Label>
                <p className="text-gray-900 mt-1 font-medium">{facility.staffing.administrator}</p>
              </div>
            )}

            {facility.location?.stateRegion && (
              <div>
                <Label className="text-sm font-medium text-gray-700">State Region</Label>
                <p className="text-gray-900 mt-1">{facility.location.stateRegion}</p>
              </div>
            )}

            {facility.location?.hhscSubOffice && (
              <div>
                <Label className="text-sm font-medium text-gray-700">HHSC Sub Office</Label>
                <p className="text-gray-900 mt-1">{facility.location.hhscSubOffice}</p>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Quick Stats */}
        <Card className="bg-gradient-to-br from-green-50 to-emerald-50 border-green-200">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Shield className="h-5 w-5 text-green-600" />
              Status
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            {facility.status && (
              <div className="flex items-center justify-between">
                <Label className="text-sm font-medium text-gray-700">Facility Status</Label>
                <Badge variant="default" className="bg-green-600">
                  {facility.status.charAt(0).toUpperCase() + facility.status.slice(1)}
                </Badge>
              </div>
            )}
            {facility.claimStatus && (
              <div className="flex items-center justify-between">
                <Label className="text-sm font-medium text-gray-700">Claim Status</Label>
                <ClaimStatusBadge status={facility.claimStatus} />
              </div>
            )}
            <div className="flex items-center justify-between">
              <Label className="text-sm font-medium text-gray-700">Verified</Label>
              <Badge variant={facility.verified ? "default" : "secondary"}>
                {facility.verified ? "Yes" : "No"}
              </Badge>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Care Types & Capacity */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Building className="h-5 w-5 text-green-600" />
            Care Services & Capacity
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-6">
          {/* Care Types */}
          {facility.careTypes && facility.careTypes.length > 0 && (
            <div>
              <Label className="text-sm font-medium text-gray-700 mb-3 block">Care Types Offered</Label>
              <div className="flex flex-wrap gap-2">
                {facility.careTypes.map((type: string, index: number) => (
                  <Badge key={index} variant="outline" className="text-sm px-3 py-1">
                    {type}
                  </Badge>
                ))}
              </div>
            </div>
          )}

          {/* Capacity */}
          {facility.capacity && (
            <div>
              <Label className="text-sm font-medium text-gray-700 mb-3 block">Bed Capacity</Label>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div className="bg-blue-50 p-4 rounded-lg border border-blue-200">
                  <Bed className="h-5 w-5 text-blue-600 mb-2" />
                  <Label className="text-xs font-medium text-blue-900 block">Total Licensed</Label>
                  <p className="text-2xl font-bold text-blue-900 mt-1">
                    {(facility.capacity.totalLicensed && facility.capacity.totalLicensed > 1) ? facility.capacity.totalLicensed : 6}
                  </p>
                </div>

                {(facility.capacity.licensedOnlyBeds || 0) > 0 && (
                  <div className="bg-indigo-50 p-4 rounded-lg border border-indigo-200">
                    <Bed className="h-5 w-5 text-indigo-600 mb-2" />
                    <Label className="text-xs font-medium text-indigo-900 block">Licensed Only</Label>
                    <p className="text-2xl font-bold text-indigo-900 mt-1">
                      {facility.capacity.licensedOnlyBeds}
                    </p>
                  </div>
                )}

                {(facility.capacity.medicaidOnlyBeds || 0) > 0 && (
                  <div className="bg-green-50 p-4 rounded-lg border border-green-200">
                    <Bed className="h-5 w-5 text-green-600 mb-2" />
                    <Label className="text-xs font-medium text-green-900 block">Medicaid Only</Label>
                    <p className="text-2xl font-bold text-green-900 mt-1">
                      {facility.capacity.medicaidOnlyBeds}
                    </p>
                  </div>
                )}

                {(facility.capacity.medicareOnlyBeds || 0) > 0 && (
                  <div className="bg-teal-50 p-4 rounded-lg border border-teal-200">
                    <Bed className="h-5 w-5 text-teal-600 mb-2" />
                    <Label className="text-xs font-medium text-teal-900 block">Medicare Only</Label>
                    <p className="text-2xl font-bold text-teal-900 mt-1">
                      {facility.capacity.medicareOnlyBeds}
                    </p>
                  </div>
                )}

                {(facility.capacity.medicaidMedicareBeds || 0) > 0 && (
                  <div className="bg-cyan-50 p-4 rounded-lg border border-cyan-200">
                    <Bed className="h-5 w-5 text-cyan-600 mb-2" />
                    <Label className="text-xs font-medium text-cyan-900 block">Medicaid/Medicare</Label>
                    <p className="text-2xl font-bold text-cyan-900 mt-1">
                      {facility.capacity.medicaidMedicareBeds}
                    </p>
                  </div>
                )}

                {(facility.capacity.icfiidBeds || 0) > 0 && (
                  <div className="bg-amber-50 p-4 rounded-lg border border-amber-200">
                    <Bed className="h-5 w-5 text-amber-600 mb-2" />
                    <Label className="text-xs font-medium text-amber-900 block">ICF/IID</Label>
                    <p className="text-2xl font-bold text-amber-900 mt-1">
                      {facility.capacity.icfiidBeds}
                    </p>
                  </div>
                )}

                {(facility.capacity.alzheimerCapacity || 0) > 0 && (
                  <div className="bg-purple-50 p-4 rounded-lg border border-purple-200">
                    <Users className="h-5 w-5 text-purple-600 mb-2" />
                    <Label className="text-xs font-medium text-purple-900 block">Alzheimer Care</Label>
                    <p className="text-2xl font-bold text-purple-900 mt-1">
                      {facility.capacity.alzheimerCapacity}
                    </p>
                  </div>
                )}
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Reviews & Feedback Section */}
      {claimInfo?.isOwner && (
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <CardTitle className="flex items-center gap-2">
                <MessageSquare className="h-5 w-5 text-purple-600" />
                Reviews & Feedback
              </CardTitle>
              <Badge variant="secondary" className="text-sm">
                {reviews.length} {reviews.length === 1 ? 'Review' : 'Reviews'}
              </Badge>
            </div>
          </CardHeader>
          <CardContent>
            {loadingReviews ? (
              <div className="flex items-center justify-center py-12">
                <Loader2 className="h-8 w-8 animate-spin text-[#3F5CEA]" />
              </div>
            ) : reviews.length === 0 ? (
              <div className="text-center py-12 bg-gray-50 rounded-lg border-2 border-dashed border-gray-300">
                <MessageSquare className="h-12 w-12 text-gray-400 mx-auto mb-3" />
                <p className="text-gray-600 font-medium">No reviews yet</p>
                <p className="text-sm text-gray-500 mt-1">
                  Reviews from families will appear here
                </p>
              </div>
            ) : (
              <div className="space-y-6">
                {reviews.map((review: any) => (
                  <div
                    key={review._id}
                    className={`border rounded-lg p-6 ${review.flagged?.isFlagged ? 'bg-yellow-50 border-yellow-300' : 'bg-white border-gray-200'
                      }`}
                  >
                    {/* Review Header */}
                    <div className="flex items-start justify-between mb-4">
                      <div className="flex-1">
                        <div className="flex items-center gap-3 mb-2">
                          <div className="flex items-center gap-1">
                            {[1, 2, 3, 4, 5].map((star) => (
                              <Star
                                key={star}
                                className={`h-4 w-4 ${star <= review.rating
                                    ? 'fill-yellow-400 text-yellow-400'
                                    : 'text-gray-300'
                                  }`}
                              />
                            ))}
                          </div>
                          <span className="font-semibold text-gray-900">
                            {review.rating.toFixed(1)}
                          </span>
                          {review.verified && (
                            <Badge variant="outline" className="bg-green-100 text-green-800">
                              <CheckCircle className="h-3 w-3 mr-1" />
                              Verified
                            </Badge>
                          )}
                        </div>
                        <div className="flex items-center gap-2 text-sm text-gray-600">
                          <User className="h-4 w-4" />
                          <span className="font-medium">
                            {review.userId?.firstName && review.userId?.lastName
                              ? `${review.userId.firstName} ${review.userId.lastName}`
                              : review.userId?.email || 'Anonymous User'}
                          </span>
                          <span>•</span>
                          <Clock className="h-3 w-3" />
                          <span>{new Date(review.createdAt).toLocaleDateString()}</span>
                        </div>
                      </div>

                      {/* Flag Button - Always visible for owners */}
                      {!review.flagged?.isFlagged && claimInfo?.isOwner && (
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => openReportModal(review._id)}
                          disabled={flaggingReview === review._id}
                          className="text-red-600 hover:text-red-700 hover:bg-red-50 border-red-300 font-medium"
                        >
                          {flaggingReview === review._id ? (
                            <Loader2 className="h-4 w-4 animate-spin" />
                          ) : (
                            <>
                              <Flag className="h-4 w-4 mr-2" />
                              Report Review
                            </>
                          )}
                        </Button>
                      )}
                      {review.flagged?.isFlagged && (
                        <Badge variant="outline" className="bg-yellow-100 text-yellow-800 border-yellow-300">
                          <Flag className="h-3 w-3 mr-1" />
                          Reported - Under Admin Review
                        </Badge>
                      )}
                    </div>

                    {/* Review Content */}
                    {review.title && (
                      <h4 className="font-semibold text-gray-900 mb-2">
                        {review.title}
                      </h4>
                    )}
                    <p className="text-gray-700 leading-relaxed mb-4">
                      {review.comment}
                    </p>

                    {/* Review Stats */}
                    {(review.helpful || review.notHelpful) && (
                      <div className="flex items-center gap-4 text-sm text-gray-600 mb-4">
                        <div className="flex items-center gap-1">
                          <ThumbsUp className="h-4 w-4" />
                          <span>{review.helpful || 0} found this helpful</span>
                        </div>
                      </div>
                    )}

                    {/* Owner Reply */}
                    {review.ownerResponse && (
                      <div className="mt-4 ml-6 p-4 bg-blue-50 border-l-4 border-blue-500 rounded-r-lg">
                        <div className="flex items-center gap-2 mb-2">
                          <Building className="h-4 w-4 text-blue-600" />
                          <span className="font-semibold text-blue-900">Owner Response</span>
                          <span className="text-xs text-blue-700">
                            {new Date(review.ownerResponse.createdAt).toLocaleDateString()}
                          </span>
                        </div>
                        <p className="text-gray-800 text-sm leading-relaxed">
                          {review.ownerResponse.response}
                        </p>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* Claim Form Dialog */}
      <Dialog
        open={showClaimDialog}
        onOpenChange={(open) => {
          // Prevent closing while submitting
          if (!submitting) {
            setShowClaimDialog(open)
          }
        }}
      >
        <DialogContent
          className="max-h-[90vh] overflow-y-auto"
          style={{ maxWidth: '1400px', width: '95vw' }}
        >          <DialogHeader>
            <DialogTitle>Claim Facility: {facility.name}</DialogTitle>
            <DialogDescription>
              Please provide your contact information, details about your relationship to this facility, and upload supporting documents.
            </DialogDescription>
          </DialogHeader>

          {submitting && (
            <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-center gap-3">
              <Loader2 className="h-5 w-5 text-blue-600 animate-spin flex-shrink-0" />
              <div className="flex-1">
                <p className="text-sm font-medium text-blue-900">
                  {uploadProgress < 100 ? 'Submitting your claim request...' : 'Finalizing...'}
                </p>
                <p className="text-xs text-blue-700 mt-1">
                  Please wait while we process your documents and submit your claim.
                </p>
              </div>
            </div>
          )}

          <div className="space-y-6 py-4">
            {/* Contact Information Section */}
            <div className="space-y-4">
              <div className="flex items-center gap-2 pb-2 border-b">
                <User className="h-4 w-4 text-[#3F5CEA]" />
                <h3 className="font-semibold text-gray-900">Contact Information</h3>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="claimant-name">
                    Full Name *
                  </Label>
                  <Input
                    id="claimant-name"
                    placeholder="John Smith"
                    value={claimantName}
                    onChange={(e) => setClaimantName(e.target.value)}
                    className="mt-2"
                  />
                </div>

                <div>
                  <Label htmlFor="claimant-phone">
                    Phone Number *
                  </Label>
                  <Input
                    id="claimant-phone"
                    type="tel"
                    placeholder="(555) 123-4567"
                    value={claimantPhone}
                    onChange={handlePhoneChange}
                    className={`mt-2 ${phoneError && claimantPhone.length > 0 ? 'border-red-500 focus:border-red-500' : ''} ${claimantPhone.length >= 10 && !phoneError ? 'border-green-500' : ''}`}
                  />
                  {phoneError && claimantPhone.length > 0 && (
                    <p className="text-xs text-red-600 mt-1 font-medium flex items-center gap-1">
                      <AlertCircle className="h-3 w-3" />
                      {phoneError}
                    </p>
                  )}
                  {!phoneError && claimantPhone.length >= 10 && (
                    <p className="text-xs text-green-600 mt-1 font-medium flex items-center gap-1">
                      <CheckCircle className="h-3 w-3" />
                      Valid phone number
                    </p>
                  )}
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="claimant-position">
                    Your Position/Title *
                  </Label>
                  <Input
                    id="claimant-position"
                    placeholder="e.g., Owner, Administrator, Manager"
                    value={claimantPosition}
                    onChange={(e) => setClaimantPosition(e.target.value)}
                    className="mt-2"
                  />
                </div>

                <div>
                  <Label htmlFor="relationship">
                    Relationship to Facility *
                  </Label>
                  <Select value={relationship} onValueChange={setRelationship}>
                    <SelectTrigger className="mt-2">
                      <SelectValue placeholder="Select relationship" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="owner">Owner</SelectItem>
                      <SelectItem value="administrator">Administrator</SelectItem>
                      <SelectItem value="manager">Manager</SelectItem>
                      <SelectItem value="authorized_representative">Authorized Representative</SelectItem>
                      <SelectItem value="legal_guardian">Legal Guardian</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div>
                <Label htmlFor="business-license">
                  Business License Number (Optional)
                </Label>
                <Input
                  id="business-license"
                  placeholder="Enter business license number if available"
                  value={businessLicense}
                  onChange={(e) => setBusinessLicense(e.target.value)}
                  className="mt-2"
                />
                <p className="text-xs text-gray-500 mt-1">
                  Providing this helps expedite verification
                </p>
              </div>
            </div>

            {/* Claim Details Section */}
            <div className="space-y-4">
              <div className="flex items-center gap-2 pb-2 border-b">
                <Briefcase className="h-4 w-4 text-[#3F5CEA]" />
                <h3 className="font-semibold text-gray-900">Claim Details</h3>
              </div>

              <div>
                <Label htmlFor="claim-message">
                  Why are you claiming this facility? *
                </Label>
                <Textarea
                  id="claim-message"
                  placeholder="Explain your relationship to this facility and why you should be granted access to manage it..."
                  value={claimMessage}
                  onChange={(e) => setClaimMessage(e.target.value)}
                  rows={5}
                  className={`mt-2 ${claimMessage.length > 0 && claimMessage.length < 20 ? 'border-red-500 focus:border-red-500' : ''}`}
                />
                <div className="flex items-center justify-between mt-1">
                  <p className={`text-xs font-medium ${claimMessage.length === 0
                      ? 'text-gray-500'
                      : claimMessage.length < 20
                        ? 'text-red-600'
                        : 'text-green-600'
                    }`}>
                    {claimMessage.length < 20
                      ? `⚠️ Need ${20 - claimMessage.length} more characters (minimum 20 required)`
                      : `✓ ${claimMessage.length}/500 characters`
                    }
                  </p>
                </div>
              </div>
            </div>

            {/* Document Upload Section */}
            <div className="space-y-4">
              <div className="flex items-center gap-2 pb-2 border-b">
                <FileText className="h-4 w-4 text-[#3F5CEA]" />
                <h3 className="font-semibold text-gray-900">Supporting Documents</h3>
              </div>

              <div>
                <Label className="mb-2 block">Upload Documents *</Label>
                <DocumentUploader
                  documents={documents}
                  onDocumentsChange={setDocuments}
                  maxFiles={5}
                  maxSizeInMB={10}
                />
                <p className="text-xs text-gray-500 mt-2">
                  Please upload documents proving your ownership or authorization to manage this facility
                  (e.g., business license, ownership documents, insurance papers, deed, lease agreement)
                </p>
              </div>
            </div>

            {/* Confirmation Section */}
            <div className="space-y-4">
              <div className="flex items-center gap-2 pb-2 border-b">
                <Shield className="h-4 w-4 text-[#3F5CEA]" />
                <h3 className="font-semibold text-gray-900">Confirmation</h3>
              </div>

              <div className="flex items-start space-x-3 p-4 bg-gray-50 rounded-lg">
                <Checkbox
                  id="confirm-authorized"
                  checked={confirmAuthorized}
                  onCheckedChange={(checked) => setConfirmAuthorized(checked as boolean)}
                  className="mt-1"
                />
                <Label htmlFor="confirm-authorized" className="text-sm leading-relaxed cursor-pointer">
                  I confirm that I am authorized to represent this facility and all information provided is accurate. I understand that providing false information may result in legal consequences.
                </Label>
              </div>
            </div>
          </div>

          <DialogFooter className="flex-col sm:flex-row gap-3">
            {submitting && uploadProgress > 0 && (
              <div className="w-full sm:flex-1">
                <div className="flex items-center justify-between text-sm mb-2">
                  <span className="text-gray-600">
                    {uploadProgress < 100 ? 'Uploading documents...' : 'Finalizing submission...'}
                  </span>
                  <span className="font-medium text-[#3F5CEA]">{uploadProgress}%</span>
                </div>
                <div className="w-full bg-gray-200 rounded-full h-2 overflow-hidden">
                  <div
                    className="bg-[#3F5CEA] h-2 rounded-full transition-all duration-300 ease-out"
                    style={{ width: `${uploadProgress}%` }}
                  />
                </div>
              </div>
            )}

            {!submitting && (
              <>
                <Button
                  variant="outline"
                  onClick={() => setShowClaimDialog(false)}
                  disabled={submitting}
                >
                  Cancel
                </Button>
                <Button
                  onClick={handleSubmitClaim}
                  disabled={submitting}
                  className="bg-[#3F5CEA] hover:bg-[#3F5CEA]/90"
                >
                  <Send className="h-4 w-4 mr-2" />
                  Submit Claim Request
                </Button>
              </>
            )}

            {submitting && (
              <Button
                disabled
                className="bg-[#3F5CEA] hover:bg-[#3F5CEA]/90 opacity-70 cursor-not-allowed"
              >
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                {uploadProgress < 100 ? 'Uploading...' : 'Submitting...'}
              </Button>
            )}
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Report Review Modal */}
      <Dialog open={showReportModal} onOpenChange={closeReportModal}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2 text-red-600">
              <Flag className="h-5 w-5" />
              Report Review to Admin
            </DialogTitle>
            <DialogDescription>
              Please provide a detailed reason for reporting this review. Your report will be reviewed by our admin team.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <label htmlFor="report-reason" className="text-sm font-medium text-gray-700">
                Reason for Reporting <span className="text-red-500">*</span>
              </label>
              <Textarea
                id="report-reason"
                placeholder="Please describe why you believe this review violates our guidelines or is inappropriate..."
                value={reportReason}
                onChange={(e) => setReportReason(e.target.value)}
                rows={5}
                className="resize-none"
              />
              <p className="text-xs text-gray-500">
                Common reasons: Spam, offensive language, false information, personal attacks, etc.
              </p>
            </div>
          </div>

          <DialogFooter className="gap-2">
            <Button
              type="button"
              variant="outline"
              onClick={closeReportModal}
              disabled={flaggingReview !== null}
            >
              Cancel
            </Button>
            <Button
              type="button"
              onClick={handleSubmitReport}
              disabled={!reportReason.trim() || flaggingReview !== null}
              className="bg-red-600 hover:bg-red-700"
            >
              {flaggingReview ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin mr-2" />
                  Reporting...
                </>
              ) : (
                <>
                  <Flag className="h-4 w-4 mr-2" />
                  Submit Report
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Subscription Prompt */}
      <SubscriptionPrompt
        open={showSubscriptionPrompt}
        onOpenChange={setShowSubscriptionPrompt}
        feature={subscriptionPromptFeature}
        facilityName={facility?.name}
      />
    </div>
  )
}

