import { useState } from 'react'
import { apiFetch, ApiError } from '../../lib/auth'
import { Button } from '../ui/button'
import { Dialog, DialogFooter } from '../ui/dialog'
import { Input } from '../ui/input'
import { useToast } from '../ui/toast'

interface CreateCourseModalProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  onCreated: (courseId: string, startNow: boolean) => Promise<void>
}

function today() {
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

function defaultStartTime() {
  const date = new Date()
  const roundedMinutes = Math.ceil((date.getMinutes() + 1) / 15) * 15
  date.setMinutes(roundedMinutes, 0, 0)
  return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

export function CreateCourseModal({ open, onOpenChange, onCreated }: CreateCourseModalProps) {
  const { error: showError } = useToast()
  const [title, setTitle] = useState('')
  const [description, setDescription] = useState('')
  const [date, setDate] = useState(today)
  const [startTime, setStartTime] = useState(defaultStartTime)
  const [duration, setDuration] = useState('60')
  const [allowAnonymous, setAllowAnonymous] = useState(false)
  const [startNow, setStartNow] = useState(false)
  const [loading, setLoading] = useState(false)
  const [errors, setErrors] = useState<{ title?: string; date?: string; startTime?: string; duration?: string }>({})

  const reset = () => {
    setTitle('')
    setDescription('')
    setDate(today())
    setStartTime(defaultStartTime())
    setDuration('60')
    setAllowAnonymous(false)
    setStartNow(false)
    setErrors({})
  }

  const handleCreate = async () => {
    const nextErrors: typeof errors = {}
    if (!title.trim()) nextErrors.title = 'Nama course wajib diisi.'
    if (!date) nextErrors.date = 'Pilih tanggal session.'
    if (!startTime) nextErrors.startTime = 'Pilih waktu mulai.'
    if (!duration || Number(duration) < 30 || Number(duration) > 120) nextErrors.duration = 'Durasi harus antara 30-120 menit.'
    setErrors(nextErrors)
    if (Object.keys(nextErrors).length > 0) return

    setLoading(true)
    try {
      const course = await apiFetch<{ id: string }>('/api/courses', {
        method: 'POST',
        body: JSON.stringify({
          title,
          description: description || null,
          date,
          start_time: `${startTime}:00`,
          duration_minutes: Number(duration),
          allow_anonymous: allowAnonymous,
        }),
      })
      await onCreated(course.id, startNow)
      onOpenChange(false)
      reset()
    } catch (cause) {
      showError('Course belum dibuat', cause instanceof ApiError ? cause.message : 'Terjadi kesalahan')
    } finally {
      setLoading(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange} title="Buat course baru" description="Siapkan course pertama Anda. Setelah dibuat, session live akan langsung dimulai." className="max-w-2xl">
      <div className="space-y-4">
        <div>
          <label className="mb-1 block text-sm font-medium text-body" htmlFor="course-title">Nama course</label>
          <Input id="course-title" autoFocus placeholder="Contoh: Matematika Kelas 10" value={title} onChange={(event) => { setTitle(event.target.value); setErrors((current) => ({ ...current, title: undefined })) }} maxLength={255} aria-invalid={Boolean(errors.title)} />
          {errors.title && <p className="mt-1 text-xs text-red">{errors.title}</p>}
        </div>
        <div>
          <label className="mb-1 block text-sm font-medium text-body" htmlFor="course-description">Deskripsi <span className="font-normal text-muted">(opsional)</span></label>
          <textarea id="course-description" className="min-h-20 w-full resize-y rounded-lg border border-line bg-paper px-3 py-2 text-sm text-ink placeholder:text-muted focus:border-clay focus:outline-none focus:ring-2 focus:ring-clay" placeholder="Topik yang akan dibahas" value={description} onChange={(event) => setDescription(event.target.value)} />
        </div>
        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className="mb-1 block text-sm font-medium text-body" htmlFor="course-date">Tanggal</label>
            <Input id="course-date" type="date" min={today()} value={date} onChange={(event) => { setDate(event.target.value); setErrors((current) => ({ ...current, date: undefined })) }} aria-invalid={Boolean(errors.date)} />
            {errors.date && <p className="mt-1 text-xs text-red">{errors.date}</p>}
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-body" htmlFor="course-time">Mulai</label>
            <Input id="course-time" type="time" value={startTime} onChange={(event) => { setStartTime(event.target.value); setErrors((current) => ({ ...current, startTime: undefined })) }} aria-invalid={Boolean(errors.startTime)} />
            {errors.startTime && <p className="mt-1 text-xs text-red">{errors.startTime}</p>}
          </div>
        </div>
        <div>
          <label className="mb-1 block text-sm font-medium text-body" htmlFor="course-duration">Durasi</label>
          <select id="course-duration" className="h-10 w-full rounded-lg border border-line bg-paper px-3 text-sm text-ink focus:outline-none focus:ring-2 focus:ring-clay" value={duration} onChange={(event) => { setDuration(event.target.value); setErrors((current) => ({ ...current, duration: undefined })) }} aria-invalid={Boolean(errors.duration)}>
            <option value="30">30 menit</option>
            <option value="45">45 menit</option>
            <option value="60">60 menit</option>
            <option value="90">90 menit</option>
            <option value="120">120 menit</option>
          </select>
          {errors.duration && <p className="mt-1 text-xs text-red">{errors.duration}</p>}
        </div>
        <label className="flex cursor-pointer items-start gap-3 rounded-lg border border-line bg-cream p-3">
          <input type="checkbox" checked={allowAnonymous} onChange={(event) => setAllowAnonymous(event.target.checked)} className="mt-0.5 h-4 w-4 accent-clay" />
          <span><strong className="block text-sm font-medium text-body">Izinkan peserta mengirim status tanpa nama</strong><small className="mt-1 block text-xs leading-5 text-body">Jika tidak, peserta akan diminta mengisi nama saat bergabung.</small></span>
        </label>
        <label className="flex cursor-pointer items-start gap-3 rounded-lg border border-sage-soft bg-sage-soft/60 p-3">
          <input type="checkbox" checked={startNow} onChange={(event) => setStartNow(event.target.checked)} className="mt-0.5 h-4 w-4 accent-clay" />
          <span><strong className="block text-sm font-medium text-body">Mulai session sekarang</strong><small className="mt-1 block text-xs leading-5 text-body">Aktifkan hanya jika kelas akan dimulai saat ini. Jika tidak, course akan tersimpan sebagai terjadwal.</small></span>
        </label>
        <div className="rounded-lg bg-cream px-3 py-2.5 text-sm text-body">
          <p className="text-xs font-semibold uppercase tracking-wide text-muted">Preview</p>
          <p className="mt-1 font-medium text-ink">{title.trim() || 'Nama course Anda'}</p>
          <p className="mt-1 text-xs text-body">{date || 'Pilih tanggal'} · {startTime || 'Pilih waktu'} · {duration} menit</p>
        </div>
      </div>
      <DialogFooter>
        <Button variant="outline" onClick={() => onOpenChange(false)}>Batal</Button>
        <Button onClick={handleCreate} loading={loading} disabled={!title.trim()}>{startNow ? 'Buat & mulai session' : 'Buat course'}</Button>
      </DialogFooter>
    </Dialog>
  )
}
