'use client'

import { useEffect, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { StatusWorkflow } from '@/components/status-workflow'
import { AdminSidebar } from '@/components/admin-sidebar'
import { 
  ArrowLeft, 
  FileText, 
  Clock, 
  CheckCircle, 
  AlertCircle, 
  Search,
  Upload,
  Download,
  Menu,
  X,
  Loader2,
  User,
  Calendar,
  MapPin,
  Phone,
  Mail,
  Settings
} from 'lucide-react'
import Link from 'next/link'
import { useRouter, useParams } from 'next/navigation'

interface ServiceRequest {
  id: string
  trackingNumber: string
  service: {
    title: string
    slug: string
  }
  user: {
    name: string
    email: string
  }
  status: string
  submissionData: any
  statusLog: Array<{
    status: string
    timestamp: string
    message?: string
    adminName?: string
  }>
  signatureUrl?: string
  photoUrl?: string
  createdAt: string
  updatedAt: string
}

const statusConfig = {
  PENDING: {
    label: 'Menunggu Verifikasi',
    color: 'bg-yellow-100 text-yellow-800',
    icon: <Clock className="w-4 h-4" />
  },
  IN_PROGRESS: {
    label: 'Sedang Diproses',
    color: 'bg-amber-100 text-amber-800',
    icon: <Loader2 className="w-4 h-4 animate-spin" />
  },
  NEED_REVISION: {
    label: 'Perlu Revisi',
    color: 'bg-orange-100 text-orange-800',
    icon: <AlertCircle className="w-4 h-4" />
  },
  REVIEWING: {
    label: 'Sedang Ditinjau',
    color: 'bg-purple-100 text-purple-800',
    icon: <Search className="w-4 h-4" />
  },
  COMPLETED: {
    label: 'Selesai',
    color: 'bg-green-100 text-green-800',
    icon: <CheckCircle className="w-4 h-4" />
  }
}

export default function RequestDetailPage() {
  const router = useRouter()
  const params = useParams()
  const requestId = params.id as string
  
  const [request, setRequest] = useState<ServiceRequest | null>(null)
  const [loading, setLoading] = useState(true)
  const [user, setUser] = useState<any>(null)
  const [pickupLocations, setPickupLocations] = useState<any[]>([])
  
  // Status update form
  const [newStatus, setNewStatus] = useState('')
  const [statusMessage, setStatusMessage] = useState('')
  const [isUpdating, setIsUpdating] = useState(false)
  const [updateMessage, setUpdateMessage] = useState('')
  
  // File upload
  const [uploadingPhoto, setUploadingPhoto] = useState(false)
  const [uploadingSignature, setUploadingSignature] = useState(false)

  useEffect(() => {
    // Check authentication
    const token = localStorage.getItem('adminToken')
    const userData = localStorage.getItem('adminUser')
    
    if (!token || !userData) {
      router.push('/admin/login')
      return
    }

    try {
      setUser(JSON.parse(userData))
    } catch (error) {
      router.push('/admin/login')
      return
    }

    fetchRequestDetail()
    fetchPickupLocations()
  }, [router, requestId])

  const fetchPickupLocations = async () => {
    try {
      const response = await fetch('/api/pickup-locations')
      const data = await response.json()
      
      if (data.success) {
        setPickupLocations(data.data)
      }
    } catch (error) {
      console.error('Error fetching pickup locations:', error)
    }
  }

  const getPickupLocationName = (locationId: string) => {
    const location = pickupLocations.find(loc => loc.id === locationId)
    return location ? location.name : locationId
  }

  const fetchRequestDetail = async () => {
    try {
      const token = localStorage.getItem('adminToken')
      const response = await fetch(`/api/admin/requests/${requestId}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })

      if (response.ok) {
        const data = await response.json()
        setRequest(data)
        setNewStatus(data.status)
      } else if (response.status === 401) {
        localStorage.removeItem('adminToken')
        localStorage.removeItem('adminUser')
        router.push('/admin/login')
      } else {
        setUpdateMessage('Pengajuan tidak ditemukan')
      }
    } catch (error) {
      console.error('Error fetching request detail:', error)
      setUpdateMessage('Terjadi kesalahan saat memuat data')
    } finally {
      setLoading(false)
    }
  }

  const handleStatusUpdate = async () => {
    if (!newStatus) {
      setUpdateMessage('Pilih status terlebih dahulu')
      return
    }

    setIsUpdating(true)
    setUpdateMessage('')

    try {
      const token = localStorage.getItem('adminToken')
      const response = await fetch(`/api/admin/requests/${requestId}/status`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          status: newStatus,
          message: statusMessage
        })
      })

      if (response.ok) {
        setUpdateMessage('Status berhasil diperbarui')
        fetchRequestDetail() // Refresh data
      } else {
        const data = await response.json()
        setUpdateMessage(data.message || 'Gagal memperbarui status')
      }
    } catch (error) {
      setUpdateMessage('Terjadi kesalahan jaringan')
    } finally {
      setIsUpdating(false)
    }
  }

  const handleFileUpload = async (fileType: 'photo' | 'signature', file: File) => {
    const setUploading = fileType === 'photo' ? setUploadingPhoto : setUploadingSignature
    
    if (!file) return
    
    setUploading(true)
    setUpdateMessage('')

    try {
      const token = localStorage.getItem('adminToken')
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', fileType)

      const response = await fetch(`/api/admin/requests/${requestId}/upload`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`
        },
        body: formData
      })

      if (response.ok) {
        setUpdateMessage(`${fileType === 'photo' ? 'Foto' : 'Tanda tangan'} berhasil diunggah`)
        fetchRequestDetail() // Refresh data
      } else {
        const data = await response.json()
        setUpdateMessage(data.message || `Gagal mengunggah ${fileType === 'photo' ? 'foto' : 'tanda tangan'}`)
      }
    } catch (error) {
      setUpdateMessage('Terjadi kesalahan jaringan')
    } finally {
      setUploading(false)
    }
  }

  const handleDownloadPDF = async () => {
    try {
      const token = localStorage.getItem('adminToken')
      const response = await fetch(`/api/admin/requests/${requestId}/download-pdf`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })

      if (response.ok) {
        const blob = await response.blob()
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `${request?.trackingNumber}.pdf`
        document.body.appendChild(a)
        a.click()
        window.URL.revokeObjectURL(url)
        document.body.removeChild(a)
      } else {
        setUpdateMessage('Gagal mengunduh PDF')
      }
    } catch (error) {
      setUpdateMessage('Terjadi kesalahan saat mengunduh PDF')
    }
  }

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString('id-ID', {
      day: 'numeric',
      month: 'long',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  const renderSubmissionData = (data: any, serviceSlug: string) => {
    if (!data) return null

    const renderField = (label: string, value: any) => {
      if (!value) return null
      return (
        <div className="p-3 bg-gray-50 rounded">
          <div className="text-xs font-medium text-gray-500 mb-1">{label}</div>
          <div className="text-sm text-gray-900">{value}</div>
        </div>
      )
    }

    switch (serviceSlug) {
      case 'skck':
        return (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            {renderField('Nama Lengkap', data.fullName)}
            {renderField('Tempat/Tanggal Lahir', `${data.placeOfBirth}, ${data.dateOfBirth}`)}
            {renderField('Jenis Kelamin', data.gender === 'L' ? 'Laki-laki' : 'Perempuan')}
            {renderField('Agama', data.religion)}
            {renderField('Pekerjaan', data.occupation)}
            {renderField('Alamat', `${data.address}, ${data.village}, ${data.district}, ${data.regency}, ${data.province}`)}
            {renderField('Telepon', data.phone)}
            {renderField('Email', data.email)}
            {renderField('No. KTP', data.identityNumber)}
            {renderField('Keperluan', data.purpose)}
          </div>
        )
      case 'spkt':
        return (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            {renderField('Nama Pelapor', data.fullName)}
            {renderField('Tempat/Tanggal Lahir', `${data.placeOfBirth}, ${data.dateOfBirth}`)}
            {renderField('Jenis Kelamin', data.gender === 'L' ? 'Laki-laki' : 'Perempuan')}
            {renderField('Pekerjaan', data.occupation)}
            {renderField('Alamat', `${data.address}, ${data.village}, ${data.district}, ${data.regency}, ${data.province}`)}
            {renderField('Telepon', data.phone)}
            {renderField('Email', data.email)}
            {renderField('Jenis Laporan', data.reportType)}
            {renderField('Tanggal Kejadian', data.incidentDate)}
            {renderField('Lokasi Kejadian', data.incidentLocation)}
            {renderField('Kronologi', data.incidentDescription)}
            {renderField('Informasi Saksi', data.witnessInfo)}
            {/* Tampilkan informasi barang hilang jika reportType adalah kehilangan */}
            {data.reportType === 'kehilangan' && (
              <>
                {renderField('Barang yang Hilang', data.additionalInfo)}
                {data.pickupLocation && renderField('Lokasi Pengambilan', getPickupLocationName(data.pickupLocation))}
              </>
            )}
          </div>
        )
      case 'lalu-lintas':
        return (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            {renderField('Nama Pemohon', data.fullName)}
            {renderField('Tempat/Tanggal Lahir', `${data.placeOfBirth}, ${data.dateOfBirth}`)}
            {renderField('Jenis Kelamin', data.gender === 'L' ? 'Laki-laki' : 'Perempuan')}
            {renderField('Pekerjaan', data.occupation)}
            {renderField('Alamat', `${data.address}, ${data.village}, ${data.district}, ${data.regency}, ${data.province}`)}
            {renderField('Telepon', data.phone)}
            {renderField('Email', data.email)}
            {renderField('Jenis Layanan', data.serviceType)}
            {renderField('Jenis Kendaraan', data.vehicleType)}
            {renderField('Merek Kendaraan', data.vehicleBrand)}
            {renderField('Tipe Kendaraan', data.vehicleTypeDetail)}
            {renderField('Warna Kendaraan', data.vehicleColor)}
            {renderField('Nomor Polisi', data.vehicleNumber)}
            {renderField('Keperluan', data.purpose)}
          </div>
        )
      default:
        return <div className="text-gray-500">Data tidak tersedia</div>
    }
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-amber-600 mx-auto"></div>
          <p className="mt-2 text-gray-600">Memuat detail pengajuan...</p>
        </div>
      </div>
    )
  }

  if (!request) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <FileText className="h-12 w-12 mx-auto mb-4 text-gray-400" />
          <p className="text-gray-500">Pengajuan tidak ditemukan</p>
          <Button asChild className="mt-4">
            <Link href="/admin/requests">Kembali ke Daftar</Link>
          </Button>
        </div>
      </div>
    )
  }

  return (
    <AdminSidebar user={user}>
      <div className="mt-6">
        {/* Alert Messages */}
        {updateMessage && (
          <Alert>
            <AlertDescription>{updateMessage}</AlertDescription>
          </Alert>
        )}

      {/* Request Header */}
      <Card className="hover:shadow-lg transition-shadow">
        <CardHeader>
          <div className="flex justify-between items-start">
            <div>
              <CardTitle className="flex items-center gap-2">
                <FileText className="w-5 h-5" />
                {request.trackingNumber}
              </CardTitle>
              <CardDescription className="mt-2">
                {request.service.title} • Diajukan oleh {request.user.name}
              </CardDescription>
            </div>
            <div className="flex items-center gap-3">
              <Badge className={statusConfig[request.status as keyof typeof statusConfig].color}>
                <div className="flex items-center gap-1">
                  {statusConfig[request.status as keyof typeof statusConfig].icon}
                  {statusConfig[request.status as keyof typeof statusConfig].label}
                </div>
              </Badge>
              <Button variant="outline" size="sm" onClick={handleDownloadPDF}>
                <Download className="h-4 w-4 mr-2" />
                Unduh PDF
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className="grid md:grid-cols-2 gap-4 text-sm">
            <div className="flex items-center gap-2">
              <Calendar className="w-4 h-4 text-gray-400" />
              <span className="text-gray-600">Diajukan:</span>
              <span className="font-medium">{formatDate(request.createdAt)}</span>
            </div>
            <div className="flex items-center gap-2">
              <Mail className="w-4 h-4 text-gray-400" />
              <span className="text-gray-600">Email:</span>
              <span className="font-medium">{request.user.email}</span>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Main Content Grid */}
      <div className="grid lg:grid-cols-3 gap-6">
        {/* Left Column - Data Pengajuan & Status History */}
        <div className="lg:col-span-2 space-y-6">
          {/* Submission Data */}
          <Card className="hover:shadow-lg transition-shadow mt-6">
            <CardHeader>
              <CardTitle>Data Pengajuan</CardTitle>
              <CardDescription>
                Informasi lengkap yang diajukan oleh pemohon
              </CardDescription>
            </CardHeader>
            <CardContent>
              {renderSubmissionData(request.submissionData, request.service.slug)}
            </CardContent>
          </Card>

          {/* Status Workflow */}
          <StatusWorkflow 
            currentStatus={request.status}
            statusLog={request.statusLog}
          />

          {/* Status History */}
          <Card className="hover:shadow-lg transition-shadow">
            <CardHeader>
              <CardTitle>Riwayat Status</CardTitle>
              <CardDescription>
                Log perubahan status pengajuan
              </CardDescription>
            </CardHeader>
            <CardContent>
              {request.statusLog && Array.isArray(request.statusLog) && request.statusLog.length > 0 ? (
                <div className="space-y-3">
                  {request.statusLog.map((log, index) => (
                    <div key={index} className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
                      <div className="w-2 h-2 bg-amber-600 rounded-full mt-2 flex-shrink-0" />
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          <span className="font-medium text-sm">
                            {statusConfig[log.status as keyof typeof statusConfig]?.label || log.status}
                          </span>
                          <span className="text-xs text-gray-500">
                            {formatDate(log.timestamp)}
                          </span>
                        </div>
                        {log.message && (
                          <p className="text-sm text-gray-600">{log.message}</p>
                        )}
                        {log.adminName && (
                          <p className="text-xs text-gray-500 mt-1">
                            Oleh: {log.adminName}
                          </p>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-gray-500 text-center py-4">Belum ada riwayat perubahan status</p>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Right Column - Status Management & File Upload */}
        <div className="space-y-6">
          {/* Status Management */}
          <Card className="hover:shadow-lg transition-shadow mt-6">
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Settings className="w-5 h-5" />
                Kelola Status
              </CardTitle>
              <CardDescription>
                Perbarui status dan tambahkan catatan
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <Label htmlFor="status">Status Baru</Label>
                <Select value={newStatus} onValueChange={setNewStatus}>
                  <SelectTrigger>
                    <SelectValue placeholder="Pilih status" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="PENDING">Menunggu Verifikasi</SelectItem>
                    <SelectItem value="IN_PROGRESS">Sedang Diproses</SelectItem>
                    <SelectItem value="NEED_REVISION">Perlu Revisi</SelectItem>
                    <SelectItem value="REVIEWING">Sedang Ditinjau</SelectItem>
                    <SelectItem value="COMPLETED">Selesai</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label htmlFor="message">Catatan (Opsional)</Label>
                <Textarea
                  id="message"
                  placeholder="Tambahkan catatan untuk perubahan status..."
                  value={statusMessage}
                  onChange={(e) => setStatusMessage(e.target.value)}
                  rows={3}
                />
              </div>
              
              {/* Quick Actions for NEED_REVISION */}
              {newStatus === 'NEED_REVISION' && (
                <div className="p-3 bg-orange-50 border border-orange-200 rounded-lg">
                  <p className="text-sm font-medium text-orange-800 mb-2">Permintaan Dokumen:</p>
                  <div className="space-y-2">
                    <Button
                      variant="outline"
                      size="sm"
                      className="w-full justify-start"
                      onClick={() => setStatusMessage('Admin meminta Anda untuk menyediakan foto terbaru.')
                    }
                    >
                      <User className="w-4 h-4 mr-2" />
                      Butuh Foto
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      className="w-full justify-start"
                      onClick={() => setStatusMessage('Admin meminta Anda untuk menyediakan tanda tangan.')
                    }
                    >
                      <FileText className="w-4 h-4 mr-2" />
                      Butuh Tanda Tangan
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      className="w-full justify-start"
                      onClick={() => setStatusMessage('Admin meminta Anda untuk menyediakan foto dan tanda tangan.')
                    }
                    >
                      <div className="flex items-center gap-2">
                        <User className="w-4 h-4" />
                        <span>+</span>
                        <FileText className="w-4 h-4" />
                      </div>
                      Butuh Foto & TTD
                    </Button>
                  </div>
                </div>
              )}
              
              <Button 
                onClick={handleStatusUpdate} 
                disabled={isUpdating || newStatus === request.status}
                className="w-full bg-amber-600 hover:bg-amber-700"
              >
                {isUpdating ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    Memperbarui...
                  </>
                ) : (
                  'Perbarui Status'
                )}
              </Button>
            </CardContent>
          </Card>

          {/* File Upload */}
          <Card className="hover:shadow-lg transition-shadow">
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Upload className="w-5 h-5" />
                Unggah Dokumen
              </CardTitle>
              <CardDescription>
                Unggah foto dan tanda tangan pemohon
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* Photo Upload */}
              <div>
                <Label className="text-sm font-medium">Foto Pemohon</Label>
                <div className="mt-2">
                  {request.photoUrl ? (
                    <div className="space-y-2">
                      <img 
                        src={request.photoUrl} 
                        alt="Foto pemohon" 
                        className="w-full h-32 object-cover rounded-lg border"
                      />
                      <p className="text-xs text-green-600">✓ Foto telah diunggah</p>
                    </div>
                  ) : (
                    <div className="border-2 border-dashed border-gray-300 rounded-lg p-4 text-center">
                      <Upload className="w-8 h-8 mx-auto mb-2 text-gray-400" />
                      <p className="text-sm text-gray-600 mb-2">Belum ada foto</p>
                      <input
                        type="file"
                        accept="image/*"
                        onChange={(e) => e.target.files?.[0] && handleFileUpload('photo', e.target.files[0])}
                        disabled={uploadingPhoto}
                        className="hidden"
                        id="photo-upload"
                      />
                      <Button 
                        variant="outline" 
                        size="sm"
                        disabled={uploadingPhoto}
                        onClick={() => document.getElementById('photo-upload')?.click()}
                        className="w-full"
                      >
                        {uploadingPhoto ? (
                          <>
                            <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                            Mengunggah...
                          </>
                        ) : (
                          'Pilih Foto'
                        )}
                      </Button>
                    </div>
                  )}
                </div>
              </div>

              {/* Signature Upload */}
              <div>
                <Label className="text-sm font-medium">Tanda Tangan</Label>
                <div className="mt-2">
                  {request.signatureUrl ? (
                    <div className="space-y-2">
                      <img 
                        src={request.signatureUrl} 
                        alt="Tanda tangan" 
                        className="w-full h-32 object-contain rounded-lg border bg-white"
                      />
                      <p className="text-xs text-green-600">✓ Tanda tangan telah diunggah</p>
                    </div>
                  ) : (
                    <div className="border-2 border-dashed border-gray-300 rounded-lg p-4 text-center">
                      <Upload className="w-8 h-8 mx-auto mb-2 text-gray-400" />
                      <p className="text-sm text-gray-600 mb-2">Belum ada tanda tangan</p>
                      <input
                        type="file"
                        accept="image/*"
                        onChange={(e) => e.target.files?.[0] && handleFileUpload('signature', e.target.files[0])}
                        disabled={uploadingSignature}
                        className="hidden"
                        id="signature-upload"
                      />
                      <Button 
                        variant="outline" 
                        size="sm"
                        disabled={uploadingSignature}
                        onClick={() => document.getElementById('signature-upload')?.click()}
                        className="w-full"
                      >
                        {uploadingSignature ? (
                          <>
                            <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                            Mengunggah...
                          </>
                        ) : (
                          'Pilih Tanda Tangan'
                        )}
                      </Button>
                    </div>
                  )}
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
      </div>
    </AdminSidebar>
  )
}