'use client'
import { useState, useEffect } from 'react'
import { formatRupiah } from '@/lib/utils'
import styles from './ServiceForm.module.css'

interface ServiceFormData {
  name: string
  slug: string
  category: string
  description: string
  longDescription: string
  imageUrl: string
  thumbnailUrl: string
  duration: string
  price: string
  dpAmount: string
  isActive: boolean
  isFeatured: boolean
  sortOrder: string
  benefits: string[]
  inclusions: string[]
  contraindications: string[]
}

interface ServiceFormProps {
  service?: ServiceFormData & { id: string } | null
  isOpen: boolean
  onClose: () => void
  onSuccess: () => void
}

const CATEGORY_OPTIONS = [
  { value: 'SPA_PACKAGE', label: 'SPA Package' },
  { value: 'BODY_FACE_TREATMENT', label: 'Body & Face Treatment' },
  { value: 'HAIR_TREATMENT', label: 'Hair Treatment' },
  { value: 'MOM_BABY_TREATMENT', label: 'Mom & Baby' },
  { value: 'WEDDING_PACKAGE', label: 'Wedding Package' },
  { value: 'ADD_ON', label: 'Add-On' },
]

const initialForm: ServiceFormData = {
  name: '',
  slug: '',
  category: 'SPA_PACKAGE',
  description: '',
  longDescription: '',
  imageUrl: '',
  thumbnailUrl: '',
  duration: '60',
  price: '',
  dpAmount: '',
  isActive: true,
  isFeatured: false,
  sortOrder: '0',
  benefits: [],
  inclusions: [],
  contraindications: [],
}

