"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 { Textarea } from "@/components/ui/textarea"
import { Badge } from "@/components/ui/badge"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Building, MapPin, Phone, Mail, Globe, FileText, User, Calendar,
  CheckCircle, XCircle, Clock, Loader2, ArrowLeft, AlertCircle,
  Download, ExternalLink
} 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"

export default function AdminClaimReviewPage() {
  const router = useRouter()
  const toast = useToast()
  const params = useParams()
  const claimId = params?.claimId as string

  const [loading, setLoading] = useState(true)
  const [processing, setProcessing] = useState(false)
  const [claimData, setClaimData] = useState<any>(null)

  // Approve/Reject state
  const [showApproveDialog, setShowApproveDialog] = useState(false)
  const [showRejectDialog, setShowRejectDialog] = useState(false)
  const [adminNotes, setAdminNotes] = useState('')
  const [rejectionReason, setRejectionReason] = useState('')

  useEffect(() => {
    loadClaimDetails()
  }, [claimId])

  const loadClaimDetails = async () => {
    try {
      setLoading(true)
      const response = await DataAPI.admin.getClaimDetails(claimId)

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

  const handleApproveClaim = async () => {
    try {
      setProcessing(true)

      const response = await DataAPI.admin.approveClaim(claimId, adminNotes)

      if (response.success) {
        toast.success("The claim request has been approved successfully.", { title: "Claim Approved" })

        setShowApproveDialog(false)

        // Redirect back to claims list
        setTimeout(() => {
          router.push('/admin/facilities/claims')
        }, 1500)
      } else {
        throw new Error(response.message || 'Failed to approve claim')
      }
    } catch (error: any) {
      console.error('Failed to approve claim:', error)
      toast.error(error.message || 'Failed to approve claim. Please try again.', { title: "Approval Failed" })
    } finally {
      setProcessing(false)
    }
  }

  const handleRejectClaim = async () => {
    if (!rejectionReason.trim()) {
      toast.error("Please provide a reason for rejection.", { title: "Validation Error" })
      return
    }

    try {
      setProcessing(true)

      const response = await DataAPI.admin.rejectClaim(claimId, rejectionReason)

      if (response.success) {
        toast.success("The claim request has been rejected.", { title: "Claim Rejected" })

        setShowRejectDialog(false)

        // Redirect back to claims list
        setTimeout(() => {
          router.push('/admin/facilities/claims')
        }, 1500)
      } else {
        throw new Error(response.message || 'Failed to reject claim')
      }
    } catch (error: any) {
      console.error('Failed to reject claim:', error)
      toast.error(error.message || 'Failed to reject claim. Please try again.', { title: "Rejection Failed" })
    } finally {
      setProcessing(false)
    }
  }

  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 claim details...</p>
        </div>
      </div>
    )
  }

  if (!claimData) {
    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">
          Claim Request Not Found
        </h3>
        <p className="text-gray-600 mb-6">
          The claim request you're looking for doesn't exist or has been removed.
        </p>
        <Link href="/admin/facilities/claims">
          <Button className="bg-[#3F5CEA] hover:bg-[#3F5CEA]/90">
            <ArrowLeft className="h-4 w-4 mr-2" />
            Back to Claims
          </Button>
        </Link>
      </div>
    )
  }

  const { claimRequest, facility, owner, ownerProfile, claimHistory } = claimData
  const canReview = ['pending', 'under_review', 'resubmitted'].includes(claimRequest.status)

  return (
    <div className="container mx-auto px-4 py-6 max-w-7xl">
      {/* Header */}
      <div className="mb-6">
        <Link href="/admin/facilities/claims">
          <Button variant="outline" size="sm" className="mb-3">
            <ArrowLeft className="h-4 w-4 mr-2" />
            Back to Claims
          </Button>
        </Link>
        <div className="flex flex-col sm:flex-row sm:items-start justify-between gap-3">
          <div>
            <h1 className="text-2xl md:text-3xl font-bold text-gray-900">
              Review Claim Request
            </h1>
            <p className="text-gray-600 mt-1">
              Submitted on {new Date(claimRequest.requestedAt).toLocaleDateString()}
            </p>
          </div>
          <Badge className={`${(claimRequest.status || '').trim() === 'pending'
              ? 'bg-yellow-100 text-yellow-800 border-yellow-200'
              : (claimRequest.status || '').trim() === 'approved'
                ? 'bg-green-100 text-green-800 border-green-200'
                : 'bg-red-100 text-red-800 border-red-200'
            }`}>
            {(claimRequest.status || '').trim() === 'pending' && <Clock className="h-3 w-3 mr-1" />}
            {(claimRequest.status || '').trim() === 'approved' && <CheckCircle className="h-3 w-3 mr-1" />}
            {(claimRequest.status || '').trim() === 'rejected' && <XCircle className="h-3 w-3 mr-1" />}
            {(claimRequest.status || '').trim().charAt(0).toUpperCase() + (claimRequest.status || '').trim().slice(1)}
          </Badge>
        </div>
      </div>

      {/* Action Buttons */}
      {canReview && (
        <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3 mb-6">
          <Button
            onClick={() => setShowApproveDialog(true)}
            className="bg-green-600 hover:bg-green-700"
          >
            <CheckCircle className="h-4 w-4 mr-2" />
            Approve Claim
          </Button>
          <Button
            onClick={() => setShowRejectDialog(true)}
            variant="destructive"
          >
            <XCircle className="h-4 w-4 mr-2" />
            Reject Claim
          </Button>
        </div>
      )}

      {claimRequest.status === 'rejected' && (
        <Badge variant="destructive" className="mb-6">Previously Rejected</Badge>
      )}

      {/* Main Content - Responsive Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left Column - Claims Details (Full width on mobile, 2 cols on desktop) */}
        <div className="lg:col-span-2 space-y-6">
          {/* Claimant Contact Information */}
          <Card>
            <CardHeader className="pb-4">
              <CardTitle className="flex items-center gap-2 text-lg">
                <User className="h-5 w-5 text-purple-600" />
                Claimant Contact Information
              </CardTitle>
              <p className="text-sm text-gray-600 mt-2">Person requesting to claim this facility</p>
            </CardHeader>
            <CardContent className="grid grid-cols-1 sm:grid-cols-2 gap-6">
              <div>
                <Label className="text-sm font-medium text-gray-500 block mb-2">Full Name</Label>
                <p className="text-base font-semibold text-gray-900">{claimRequest.claimantInfo?.name || 'N/A'}</p>
              </div>
              <div>
                <Label className="text-sm font-medium text-gray-500 block mb-2">Email Address</Label>
                <p className="text-base font-medium text-gray-900 flex items-center gap-2">
                  <Mail className="h-4 w-4 text-gray-400 flex-shrink-0" />
                  <span className="truncate">{owner.email || 'N/A'}</span>
                </p>
              </div>
              <div>
                <Label className="text-sm font-medium text-gray-500 block mb-2">Phone Number</Label>
                <p className="text-base font-medium text-gray-900 flex items-center gap-2">
                  <Phone className="h-4 w-4 text-gray-400 flex-shrink-0" />
                  {claimRequest.claimantInfo?.phone || 'N/A'}
                </p>
              </div>
              <div>
                <Label className="text-sm font-medium text-gray-500 block mb-2">Position/Title</Label>
                <p className="text-base font-medium text-gray-900">{claimRequest.claimantInfo?.position || 'N/A'}</p>
              </div>
              <div>
                <Label className="text-sm font-medium text-gray-500 block mb-2">Relationship to Facility</Label>
                <p className="text-base font-medium text-gray-900 capitalize">
                  {claimRequest.claimantInfo?.relationship?.replace(/_/g, ' ') || 'N/A'}
                </p>
              </div>
              <div>
                <Label className="text-sm font-medium text-gray-500 block mb-2">Business License Number</Label>
                <p className="text-base font-medium text-gray-900 font-mono tracking-wide">
                  {claimRequest.claimantInfo?.businessLicense || 'Not Provided'}
                </p>
              </div>
            </CardContent>
          </Card>

          {/* Facility Information */}
          <Card>
            <CardHeader className="pb-4">
              <CardTitle className="flex items-center gap-2 text-lg">
                <Building className="h-5 w-5 text-blue-600" />
                Facility Information
              </CardTitle>
              <p className="text-sm text-gray-600 mt-2">Current facility contact details</p>
            </CardHeader>
            <CardContent className="space-y-5">
              <div>
                <Label className="text-sm font-medium text-gray-700">Facility Name</Label>
                <p className="text-lg font-semibold text-gray-900 mt-1">{facility.name}</p>
              </div>

              <div>
                <Label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                  <MapPin className="h-4 w-4" />
                  Location
                </Label>
                <p className="text-gray-900 mt-1">
                  {facility.location.address}<br />
                  {facility.location.city}, {facility.location.state} {facility.location.zipCode}
                </p>
              </div>

              <div>
                <Label className="text-sm font-medium text-gray-700 flex items-center gap-2">
                  <FileText className="h-4 w-4" />
                  License Information
                </Label>
                <p className="text-gray-900 mt-1 font-mono">{facility.licensing.licenseNumber}</p>
                {facility.licensing.licenseType && (
                  <p className="text-sm text-gray-600 mt-1">{facility.licensing.licenseType}</p>
                )}
              </div>

              {facility.contact && (
                <div className="pt-4 border-t">
                  <Label className="text-sm font-medium text-gray-700 mb-2 block">Facility Contact Information</Label>
                  <div className="space-y-2">
                    {facility.contact.phone && (
                      <div className="flex items-center gap-2 text-sm">
                        <Phone className="h-4 w-4 text-gray-400" />
                        <span className="text-gray-900">{facility.contact.phone}</span>
                      </div>
                    )}
                    {facility.contact.email && (
                      <div className="flex items-center gap-2 text-sm">
                        <Mail className="h-4 w-4 text-gray-400" />
                        <span className="text-gray-900">{facility.contact.email}</span>
                      </div>
                    )}
                    {facility.contact.website && (
                      <div className="flex items-center gap-2 text-sm">
                        <Globe className="h-4 w-4 text-gray-400" />
                        <a href={facility.contact.website} target="_blank" rel="noopener noreferrer" className="text-[#3F5CEA] hover:underline">
                          {facility.contact.website}
                        </a>
                      </div>
                    )}
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Right Column - Actions (Full width on mobile, 1 col on desktop) */}
        <div className="space-y-6">
          <Card>
            <CardHeader className="pb-4">
              <CardTitle className="flex items-center gap-2 text-lg">
                <User className="h-5 w-5 text-purple-600" />
                Owner Information
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-5">
              <div>
                <Label className="text-sm font-medium text-gray-700">Name</Label>
                <p className="text-lg font-semibold text-gray-900 mt-1">
                  {owner.firstName} {owner.lastName}
                </p>
              </div>

              {ownerProfile?.businessInfo?.companyName && (
                <div>
                  <Label className="text-sm font-medium text-gray-700">Company</Label>
                  <p className="text-gray-900 mt-1">{ownerProfile.businessInfo.companyName}</p>
                </div>
              )}

              <div>
                <Label className="text-sm font-medium text-gray-700">Email</Label>
                <p className="text-gray-900 mt-1">{owner.email}</p>
              </div>

              {owner.phone && (
                <div>
                  <Label className="text-sm font-medium text-gray-700">Phone</Label>
                  <p className="text-gray-900 mt-1">{owner.phone}</p>
                </div>
              )}

              {ownerProfile?.verification && (
                <div className="pt-4 border-t">
                  <Label className="text-sm font-medium text-gray-700 block mb-2">Verification Status</Label>
                  <Badge className="capitalize" variant={
                    ownerProfile.verification.status === 'verified' ? 'default' : 'outline'
                  }>
                    {ownerProfile.verification.status}
                  </Badge>
                </div>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-4">
              <CardTitle className="text-lg">Claim Request Details</CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              <div>
                <Label className="text-sm font-medium text-gray-700 block mb-3">Reason for Claim</Label>
                <div className="bg-gray-50 rounded-lg p-4 border border-gray-200">
                  <p className="text-sm text-gray-900 whitespace-pre-wrap leading-relaxed">
                    {claimRequest.message}
                  </p>
                </div>
              </div>

              {claimRequest.documents && claimRequest.documents.length > 0 && (
                <div>
                  <Label className="text-sm font-medium text-gray-700 mb-3 block">
                    Supporting Documents ({claimRequest.documents.length})
                  </Label>
                  <div className="space-y-3">
                    {claimRequest.documents.map((doc: any, index: number) => {
                      // Extract filename from URL or use provided name
                      let displayName = doc.name

                      // If name looks like a hash/ID, try to extract filename from URL
                      if (displayName && displayName.length > 30 && displayName.match(/^[a-f0-9]+/i)) {
                        try {
                          const urlObj = new URL(doc.url)
                          const pathname = urlObj.pathname
                          const filename = pathname.split('/').pop()
                          if (filename && filename !== displayName) {
                            displayName = decodeURIComponent(filename)
                          } else {
                            // If still hash-like, create a user-friendly name
                            displayName = `Document ${index + 1}`
                          }
                        } catch (e) {
                          displayName = `Document ${index + 1}`
                        }
                      }

                      // Capitalize document type
                      const docType = doc.type ? doc.type.charAt(0).toUpperCase() + doc.type.slice(1) : 'Document'

                      return (
                        <div key={index} className="flex items-start gap-3 p-4 border border-gray-200 rounded-lg bg-gray-50 hover:bg-gray-100 transition-colors">
                          <FileText className="h-5 w-5 text-blue-600 flex-shrink-0 mt-0.5" />
                          <div className="flex-1 min-w-0">
                            <p className="font-medium text-gray-900 truncate" title={displayName}>
                              {displayName}
                            </p>
                            <p className="text-sm text-gray-500 mt-1">
                              {docType}
                              {doc.uploadedAt && ` • Uploaded ${new Date(doc.uploadedAt).toLocaleDateString('en-US', {
                                year: 'numeric',
                                month: 'short',
                                day: 'numeric'
                              })}`}
                              {doc.size && ` • ${(doc.size / 1024).toFixed(0)} KB`}
                            </p>
                          </div>
                          <Button variant="outline" size="sm" className="flex-shrink-0" asChild>
                            <a href={doc.url} target="_blank" rel="noopener noreferrer">
                              <Download className="h-3 w-3 mr-1" />
                              View
                            </a>
                          </Button>
                        </div>
                      )
                    })}
                  </div>
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Claim History */}
      {claimHistory && claimHistory.length > 1 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Calendar className="h-5 w-5 text-orange-600" />
              Claim History
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {claimHistory.map((claim: any, index: number) => (
                <div key={index} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                  <div className="flex items-center gap-3">
                    {claim.status === 'pending' && <Clock className="h-4 w-4 text-yellow-600" />}
                    {claim.status === 'approved' && <CheckCircle className="h-4 w-4 text-green-600" />}
                    {claim.status === 'rejected' && <XCircle className="h-4 w-4 text-red-600" />}
                    <div>
                      <p className="text-sm font-medium text-gray-900">
                        {claim.status.charAt(0).toUpperCase() + claim.status.slice(1)}
                      </p>
                      <p className="text-xs text-gray-600">
                        {new Date(claim.requestedAt).toLocaleDateString()}
                      </p>
                    </div>
                  </div>
                  {claim.reviewedAt && (
                    <p className="text-xs text-gray-500">
                      Reviewed: {new Date(claim.reviewedAt).toLocaleDateString()}
                    </p>
                  )}
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Approve Dialog */}
      <Dialog open={showApproveDialog} onOpenChange={setShowApproveDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Approve Claim Request</DialogTitle>
            <DialogDescription>
              Are you sure you want to approve this claim request for <strong>{facility.name}</strong>?
              This will grant {owner.firstName} {owner.lastName} ownership and management access.
            </DialogDescription>
          </DialogHeader>

          <div className="py-4">
            <Label htmlFor="admin-notes">Admin Notes (Optional)</Label>
            <Textarea
              id="admin-notes"
              placeholder="Add any notes for the owner..."
              value={adminNotes}
              onChange={(e) => setAdminNotes(e.target.value)}
              rows={3}
              className="mt-2"
            />
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setShowApproveDialog(false)}
              disabled={processing}
            >
              Cancel
            </Button>
            <Button
              onClick={handleApproveClaim}
              disabled={processing}
              className="bg-green-600 hover:bg-green-700"
            >
              {processing ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Approving...
                </>
              ) : (
                <>
                  <CheckCircle className="h-4 w-4 mr-2" />
                  Approve Claim
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Reject Dialog */}
      <Dialog open={showRejectDialog} onOpenChange={setShowRejectDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Reject Claim Request</DialogTitle>
            <DialogDescription>
              Please provide a reason for rejecting this claim request.
              The owner will receive this explanation via email.
            </DialogDescription>
          </DialogHeader>

          <div className="py-4">
            <Label htmlFor="rejection-reason">Rejection Reason *</Label>
            <Textarea
              id="rejection-reason"
              placeholder="Explain why this claim is being rejected..."
              value={rejectionReason}
              onChange={(e) => setRejectionReason(e.target.value)}
              rows={4}
              className="mt-2"
            />
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setShowRejectDialog(false)}
              disabled={processing}
            >
              Cancel
            </Button>
            <Button
              onClick={handleRejectClaim}
              disabled={processing}
              variant="destructive"
            >
              {processing ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Rejecting...
                </>
              ) : (
                <>
                  <XCircle className="h-4 w-4 mr-2" />
                  Reject Claim
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}

