'use client'

import { useState } 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, FileText, 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
  education: string
  address: string
  village: string
  district: string
  regency: string
  province: string
  phone: string
  email: string
  identityNumber: string
  passportNumber: string
  purpose: string
  companyAddress: string
  specialNotes: string
  agreeToTerms: boolean
}

export default function SKCKForm() {
  const router = useRouter()
  const [currentStep, setCurrentStep] = useState(1)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [isSubmitted, setIsSubmitted] = useState(false)
  const [trackingNumber, setTrackingNumber] = useState('')
  const [formData, setFormData] = useState<FormData>({
    fullName: '',
    placeOfBirth: '',
    dateOfBirth: '',
    gender: '',
    nationality: 'Indonesia',
    religion: '',
    occupation: '',
    education: '',
    address: '',
    village: '',
    district: '',
    regency: '',
    province: '',
    phone: '',
    email: '',
    identityNumber: '',
    passportNumber: '',
    purpose: '',
    companyAddress: '',
    specialNotes: '',
    agreeToTerms: false
  })

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

  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.education && formData.address && 
                 formData.village && formData.district && formData.regency && formData.province)
      case 3:
        return !!(formData.phone && formData.email && formData.identityNumber && formData.purpose)
      case 4:
        return 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: 'skck',
          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>
                Permohonan SKCK Anda 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 pengajuan 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 SKCK</h1>
            <p className="opacity-90">Surat Keterangan Catatan Kriminal</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 && 'Kontak & Keperluan'}
                  {step === 4 && 'Konfirmasi'}
                </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">
        <form onSubmit={handleSubmit} className="space-y-6">
            {/* Step 1: Personal Data */}
            {currentStep === 1 && (
              <Card>
                <CardHeader>
                  <CardTitle>Data Diri</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 className="grid md:grid-cols-2 gap-4">
                    <div>
                      <Label htmlFor="occupation">Pekerjaan *</Label>
                      <Input
                        id="occupation"
                        value={formData.occupation}
                        onChange={(e) => handleInputChange('occupation', e.target.value)}
                        placeholder="Masukkan pekerjaan"
                        required
                      />
                    </div>
                    <div>
                      <Label htmlFor="education">Pendidikan *</Label>
                      <Select value={formData.education} onValueChange={(value) => handleInputChange('education', value)}>
                        <SelectTrigger>
                          <SelectValue placeholder="Pilih pendidikan" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="SD">SD</SelectItem>
                          <SelectItem value="SMP">SMP</SelectItem>
                          <SelectItem value="SMA">SMA</SelectItem>
                          <SelectItem value="D1">D1</SelectItem>
                          <SelectItem value="D2">D2</SelectItem>
                          <SelectItem value="D3">D3</SelectItem>
                          <SelectItem value="S1">S1</SelectItem>
                          <SelectItem value="S2">S2</SelectItem>
                          <SelectItem value="S3">S3</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </CardContent>
              </Card>
            )}

            {/* Step 2: Address */}
            {currentStep === 2 && (
              <Card>
                <CardHeader>
                  <CardTitle>Alamat</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 & Purpose */}
            {currentStep === 3 && (
              <Card>
                <CardHeader>
                  <CardTitle>Kontak & Keperluan</CardTitle>
                  <CardDescription>
                    Lengkapi informasi kontak dan tujuan pengajuan
                  </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 className="grid md:grid-cols-2 gap-4">
                    <div>
                      <Label htmlFor="identityNumber">Nomor KTP *</Label>
                      <Input
                        id="identityNumber"
                        value={formData.identityNumber}
                        onChange={(e) => handleInputChange('identityNumber', e.target.value)}
                        placeholder="Masukkan nomor KTP"
                        required
                      />
                    </div>
                    <div>
                      <Label htmlFor="passportNumber">Nomor Paspor</Label>
                      <Input
                        id="passportNumber"
                        value={formData.passportNumber}
                        onChange={(e) => handleInputChange('passportNumber', e.target.value)}
                        placeholder="Masukkan nomor paspor (jika ada)"
                      />
                    </div>
                  </div>

                  <div>
                    <Label htmlFor="purpose">Keperluan SKCK *</Label>
                    <Select value={formData.purpose} onValueChange={(value) => handleInputChange('purpose', value)}>
                      <SelectTrigger>
                        <SelectValue placeholder="Pilih keperluan" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="melamar-kerja">Melamar Pekerjaan</SelectItem>
                        <SelectItem value="pendidikan">Pendidikan</SelectItem>
                        <SelectItem value="visa">Visa</SelectItem>
                        <SelectItem value="keperluan-lain">Keperluan Lain</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div>
                    <Label htmlFor="companyAddress">Alamat Instansi/Perusahaan</Label>
                    <Textarea
                      id="companyAddress"
                      value={formData.companyAddress}
                      onChange={(e) => handleInputChange('companyAddress', e.target.value)}
                      placeholder="Masukkan alamat instansi/perusahaan (jika ada)"
                      rows={2}
                    />
                  </div>

                  <div>
                    <Label htmlFor="specialNotes">Catatan Tambahan</Label>
                    <Textarea
                      id="specialNotes"
                      value={formData.specialNotes}
                      onChange={(e) => handleInputChange('specialNotes', e.target.value)}
                      placeholder="Masukkan catatan tambahan (jika ada)"
                      rows={2}
                    />
                  </div>
                </CardContent>
              </Card>
            )}

            {/* Step 4: Confirmation */}
            {currentStep === 4 && (
              <Card>
                <CardHeader>
                  <CardTitle>Konfirmasi Pengajuan</CardTitle>
                  <CardDescription>
                    Periksa kembali data yang Anda masukkan
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-6">
                  <div className="grid md:grid-cols-2 gap-6">
                    <div>
                      <h4 className="font-semibold mb-3">Data Diri</h4>
                      <div className="space-y-2 text-sm">
                        <div className="flex justify-between">
                          <span className="text-gray-600">Nama:</span>
                          <span>{formData.fullName}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-gray-600">Tempat/Tanggal Lahir:</span>
                          <span>{formData.placeOfBirth}, {formData.dateOfBirth}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-gray-600">Jenis Kelamin:</span>
                          <span>{formData.gender === 'L' ? 'Laki-laki' : 'Perempuan'}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-gray-600">Agama:</span>
                          <span>{formData.religion}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-gray-600">Pekerjaan:</span>
                          <span>{formData.occupation}</span>
                        </div>
                      </div>
                    </div>

                    <div>
                      <h4 className="font-semibold mb-3">Kontak</h4>
                      <div className="space-y-2 text-sm">
                        <div className="flex justify-between">
                          <span className="text-gray-600">Telepon:</span>
                          <span>{formData.phone}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-gray-600">Email:</span>
                          <span>{formData.email}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-gray-600">Nomor KTP:</span>
                          <span>{formData.identityNumber}</span>
                        </div>
                        <div className="flex justify-between">
                          <span className="text-gray-600">Keperluan:</span>
                          <span>{formData.purpose}</span>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div>
                    <h4 className="font-semibold mb-3">Alamat</h4>
                    <div className="text-sm text-gray-600">
                      {formData.address}, {formData.village}, {formData.district}, {formData.regency}, {formData.province}
                    </div>
                  </div>

                  <div className="border-t pt-4">
                    <div className="flex items-start gap-3">
                      <Checkbox
                        id="agreeToTerms"
                        checked={formData.agreeToTerms}
                        onCheckedChange={(checked) => handleInputChange('agreeToTerms', checked as boolean)}
                      />
                      <div className="text-sm">
                        <Label htmlFor="agreeToTerms" className="font-normal">
                          Saya menyatakan bahwa data yang saya masukkan adalah benar dan dapat dipertanggungjawabkan. 
                          Saya memahami bahwa memberikan informasi palsu dapat dikenakan sanksi sesuai dengan peraturan perundang-undangan yang berlaku.
                        </Label>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            )}

            {/* Navigation Buttons */}
            <div className="flex flex-col sm:flex-row justify-between gap-3 sm:gap-0">
              <Button
                type="button"
                variant="outline"
                onClick={prevStep}
                disabled={currentStep === 1}
                className="w-full sm:w-auto order-2 sm:order-1"
              >
                Sebelumnya
              </Button>

              {currentStep < 4 ? (
                <Button
                  type="button"
                  onClick={nextStep}
                  disabled={!validateStep(currentStep)}
                  className="bg-amber-600 hover:bg-amber-700 w-full sm:w-auto order-1 sm:order-2"
                >
                  Selanjutnya
                </Button>
              ) : (
                <Button
                  type="submit"
                  disabled={!validateStep(4) || isSubmitting}
                  className="bg-amber-600 hover:bg-amber-700 w-full sm:w-auto order-1 sm:order-2"
                >
                  {isSubmitting ? (
                    <>
                      <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                      Mengajukan...
                    </>
                  ) : (
                    'Ajukan Permohonan'
                  )}
                </Button>
              )}
            </div>
          </form>
        </div>
      </div>
    )
  }
