'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 { ArrowLeft, Car, Upload, Loader2, CheckCircle } from 'lucide-react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { UserSidebar } from '@/components/user-sidebar'

interface FormData {
  nama: string
  tempatLahir: string
  tanggalLahir: string
  nik: string
  alamat: string
  pekerjaan: string
  noSim: string
  noStnk: string
  jenisKendaraan: string
  noPolisi: string
  keperluan: string
}

export default function LaluLintasForm() {
  const router = useRouter()
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [isSubmitted, setIsSubmitted] = useState(false)
  const [trackingNumber, setTrackingNumber] = useState('')
  const [formData, setFormData] = useState<FormData>({
    nama: '',
    tempatLahir: '',
    tanggalLahir: '',
    nik: '',
    alamat: '',
    pekerjaan: '',
    noSim: '',
    noStnk: '',
    jenisKendaraan: '',
    noPolisi: '',
    keperluan: ''
  })

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    setIsSubmitting(true)

    try {
      const response = await fetch('/api/service-requests', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          serviceSlug: 'lalu-lintas',
          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 (
      <UserSidebar>
        <div className="max-w-2xl mx-auto">
          <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 layanan lalu lintas Anda telah berhasil diajukan
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="p-4 bg-blue-50 rounded-lg">
                <p className="text-sm text-gray-600 mb-1">Nomor Pelacakan:</p>
                <p className="text-xl font-mono font-bold text-blue-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>
      </UserSidebar>
    )
  }

  return (
    <UserSidebar>
      {/* Header */}
      <div className="bg-blue-600 text-white -mx-4 -mt-4 px-4 py-8 rounded-b-lg">
        <div className="max-w-4xl mx-auto">
          <div className="flex items-center gap-4 mb-4">
            <Link href="/" className="text-white hover:bg-blue-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 Layanan Lalu Lintas</h1>
            <p className="opacity-90">SIM, STNK, dan layanan lalu lintas lainnya</p>
          </div>
        </div>
      </div>

      {/* Form */}
      <div className="max-w-4xl mx-auto">
        <form onSubmit={handleSubmit} className="space-y-6">
          <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="nama">Nama Lengkap *</Label>
                  <Input
                    id="nama"
                    value={formData.nama}
                    onChange={(e) => handleInputChange('nama', e.target.value)}
                    placeholder="Masukkan nama lengkap"
                    required
                  />
                </div>
                <div>
                  <Label htmlFor="tempatLahir">Tempat Lahir *</Label>
                  <Input
                    id="tempatLahir"
                    value={formData.tempatLahir}
                    onChange={(e) => handleInputChange('tempatLahir', e.target.value)}
                    placeholder="Masukkan tempat lahir"
                    required
                  />
                </div>
              </div>
              
              <div className="grid md:grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="tanggalLahir">Tanggal Lahir *</Label>
                  <Input
                    id="tanggalLahir"
                    type="date"
                    value={formData.tanggalLahir}
                    onChange={(e) => handleInputChange('tanggalLahir', e.target.value)}
                    required
                  />
                </div>
                <div>
                  <Label htmlFor="nik">NIK *</Label>
                  <Input
                    id="nik"
                    value={formData.nik}
                    onChange={(e) => handleInputChange('nik', e.target.value)}
                    placeholder="Masukkan NIK"
                    required
                  />
                </div>
              </div>

              <div>
                <Label htmlFor="alamat">Alamat Lengkap *</Label>
                <Textarea
                  id="alamat"
                  value={formData.alamat}
                  onChange={(e) => handleInputChange('alamat', e.target.value)}
                  placeholder="Masukkan alamat lengkap"
                  rows={3}
                  required
                />
              </div>

              <div>
                <Label htmlFor="pekerjaan">Pekerjaan *</Label>
                <Input
                  id="pekerjaan"
                  value={formData.pekerjaan}
                  onChange={(e) => handleInputChange('pekerjaan', e.target.value)}
                  placeholder="Masukkan pekerjaan"
                  required
                />
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Data Kendaraan</CardTitle>
              <CardDescription>
                Lengkapi data kendaraan terkait
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid md:grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="noSim">Nomor SIM</Label>
                  <Input
                    id="noSim"
                    value={formData.noSim}
                    onChange={(e) => handleInputChange('noSim', e.target.value)}
                    placeholder="Masukkan nomor SIM"
                  />
                </div>
                <div>
                  <Label htmlFor="noStnk">Nomor STNK</Label>
                  <Input
                    id="noStnk"
                    value={formData.noStnk}
                    onChange={(e) => handleInputChange('noStnk', e.target.value)}
                    placeholder="Masukkan nomor STNK"
                  />
                </div>
              </div>

              <div className="grid md:grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="jenisKendaraan">Jenis Kendaraan *</Label>
                  <Select value={formData.jenisKendaraan} onValueChange={(value) => handleInputChange('jenisKendaraan', value)}>
                    <SelectTrigger>
                      <SelectValue placeholder="Pilih jenis kendaraan" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="Motor">Motor</SelectItem>
                      <SelectItem value="Mobil">Mobil</SelectItem>
                      <SelectItem value="Truk">Truk</SelectItem>
                      <SelectItem value="Bus">Bus</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label htmlFor="noPolisi">Nomor Polisi</Label>
                  <Input
                    id="noPolisi"
                    value={formData.noPolisi}
                    onChange={(e) => handleInputChange('noPolisi', e.target.value)}
                    placeholder="Masukkan nomor polisi"
                  />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Keperluan</CardTitle>
              <CardDescription>
                Jelaskan keperluan pengajuan layanan
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div>
                <Label htmlFor="keperluan">Keperluan *</Label>
                <Textarea
                  id="keperluan"
                  value={formData.keperluan}
                  onChange={(e) => handleInputChange('keperluan', e.target.value)}
                  placeholder="Jelaskan keperluan pengajuan layanan lalu lintas"
                  rows={4}
                  required
                />
              </div>
            </CardContent>
          </Card>

          <div className="flex justify-end space-x-4">
            <Link href="/">
              <Button type="button" variant="outline">
                Batal
              </Button>
            </Link>
            <Button
              type="submit"
              disabled={isSubmitting}
              className="bg-blue-600 hover:bg-blue-700"
            >
              {isSubmitting ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  Mengajukan...
                </>
              ) : (
                'Ajukan Permohonan'
              )}
            </Button>
          </div>
        </form>
      </div>
    </UserSidebar>
  )
}