export default function ServiceForm({ service, isOpen, onClose, onSuccess }: ServiceFormProps) {
  const [form, setForm] = useState<ServiceFormData>(initialForm)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [newBenefit, setNewBenefit] = useState('')
  const [newInclusion, setNewInclusion] = useState('')
  const [newContraindication, setNewContraindication] = useState('')

  useEffect(() => {
    if (service) {
      setForm({
        name: service.name || '',
        slug: service.slug || '',
        category: service.category || 'SPA_PACKAGE',
        description: service.description || '',
        longDescription: service.longDescription || '',
        imageUrl: service.imageUrl || '',
        thumbnailUrl: service.thumbnailUrl || '',
        duration: String(service.duration || '60'),
        price: String(service.price || ''),
        dpAmount: service.dpAmount ? String(service.dpAmount) : '',
        isActive: service.isActive ?? true,
        isFeatured: service.isFeatured ?? false,
        sortOrder: String(service.sortOrder || '0'),
        benefits: Array.isArray(service.benefits) ? service.benefits : JSON.parse(service.benefits || '[]'),
        inclusions: Array.isArray(service.inclusions) ? service.inclusions : JSON.parse(service.inclusions || '[]'),
        contraindications: Array.isArray(service.contraindications) ? service.contraindications : JSON.parse(service.contraindications || '[]'),
      })
    } else {
      setForm(initialForm)
    }
    setError(null)
  }, [service, isOpen])

  function handleChange(field: keyof ServiceFormData, value: string | boolean) {
    setForm(prev => ({ ...prev, [field]: value }))
  }

  function addBenefit() {
    if (newBenefit.trim()) {
      setForm(prev => ({ ...prev, benefits: [...prev.benefits, newBenefit.trim()] }))
      setNewBenefit('')
    }
  }

  function removeBenefit(index: number) {
    setForm(prev => ({ ...prev, benefits: prev.benefits.filter((_, i) => i !== index) }))
  }

  function addInclusion() {
    if (newInclusion.trim()) {
      setForm(prev => ({ ...prev, inclusions: [...prev.inclusions, newInclusion.trim()] }))
      setNewInclusion('')
    }
  }

  function removeInclusion(index: number) {
    setForm(prev => ({ ...prev, inclusions: prev.inclusions.filter((_, i) => i !== index) }))
  }

  function addContraindication() {
    if (newContraindication.trim()) {
      setForm(prev => ({ ...prev, contraindications: [...prev.contraindications, newContraindication.trim()] }))
      setNewContraindication('')
    }
  }

  function removeContraindication(index: number) {
    setForm(prev => ({ ...prev, contraindications: prev.contraindications.filter((_, i) => i !== index) }))
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setError(null)

    // Validation
    if (!form.name.trim() || form.name.trim().length < 3) {
      setError('Nama layanan minimal 3 karakter')
      return
    }
    if (!form.description.trim() || form.description.trim().length < 10) {
      setError('Deskripsi minimal 10 karakter')
      return
    }
    if (!form.price || parseFloat(form.price) <= 0) {
      setError('Harga harus lebih dari 0')
      return
    }
    const durationNum = parseInt(form.duration)
    if (!durationNum || durationNum < 30 || durationNum > 480) {
      setError('Durasi harus antara 30-480 menit')
      return
    }

    setSaving(true)
    try {
      const url = service ? `/api/admin/services/${service.id}` : '/api/admin/services'
      const method = service ? 'PATCH' : 'POST'

      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.name.trim(),
          slug: form.slug.trim() || undefined,
          category: form.category,
          description: form.description.trim(),
          longDescription: form.longDescription.trim() || undefined,
          imageUrl: form.imageUrl.trim() || undefined,
          thumbnailUrl: form.thumbnailUrl.trim() || undefined,
          duration: parseInt(form.duration),
          price: parseFloat(form.price),
          dpAmount: form.dpAmount ? parseFloat(form.dpAmount) : null,
          isActive: form.isActive,
          isFeatured: form.isFeatured,
          sortOrder: parseInt(form.sortOrder) || 0,
          benefits: form.benefits,
          inclusions: form.inclusions,
          contraindications: form.contraindications,
        }),
      })

      if (!res.ok) {
        const data = await res.json()
        throw new Error(data.error || 'Gagal menyimpan layanan')
      }

      onSuccess()
      onClose()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Terjadi kesalahan')
    } finally {
      setSaving(false)
    }
  }

  if (!isOpen) return null

  return (
    <div className={styles.overlay} onClick={(e) => e.target === e.currentTarget && onClose()}>
      <div className={styles.modal}>
        <div className={styles.header}>
          <h2 className={styles.title}>{service ? 'Edit Layanan' : 'Tambah Layanan Baru'}</h2>
          <button className={styles.closeBtn} onClick={onClose} type="button">✕</button>
        </div>

        <form onSubmit={handleSubmit}>
          <div className={styles.body}>
            {error && (
              <div className={styles.errorBanner}>
                <span>⚠️</span> {error}
              </div>
            )}

            <div className={styles.grid2col}>
              <div className={styles.field}>
                <label className="input-label" htmlFor="svc-name">Nama Layanan *</label>
                <input
                  id="svc-name"
                  className="input"
                  type="text"
                  value={form.name}
                  onChange={(e) => handleChange('name', e.target.value)}
                  placeholder="Contoh: Signature Massage"
                  maxLength={100}
                  required
                />
              </div>

              <div className={styles.field}>
                <label className="input-label" htmlFor="svc-category">Kategori</label>
                <select
                  id="svc-category"
                  className="input"
                  value={form.category}
                  onChange={(e) => handleChange('category', e.target.value)}
                >
                  {CATEGORY_OPTIONS.map(opt => (
                    <option key={opt.value} value={opt.value}>{opt.label}</option>
                  ))}
                </select>
              </div>

              <div className={styles.field}>
                <label className="input-label" htmlFor="svc-slug">Slug (URL)</label>
                <input
                  id="svc-slug"
                  className="input"
                  type="text"
                  value={form.slug}
                  onChange={(e) => handleChange('slug', e.target.value)}
                  placeholder="auto-generate jika kosong"
                />
                <span className="input-helper">Slug untuk URL, kosongkan untuk auto-generate</span>
              </div>

              <div className={styles.field}>
                <label className="input-label" htmlFor="svc-sort">Urutan Tampilan</label>
                <input
                  id="svc-sort"
                  className="input"
                  type="number"
                  value={form.sortOrder}
                  onChange={(e) => handleChange('sortOrder', e.target.value)}
                  min="0"
                  placeholder="0"
                />
              </div>

              <div className={styles.field}>
                <label className="input-label" htmlFor="svc-duration">Durasi (menit) *</label>
                <input
                  id="svc-duration"
                  className="input"
                  type="number"
                  value={form.duration}
                  onChange={(e) => handleChange('duration', e.target.value)}
                  min="30"
                  max="480"
                  required
                />
              </div>

              <div className={styles.field}>
                <label className="input-label" htmlFor="svc-price">Harga (Rp) *</label>
                <input
                  id="svc-price"
                  className="input"
                  type="number"
                  value={form.price}
                  onChange={(e) => handleChange('price', e.target.value)}
                  min="0"
                  placeholder="350000"
                  required
                />
                {form.price && parseFloat(form.price) > 0 && (
                  <span className="input-helper">{formatRupiah(parseFloat(form.price))}</span>
                )}
              </div>

              <div className={styles.field}>
                <label className="input-label" htmlFor="svc-dp">DP Amount (Rp)</label>
                <input
                  id="svc-dp"
                  className="input"
                  type="number"
                  value={form.dpAmount}
                  onChange={(e) => handleChange('dpAmount', e.target.value)}
                  min="0"
                  placeholder="Opsional"
                />
                <span className="input-helper">Jumlah minimum DP, kosongkan jika tidak ada</span>
              </div>

              <div className={styles.field}>
                <label className="input-label" htmlFor="svc-image">URL Gambar</label>
                <input
                  id="svc-image"
                  className="input"
                  type="url"
                  value={form.imageUrl}
                  onChange={(e) => handleChange('imageUrl', e.target.value)}
                  placeholder="https://..."
                />
              </div>
            </div>

            <div className={styles.field}>
              <label className="input-label" htmlFor="svc-desc">Deskripsi *</label>
              <textarea
                id="svc-desc"
                className={`input ${styles.textarea}`}
                value={form.description}
                onChange={(e) => handleChange('description', e.target.value)}
                placeholder="Deskripsi singkat layanan (minimal 10 karakter)"
                rows={3}
                required
              />
            </div>

            <div className={styles.field}>
              <label className="input-label" htmlFor="svc-long-desc">Deskripsi Lengkap</label>
              <textarea
                id="svc-long-desc"
                className={`input ${styles.textarea}`}
                value={form.longDescription}
                onChange={(e) => handleChange('longDescription', e.target.value)}
                placeholder="Deskripsi lengkap untuk halaman detail layanan (opsional)"
                rows={4}
              />
            </div>

            {/* Benefits */}
            <div className={styles.field}>
              <label className="input-label">Benefit / Keunggulan</label>
              <div className={styles.tagInput}>
                <input
                  className="input"
                  type="text"
                  value={newBenefit}
                  onChange={(e) => setNewBenefit(e.target.value)}
                  placeholder="Tambah benefit..."
                  onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), addBenefit())}
                />
                <button type="button" className="btn btn-sm btn-ghost" onClick={addBenefit}>+ Tambah</button>
              </div>
              <div className={styles.tagList}>
                {form.benefits.map((b, i) => (
                  <span key={i} className={styles.tag}>
                    {b}
                    <button type="button" onClick={() => removeBenefit(i)}>×</button>
                  </span>
                ))}
              </div>
            </div>

            {/* Inclusions */}
            <div className={styles.field}>
              <label className="input-label">Yang Termasuk</label>
              <div className={styles.tagInput}>
                <input
                  className="input"
                  type="text"
                  value={newInclusion}
                  onChange={(e) => setNewInclusion(e.target.value)}
                  placeholder="Tambah inclusion..."
                  onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), addInclusion())}
                />
                <button type="button" className="btn btn-sm btn-ghost" onClick={addInclusion}>+ Tambah</button>
              </div>
              <div className={styles.tagList}>
                {form.inclusions.map((item, i) => (
                  <span key={i} className={styles.tag}>
                    {item}
                    <button type="button" onClick={() => removeInclusion(i)}>×</button>
                  </span>
                ))}
              </div>
            </div>

            {/* Contraindications */}
            <div className={styles.field}>
              <label className="input-label">Kontraindikasi / Perhatian</label>
              <div className={styles.tagInput}>
                <input
                  className="input"
                  type="text"
                  value={newContraindication}
                  onChange={(e) => setNewContraindication(e.target.value)}
                  placeholder="Tambah perhatian khusus..."
                  onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), addContraindication())}
                />
                <button type="button" className="btn btn-sm btn-ghost" onClick={addContraindication}>+ Tambah</button>
              </div>
              <div className={styles.tagList}>
                {form.contraindications.map((item, i) => (
                  <span key={i} className={styles.tag}>
                    {item}
                    <button type="button" onClick={() => removeContraindication(i)}>×</button>
                  </span>
                ))}
              </div>
            </div>

            {/* Toggles */}
            <div className={styles.toggleRow}>
              <label className={styles.toggle}>
                <input
                  type="checkbox"
                  checked={form.isActive}
                  onChange={(e) => handleChange('isActive', e.target.checked)}
                />
                <span className={styles.toggleSlider}></span>
                <span className={styles.toggleLabel}>Layanan Aktif</span>
              </label>

              <label className={styles.toggle}>
                <input
                  type="checkbox"
                  checked={form.isFeatured}
                  onChange={(e) => handleChange('isFeatured', e.target.checked)}
                />
                <span className={styles.toggleSlider}></span>
                <span className={styles.toggleLabel}>Tampilkan di Featured</span>
              </label>
            </div>
          </div>

          <div className={styles.footer}>
            <button type="button" className="btn btn-ghost" onClick={onClose} disabled={saving}>
              Batal
            </button>
            <button type="submit" className="btn btn-primary" disabled={saving}>
              {saving ? 'Menyimpan...' : (service ? 'Simpan Perubahan' : 'Tambah Layanan')}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}