'use client'

import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Search, FileText, Clock, CheckCircle, AlertCircle, Loader2, Download, User, Mail, Calendar, MapPin, Phone } from 'lucide-react'
import Link from 'next/link'

interface TrackingData {
  id: string
  trackingNumber: string
  service: {
    title: string
  }
  user: {
    name: string
    email: string
  }
  status: 'PENDING' | 'IN_PROGRESS' | 'NEED_REVISION' | 'REVIEWING' | 'COMPLETED'
  createdAt: string
  statusLog?: Array<{
    status: string
    timestamp: string
    message?: string
    adminName?: string
  }>
  submissionData?: any
  signatureUrl?: string
  photoUrl?: string
}

interface SystemSettings {
  heroTitle: string
  heroDescription: string
  heroBackgroundImage: string
  contactPhone: string
  contactEmail: string
  contactAddress: string
  organizationName: 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 TrackingPage() {
  const [trackingNumber, setTrackingNumber] = useState('')
  const [trackingData, setTrackingData] = useState<TrackingData | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [searched, setSearched] = useState(false)
  const [downloadingPDF, setDownloadingPDF] = useState(false)
  const [systemSettings, setSystemSettings] = useState<SystemSettings | null>(null)
  const [settingsLoading, setSettingsLoading] = useState(true)

  // Fetch system settings on component mount
  useEffect(() => {
    const fetchSettings = async () => {
      try {
        const response = await fetch('/api/settings')
        if (response.ok) {
          const data = await response.json()
          setSystemSettings(data)
        }
      } catch (error) {
        console.error('Failed to fetch system settings:', error)
      } finally {
        setSettingsLoading(false)
      }
    }

    fetchSettings()
  }, [])

  const handleTrack = async () => {
    if (!trackingNumber.trim()) {
      setError('Masukkan nomor pelacakan terlebih dahulu')
      return
    }

    setLoading(true)
    setError('')

    try {
      const response = await fetch(`/api/tracking/${trackingNumber}`)
      const data = await response.json()

      if (response.ok) {
        setTrackingData(data)
        setSearched(true)
      } else {
        setError(data.message || 'Nomor pelacakan tidak ditemukan')
        setTrackingData(null)
      }
    } catch (err) {
      setError('Terjadi kesalahan saat mencari data. Silakan coba lagi.')
      setTrackingData(null)
    } finally {
      setLoading(false)
    }
  }

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleTrack()
    }
  }

  const handleDownloadPDF = async () => {
    if (!trackingData) return
    
    setDownloadingPDF(true)
    try {
      const response = await fetch(`/api/public/download-pdf/${trackingData.trackingNumber}`)
      
      if (response.ok) {
        const blob = await response.blob()
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `${trackingData.trackingNumber}.pdf`
        document.body.appendChild(a)
        a.click()
        window.URL.revokeObjectURL(url)
        document.body.removeChild(a)
      } else {
        const data = await response.json()
        setError(data.message || 'Gagal mengunduh PDF')
      }
    } catch (err) {
      setError('Terjadi kesalahan saat mengunduh PDF')
    } finally {
      setDownloadingPDF(false)
    }
  }

  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, serviceTitle: 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>
      )
    }

    // Determine service type based on title
    const serviceSlug = serviceTitle.toLowerCase().includes('skck') ? 'skck' : 
                       serviceTitle.toLowerCase().includes('spkt') ? 'spkt' : 
                       serviceTitle.toLowerCase().includes('lalu lintas') ? 'lalu-lintas' : 'other'

    if (serviceSlug === 'skck') {
      return (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          {renderField('Nama Lengkap', data.fullName || data.name)}
          {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>
      )
    } else if (serviceSlug === 'spkt') {
      return (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          {renderField('Nama Pelapor', data.fullName || data.name)}
          {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)}
        </div>
      )
    } else if (serviceSlug === 'lalu-lintas') {
      return (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          {renderField('Nama Pemohon', data.fullName || data.name)}
          {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>
      )
    } else {
      return <div className="text-gray-500">Data tidak tersedia</div>
    }
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <section className="bg-amber-600 text-white py-16">
        <div className="max-w-4xl mx-auto px-4 text-center">
          <h1 className="text-3xl md:text-4xl font-bold mb-4">
            Lacak Pengajuan Anda
          </h1>
          <p className="text-lg opacity-90">
            Masukkan nomor pelacakan untuk memantau status pengajuan dokumen Anda
          </p>
          {systemSettings?.organizationName && (
            <p className="text-sm opacity-75 mt-2">
              {systemSettings.organizationName}
            </p>
          )}
        </div>
      </section>

      {/* Tracking Form */}
      <section className="py-12">
        <div className="max-w-2xl mx-auto px-4">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Search className="w-5 h-5" />
                Masukkan Nomor Pelacakan
              </CardTitle>
              <CardDescription>
                Nomor pelacakan Anda dapat ditemukan pada bukti pengajuan
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex gap-2">
                <Input
                  placeholder="Contoh: SRV-2024-001234"
                  value={trackingNumber}
                  onChange={(e) => setTrackingNumber(e.target.value)}
                  onKeyPress={handleKeyPress}
                  className="flex-1"
                />
                <Button 
                  onClick={handleTrack} 
                  disabled={loading}
                  className="bg-amber-600 hover:bg-amber-700"
                >
                  {loading ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    'Lacak'
                  )}
                </Button>
              </div>
              {error && (
                <div className="mt-4 p-3 bg-red-50 border border-red-200 rounded-md text-red-700 text-sm">
                  {error}
                </div>
              )}
            </CardContent>
          </Card>
        </div>
      </section>

      {/* Tracking Result */}
      {trackingData && (
        <section className="py-8">
          <div className="max-w-4xl mx-auto px-4">
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <CardTitle className="flex items-center gap-2">
                    <FileText className="w-5 h-5" />
                    Detail Pengajuan
                  </CardTitle>
                  <Badge className={statusConfig[trackingData.status].color}>
                    <div className="flex items-center gap-1">
                      {statusConfig[trackingData.status].icon}
                      {statusConfig[trackingData.status].label}
                    </div>
                  </Badge>
                </div>
              </CardHeader>
              <CardContent className="space-y-6">
                {/* Informasi Pemohon */}
                <div className="grid md:grid-cols-2 gap-4">
                  <div>
                    <label className="text-sm font-medium text-gray-500">Nomor Pelacakan</label>
                    <p className="font-mono font-semibold">{trackingData.trackingNumber}</p>
                  </div>
                  <div>
                    <label className="text-sm font-medium text-gray-500">Jenis Layanan</label>
                    <p className="font-semibold">{trackingData.service.title}</p>
                  </div>
                  <div>
                    <label className="text-sm font-medium text-gray-500">Nama Pemohon</label>
                    <div className="flex items-center gap-2">
                      <User className="w-4 h-4 text-gray-400" />
                      <p className="font-semibold">{trackingData.user.name}</p>
                    </div>
                  </div>
                  <div>
                    <label className="text-sm font-medium text-gray-500">Email</label>
                    <div className="flex items-center gap-2">
                      <Mail className="w-4 h-4 text-gray-400" />
                      <p className="text-sm">{trackingData.user.email}</p>
                    </div>
                  </div>
                  <div>
                    <label className="text-sm font-medium text-gray-500">Tanggal Pengajuan</label>
                    <div className="flex items-center gap-2">
                      <Calendar className="w-4 h-4 text-gray-400" />
                      <p>{formatDate(trackingData.createdAt)}</p>
                    </div>
                  </div>
                  <div>
                    <label className="text-sm font-medium text-gray-500">Status Saat Ini</label>
                    <Badge className={statusConfig[trackingData.status].color}>
                      <div className="flex items-center gap-1">
                        {statusConfig[trackingData.status].icon}
                        {statusConfig[trackingData.status].label}
                      </div>
                    </Badge>
                  </div>
                </div>

                {/* Data Pengajuan Lengkap */}
                {trackingData.submissionData && (
                  <div>
                    <h4 className="font-semibold mb-3 flex items-center gap-2">
                      <FileText className="w-4 h-4" />
                      Data Pengajuan
                    </h4>
                    {renderSubmissionData(trackingData.submissionData, trackingData.service.title)}
                  </div>
                )}

                {/* Dokumen Upload */}
                {(trackingData.photoUrl || trackingData.signatureUrl) && (
                  <div>
                    <h4 className="font-semibold mb-3">Dokumen Terlampir</h4>
                    <div className="grid md:grid-cols-2 gap-4">
                      {trackingData.photoUrl && (
                        <div>
                          <label className="text-sm font-medium text-gray-500">Foto Pemohon</label>
                          <div className="mt-1">
                            <img 
                              src={trackingData.photoUrl} 
                              alt="Foto Pemohon" 
                              className="w-32 h-40 object-cover rounded border"
                            />
                          </div>
                        </div>
                      )}
                      {trackingData.signatureUrl && (
                        <div>
                          <label className="text-sm font-medium text-gray-500">Tanda Tangan</label>
                          <div className="mt-1">
                            <img 
                              src={trackingData.signatureUrl} 
                              alt="Tanda Tangan" 
                              className="w-32 h-20 object-contain rounded border"
                            />
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                )}

                {/* Status Log */}
                {trackingData.statusLog && Array.isArray(trackingData.statusLog) && trackingData.statusLog.length > 0 && (
                  <div>
                    <h4 className="font-semibold mb-3">Riwayat Status</h4>
                    <div className="space-y-3">
                      {trackingData.statusLog.map((log, index) => (
                        <div key={index} className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
                          <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>
                  </div>
                )}

                {/* Action Buttons */}
                <div className="flex gap-3 pt-4 border-t">
                  <Button variant="outline" asChild>
                    <Link href="/">Kembali ke Beranda</Link>
                  </Button>
                  {trackingData.status === 'COMPLETED' && (
                    <Button 
                      onClick={handleDownloadPDF}
                      disabled={downloadingPDF}
                      className="bg-green-600 hover:bg-green-700"
                    >
                      {downloadingPDF ? (
                        <>
                          <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                          Mengunduh...
                        </>
                      ) : (
                        <>
                          <Download className="w-4 h-4 mr-2" />
                          Unduh PDF
                        </>
                      )}
                    </Button>
                  )}
                  {trackingData.status === 'NEED_REVISION' && (
                    <Button asChild className="bg-amber-600 hover:bg-amber-700">
                      <Link href={`/ajuan/revisi/${trackingData.trackingNumber}`}>
                        Ajukan Revisi
                      </Link>
                    </Button>
                  )}
                </div>
              </CardContent>
            </Card>
          </div>
        </section>
      )}

      {/* Help Section */}
      {!searched && (
        <section className="py-12">
          <div className="max-w-4xl mx-auto px-4">
            <Card>
              <CardHeader>
                <CardTitle>Pusat Bantuan</CardTitle>
                <CardDescription>
                  Butuh bantuan dengan pelacakan pengajuan Anda?
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="grid md:grid-cols-2 gap-6">
                  <div>
                    <h4 className="font-semibold mb-2">Cara Melacak Pengajuan</h4>
                    <ol className="text-sm text-gray-600 space-y-1 list-decimal list-inside">
                      <li>Buka email konfirmasi yang Anda terima</li>
                      <li>Temukan nomor pelacakan di email tersebut</li>
                      <li>Masukkan nomor pelacakan di form di atas</li>
                      <li>Klik tombol "Lacak" untuk melihat status</li>
                    </ol>
                  </div>
                  <div>
                    <h4 className="font-semibold mb-2">Kontak Bantuan</h4>
                    {settingsLoading ? (
                      <div className="text-sm text-gray-600 space-y-1">
                        <p>Memuat informasi kontak...</p>
                      </div>
                    ) : systemSettings ? (
                      <div className="text-sm text-gray-600 space-y-1">
                        {systemSettings.contactPhone && (
                          <p>📞 {systemSettings.contactPhone}</p>
                        )}
                        {systemSettings.contactEmail && (
                          <p>📧 {systemSettings.contactEmail}</p>
                        )}
                        {systemSettings.contactAddress && (
                          <p>📍 {systemSettings.contactAddress}</p>
                        )}
                      </div>
                    ) : (
                      <div className="text-sm text-gray-600 space-y-1">
                        <p>📞 (0286) 321001</p>
                        <p>📧 polreswonosobo@polri.go.id</p>
                        <p>📍 Jl. Pahlawan No. 15, Wonosobo</p>
                      </div>
                    )}
                  </div>
                </div>
                
                {/* Back to Home Button */}
                <div className="mt-6 pt-6 border-t">
                  <div className="flex justify-center">
                    <Button variant="outline" asChild>
                      <Link href="/">
                        Kembali ke Beranda
                      </Link>
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </section>
      )}
    </div>
  )
}