'use client'

import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Textarea } from '@/components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Checkbox } from '@/components/ui/checkbox'
import { ArrowLeft, Shield, Upload, Loader2, CheckCircle } from 'lucide-react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'

interface FormData {
  fullName: string
  placeOfBirth: string
  dateOfBirth: string
  gender: string
  nationality: string
  religion: string
  occupation: string
  address: string
  village: string
  district: string
  regency: string
  province: string
  phone: string
  email: string
  identityNumber: string
  reportType: string
  incidentDate: string
  incidentLocation: string
  incidentDescription: string
  witnessInfo: string
  additionalInfo: string
  pickupLocation: string
  agreeToTerms: boolean
}

interface PickupLocation {
  id: string
  name: string
  type: 'polres' | 'polsek'
  address: string
  phone?: string
  email?: string
  chief?: string
  polresName?: string
}

export default function SPKTForm() {
  const router = useRouter()
  const [currentStep, setCurrentStep] = useState(1)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [isSubmitted, setIsSubmitted] = useState(false)
  const [trackingNumber, setTrackingNumber] = useState('')
  const [pickupLocations, setPickupLocations] = useState<PickupLocation[]>([])
  const [isLoadingLocations, setIsLoadingLocations] = useState(true)
  const [formData, setFormData] = useState<FormData>({
    fullName: '',
    placeOfBirth: '',
    dateOfBirth: '',
    gender: '',
    nationality: 'Indonesia',
    religion: '',
    occupation: '',
    address: '',
    village: '',
    district: '',
    regency: '',
    province: '',
    phone: '',
    email: '',
    identityNumber: '',
    reportType: '',
    incidentDate: '',
    incidentLocation: '',
    incidentDescription: '-',
    witnessInfo: '-',
    additionalInfo: '',
    pickupLocation: '',
    agreeToTerms: false
  })

  const handleInputChange = (field: keyof FormData, value: string | boolean) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
  }

  // Fetch pickup locations on component mount
  useEffect(() => {
    const fetchPickupLocations = async () => {
      try {
        const response = await fetch('/api/pickup-locations')
        const data = await response.json()
        
        if (data.success) {
          setPickupLocations(data.data)
        } else {
          console.error('Failed to fetch pickup locations:', data.message)
        }
      } catch (error) {
        console.error('Error fetching pickup locations:', error)
      } finally {
        setIsLoadingLocations(false)
      }
    }

    fetchPickupLocations()
  }, [])

  const validateStep = (step: number): boolean => {
    switch (step) {
      case 1:
        return !!(formData.fullName && formData.placeOfBirth && formData.dateOfBirth && 
                 formData.gender && formData.religion && formData.nationality)
      case 2:
        return !!(formData.occupation && formData.address && 
                 formData.village && formData.district && formData.regency && formData.province)
      case 3:
        return !!(formData.phone && formData.email && formData.identityNumber && 
                 formData.reportType && formData.incidentDate && formData.incidentLocation)
      case 4:
        return !!(formData.additionalInfo && formData.pickupLocation && formData.agreeToTerms)
      default:
        return false
    }
  }

  const nextStep = () => {
    if (validateStep(currentStep)) {
      setCurrentStep(prev => Math.min(prev + 1, 4))
    }
  }

  const prevStep = () => {
    setCurrentStep(prev => Math.max(prev - 1, 1))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!validateStep(4)) {
      return
    }

    setIsSubmitting(true)

    try {
      const response = await fetch('/api/service-requests', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          serviceSlug: 'spkt',
          submissionData: formData
        })
      })

      const data = await response.json()

      if (response.ok) {
        setTrackingNumber(data.trackingNumber)
        setIsSubmitted(true)
      } else {
        alert(data.message || 'Terjadi kesalahan saat mengajukan permohonan')
      }
    } catch (error) {
      alert('Terjadi kesalahan jaringan. Silakan coba lagi.')
    } finally {
      setIsSubmitting(false)
    }
  }

  if (isSubmitted) {
    return (
      <div className="min-h-screen bg-gray-50 py-8">
        <div className="max-w-2xl mx-auto px-4">
          <Card className="text-center">
            <CardHeader>
              <div className="mx-auto mb-4 p-3 bg-green-100 rounded-full text-green-600 w-fit">
                <CheckCircle className="w-8 h-8" />
              </div>
              <CardTitle className="text-2xl text-green-600">Pengajuan Berhasil!</CardTitle>
              <CardDescription>
                Laporan Anda ke SPKT telah berhasil diajukan
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="p-4 bg-amber-50 rounded-lg">
                <p className="text-sm text-gray-600 mb-1">Nomor Pelacakan:</p>
                <p className="text-xl font-mono font-bold text-amber-600">{trackingNumber}</p>
              </div>
              <p className="text-sm text-gray-600">
                Simpan nomor pelacakan ini untuk memantau status laporan Anda. 
                Anda juga akan menerima email konfirmasi.
              </p>
              <div className="flex gap-3 justify-center">
                <Link href="/lacak">
                  <Button variant="outline">
                    Lacak Pengajuan
                  </Button>
                </Link>
                <Link href="/">
                  <Button>
                    Kembali ke Beranda
                  </Button>
                </Link>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <div className="bg-amber-600 text-white px-4 py-8">
        <div className="max-w-4xl mx-auto">
          <div className="flex items-center gap-4 mb-4">
            <Link href="/" className="text-white hover:bg-amber-700 p-2 rounded">
              <ArrowLeft className="w-4 h-4" />
            </Link>
          </div>
          <div className="text-center">
            <h1 className="text-3xl font-bold mb-2">Pengajuan SPKT</h1>
            <p className="opacity-90">Surat Pemberitahuan Kepolisian Terpadu</p>
          </div>
        </div>
      </div>

      {/* Progress Steps */}
      <div className="bg-white border-b px-4 py-6 mb-6">
        <div className="max-w-4xl mx-auto">
          <div className="flex items-center justify-between overflow-x-auto">
            {[1, 2, 3, 4].map((step) => (
              <div key={step} className="flex items-center flex-shrink-0 min-w-0">
                <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium ${
                  currentStep >= step 
                    ? 'bg-amber-600 text-white' 
                    : 'bg-gray-200 text-gray-600'
                }`}>
                  {step}
                </div>
                <span className={`ml-2 text-sm hidden sm:block ${
                  currentStep >= step ? 'text-amber-600 font-medium' : 'text-gray-600'
                }`}>
                  {step === 1 && 'Data Diri'}
                  {step === 2 && 'Alamat'}
                  {step === 3 && 'Info Laporan'}
                  {step === 4 && 'Detail Kejadian'}
                </span>
                {step < 4 && (
                  <div className={`w-8 sm:w-16 h-1 mx-2 sm:mx-4 ${
                    currentStep > step ? 'bg-amber-600' : 'bg-gray-200'
                  }`} />
                )}
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Form */}
      <div className="max-w-4xl mx-auto px-4 pb-8">
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* Step 1: Personal Data */}
          {currentStep === 1 && (
            <Card>
              <CardHeader>
                <CardTitle>Data Diri Pelapor</CardTitle>
                <CardDescription>
                  Lengkapi data pribadi Anda dengan benar
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid md:grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="fullName">Nama Lengkap *</Label>
                    <Input
                      id="fullName"
                      value={formData.fullName}
                      onChange={(e) => handleInputChange('fullName', e.target.value)}
                      placeholder="Masukkan nama lengkap"
                      required
                    />
                  </div>
                  <div>
                    <Label htmlFor="placeOfBirth">Tempat Lahir *</Label>
                    <Input
                      id="placeOfBirth"
                      value={formData.placeOfBirth}
                      onChange={(e) => handleInputChange('placeOfBirth', e.target.value)}
                      placeholder="Masukkan tempat lahir"
                      required
                    />
                  </div>
                </div>
                
                <div className="grid md:grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="dateOfBirth">Tanggal Lahir *</Label>
                    <Input
                      id="dateOfBirth"
                      type="date"
                      value={formData.dateOfBirth}
                      onChange={(e) => handleInputChange('dateOfBirth', e.target.value)}
                      required
                    />
                  </div>
                  <div>
                    <Label htmlFor="gender">Jenis Kelamin *</Label>
                    <Select value={formData.gender} onValueChange={(value) => handleInputChange('gender', value)}>
                      <SelectTrigger>
                        <SelectValue placeholder="Pilih jenis kelamin" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="L">Laki-laki</SelectItem>
                        <SelectItem value="P">Perempuan</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="grid md:grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="nationality">Kewarganegaraan *</Label>
                    <Input
                      id="nationality"
                      value={formData.nationality}
                      onChange={(e) => handleInputChange('nationality', e.target.value)}
                      placeholder="Masukkan kewarganegaraan"
                      required
                    />
                  </div>
                  <div>
                    <Label htmlFor="religion">Agama *</Label>
                    <Select value={formData.religion} onValueChange={(value) => handleInputChange('religion', value)}>
                      <SelectTrigger>
                        <SelectValue placeholder="Pilih agama" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="Islam">Islam</SelectItem>
                        <SelectItem value="Kristen">Kristen</SelectItem>
                        <SelectItem value="Katolik">Katolik</SelectItem>
                        <SelectItem value="Hindu">Hindu</SelectItem>
                        <SelectItem value="Buddha">Buddha</SelectItem>
                        <SelectItem value="Konghucu">Konghucu</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div>
                  <Label htmlFor="occupation">Pekerjaan *</Label>
                  <Select value={formData.occupation} onValueChange={(value) => handleInputChange('occupation', value)}>
                    <SelectTrigger>
                      <SelectValue placeholder="Pilih pekerjaan" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="Pegawai Negeri Sipil">Pegawai Negeri Sipil</SelectItem>
                      <SelectItem value="TNI/Polri">TNI/Polri</SelectItem>
                      <SelectItem value="Swasta">Swasta</SelectItem>
                      <SelectItem value="Wiraswasta">Wiraswasta</SelectItem>
                      <SelectItem value="Petani">Petani</SelectItem>
                      <SelectItem value="Nelayan">Nelayan</SelectItem>
                      <SelectItem value="Buruh">Buruh</SelectItem>
                      <SelectItem value="Pedagang">Pedagang</SelectItem>
                      <SelectItem value="Guru">Guru</SelectItem>
                      <SelectItem value="Dokter">Dokter</SelectItem>
                      <SelectItem value="Perawat">Perawat</SelectItem>
                      <SelectItem value="Pengacara">Pengacara</SelectItem>
                      <SelectItem value="Arsitek">Arsitek</SelectItem>
                      <SelectItem value="Insinyur">Insinyur</SelectItem>
                      <SelectItem value="Akuntan">Akuntan</SelectItem>
                      <SelectItem value="Programmer">Programmer</SelectItem>
                      <SelectItem value="Desainer">Desainer</SelectItem>
                      <SelectItem value="Jurnalis">Jurnalis</SelectItem>
                      <SelectItem value="Seniman">Seniman</SelectItem>
                      <SelectItem value="Atlet">Atlet</SelectItem>
                      <SelectItem value="Pelajar/Mahasiswa">Pelajar/Mahasiswa</SelectItem>
                      <SelectItem value="Ibu Rumah Tangga">Ibu Rumah Tangga</SelectItem>
                      <SelectItem value="Pensiunan">Pensiunan</SelectItem>
                      <SelectItem value="Tidak Bekerja">Tidak Bekerja</SelectItem>
                      <SelectItem value="Lainnya">Lainnya</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </CardContent>
            </Card>
          )}

          {/* Step 2: Address */}
          {currentStep === 2 && (
            <Card>
              <CardHeader>
                <CardTitle>Alamat Pelapor</CardTitle>
                <CardDescription>
                  Lengkapi data alamat tempat tinggal Anda
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <Label htmlFor="address">Alamat Lengkap *</Label>
                  <Textarea
                    id="address"
                    value={formData.address}
                    onChange={(e) => handleInputChange('address', e.target.value)}
                    placeholder="Masukkan alamat lengkap"
                    rows={3}
                    required
                  />
                </div>

                <div className="grid md:grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="village">Desa/Kelurahan *</Label>
                    <Input
                      id="village"
                      value={formData.village}
                      onChange={(e) => handleInputChange('village', e.target.value)}
                      placeholder="Masukkan desa/kelurahan"
                      required
                    />
                  </div>
                  <div>
                    <Label htmlFor="district">Kecamatan *</Label>
                    <Input
                      id="district"
                      value={formData.district}
                      onChange={(e) => handleInputChange('district', e.target.value)}
                      placeholder="Masukkan kecamatan"
                      required
                    />
                  </div>
                </div>

                <div className="grid md:grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="regency">Kabupaten/Kota *</Label>
                    <Input
                      id="regency"
                      value={formData.regency}
                      onChange={(e) => handleInputChange('regency', e.target.value)}
                      placeholder="Masukkan kabupaten/kota"
                      required
                    />
                  </div>
                  <div>
                    <Label htmlFor="province">Provinsi *</Label>
                    <Input
                      id="province"
                      value={formData.province}
                      onChange={(e) => handleInputChange('province', e.target.value)}
                      placeholder="Masukkan provinsi"
                      required
                    />
                  </div>
                </div>
              </CardContent>
            </Card>
          )}

          {/* Step 3: Contact & Report Info */}
          {currentStep === 3 && (
            <Card>
              <CardHeader>
                <CardTitle>Kontak & Informasi Laporan</CardTitle>
                <CardDescription>
                  Lengkapi informasi kontak dan detail laporan
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid md:grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="phone">Nomor Telepon *</Label>
                    <Input
                      id="phone"
                      type="tel"
                      value={formData.phone}
                      onChange={(e) => handleInputChange('phone', e.target.value)}
                      placeholder="Masukkan nomor telepon"
                      required
                    />
                  </div>
                  <div>
                    <Label htmlFor="email">Email *</Label>
                    <Input
                      id="email"
                      type="email"
                      value={formData.email}
                      onChange={(e) => handleInputChange('email', e.target.value)}
                      placeholder="Masukkan email"
                      required
                    />
                  </div>
                </div>

                <div>
                  <Label htmlFor="identityNumber">Nomor Identitas (KTP/SIM/Paspor) *</Label>
                  <Input
                    id="identityNumber"
                    value={formData.identityNumber}
                    onChange={(e) => handleInputChange('identityNumber', e.target.value)}
                    placeholder="Masukkan nomor identitas"
                    required
                  />
                </div>

                <div>
                  <Label htmlFor="reportType">Jenis Laporan *</Label>
                  <Select value={formData.reportType} onValueChange={(value) => handleInputChange('reportType', value)}>
                    <SelectTrigger>
                      <SelectValue placeholder="Pilih jenis laporan" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="kehilangan">Laporan Kehilangan</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="grid md:grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="incidentDate">Tanggal Kejadian *</Label>
                    <Input
                      id="incidentDate"
                      type="date"
                      value={formData.incidentDate}
                      onChange={(e) => handleInputChange('incidentDate', e.target.value)}
                      required
                    />
                  </div>
                  <div>
                    <Label htmlFor="incidentLocation">Lokasi Kejadian *</Label>
                    <Input
                      id="incidentLocation"
                      value={formData.incidentLocation}
                      onChange={(e) => handleInputChange('incidentLocation', e.target.value)}
                      placeholder="Masukkan lokasi kejadian"
                      required
                    />
                  </div>
                </div>
              </CardContent>
            </Card>
          )}

          {/* Step 4: Incident Details */}
          {currentStep === 4 && (
            <Card>
              <CardHeader>
                <CardTitle>Detail Kejadian</CardTitle>
                <CardDescription>
                  Lengkapi informasi barang yang hilang dan lokasi pengambilan surat
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <Label htmlFor="additionalInfo">Informasi Barang Apa Saja yang Hilang</Label>
                  <Textarea
                    id="additionalInfo"
                    value={formData.additionalInfo}
                    onChange={(e) => handleInputChange('additionalInfo', e.target.value)}
                    placeholder="Jelaskan barang apa saja yang hilang (jenis, merek, nomor seri, ciri-ciri, dll)"
                    rows={3}
                    required
                  />
                </div>

                <div className="p-4 bg-amber-50 rounded-lg border border-amber-200">
                  <Label htmlFor="pickupLocation" className="text-base font-semibold text-amber-800">Lokasi Pengambilan Surat *</Label>
                  {isLoadingLocations ? (
                    <div className="flex items-center justify-center py-6 text-sm text-amber-600">
                      <Loader2 className="w-5 h-5 animate-spin mr-2" />
                      <span>Memuat data lokasi...</span>
                    </div>
                  ) : (
                    <Select value={formData.pickupLocation} onValueChange={(value) => handleInputChange('pickupLocation', value)}>
                      <SelectTrigger className="mt-2 bg-white border-amber-300 focus:border-amber-500 focus:ring-amber-200">
                        <SelectValue placeholder="Pilih lokasi pengambilan surat" />
                      </SelectTrigger>
                      <SelectContent>
                        {pickupLocations.map((location) => (
                          <SelectItem key={location.id} value={location.id} className="py-3 px-4">
                            <div className="flex flex-col">
                              <span className="font-medium text-amber-900">{location.name}</span>
                              <span className="text-xs text-gray-600 mt-1 leading-relaxed">{location.address}</span>
                            </div>
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  )}
                  {formData.pickupLocation && (
                    <div className="mt-3 p-2 bg-white rounded border border-amber-200">
                      <p className="text-xs text-amber-700 font-medium">
                        ✓ Lokasi pengambilan telah dipilih
                      </p>
                    </div>
                  )}
                </div>

                <div className="flex items-start space-x-2 p-4 bg-gray-50 rounded-lg">
                  <Checkbox
                    id="agreeToTerms"
                    checked={formData.agreeToTerms}
                    onCheckedChange={(checked) => handleInputChange('agreeToTerms', checked as boolean)}
                  />
                  <Label htmlFor="agreeToTerms" className="text-sm text-gray-700 leading-relaxed">
                    Saya menyatakan bahwa informasi yang saya berikan adalah benar dan dapat dipertanggungjawabkan. 
                    Saya memahami bahwa memberikan keterangan palsu dapat dikenakan sanksi sesuai dengan peraturan perundang-undangan yang berlaku.
                  </Label>
                </div>
              </CardContent>
            </Card>
          )}

          {/* Navigation Buttons */}
          <div className="flex flex-col sm:flex-row justify-between gap-3 sm:gap-0 items-center pt-6">
            <div className="w-full sm:w-auto order-2 sm:order-1">
              {currentStep > 1 && (
                <Button
                  type="button"
                  onClick={prevStep}
                  variant="outline"
                  className="w-full sm:w-auto"
                >
                  Sebelumnya
                </Button>
              )}
            </div>
            
            <div className="w-full sm:w-auto order-1 sm:order-2">
              {currentStep < 4 ? (
                <Button
                  type="button"
                  onClick={nextStep}
                  disabled={!validateStep(currentStep)}
                  className="bg-amber-600 hover:bg-amber-700 w-full sm:w-auto"
                >
                  Selanjutnya
                </Button>
              ) : (
                <Button
                  type="submit"
                  disabled={!validateStep(4) || isSubmitting}
                  className="bg-amber-600 hover:bg-amber-700 w-full sm:w-auto"
                >
                  {isSubmitting ? (
                    <>
                      <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                      Mengajukan...
                    </>
                  ) : (
                    'Ajukan Laporan'
                  )}
                </Button>
              )}
            </div>
          </div>
        </form>
      </div>
    </div>
  )
}