'use client'

import { useEffect, useState } from 'react'
import { Edit, Plus, Trash2 } from 'lucide-react'
import { toast } from 'sonner'

import { useLanguage } from '@/contexts/LanguageContext'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { Textarea } from '@/components/ui/textarea'
import {
  createAdminFaq,
  deleteAdminFaq,
  getAdminFaqs,
  type AdminFaqItem,
  updateAdminFaq,
} from '@/services/data/admin-content'

const emptyForm: AdminFaqItem = {
  id: '',
  title: '',
  questionAr: '',
  questionEn: '',
  answerAr: '',
  answerEn: '',
  category: '',
  isPublished: true,
  displayOrder: 0,
}

export default function FAQManagementPage() {
  const { t } = useLanguage()
  const [items, setItems] = useState<AdminFaqItem[]>([])
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [isDialogOpen, setIsDialogOpen] = useState(false)
  const [editingId, setEditingId] = useState<string | null>(null)
  const [formData, setFormData] = useState<AdminFaqItem>(emptyForm)

  useEffect(() => {
    void loadData()
  }, [])

  async function loadData() {
    setLoading(true)
    try {
      setItems(await getAdminFaqs())
    } catch (error) {
      toast.error(error instanceof Error ? error.message : t('تعذر تحميل الأسئلة الشائعة', 'Failed to load FAQs'))
    } finally {
      setLoading(false)
    }
  }

  function updateField(field: keyof AdminFaqItem, value: string | boolean | number) {
    setFormData((current) => ({ ...current, [field]: value }))
  }

  function openCreate() {
    setEditingId(null)
    setFormData(emptyForm)
    setIsDialogOpen(true)
  }

  function openEdit(item: AdminFaqItem) {
    setEditingId(item.id)
    setFormData(item)
    setIsDialogOpen(true)
  }

  async function handleSubmit() {
    const questionAr = formData.questionAr.trim() || formData.title.trim()
    const answerAr = formData.answerAr.trim()

    if (!questionAr || !answerAr) {
      toast.error(t('السؤال والجواب بالعربية مطلوبان', 'Arabic question and answer are required'))
      return
    }

    setSaving(true)
    try {
      const payload = {
        title: questionAr,
        content: answerAr,
        questionAr,
        questionEn: formData.questionEn,
        answerAr,
        answerEn: formData.answerEn,
        category: formData.category,
        isPublished: formData.isPublished ? 1 : 0,
        displayOrder: formData.displayOrder,
      }

      if (editingId) {
        await updateAdminFaq(editingId, payload)
        toast.success(t('تم تحديث السؤال', 'FAQ updated'))
      } else {
        await createAdminFaq(payload)
        toast.success(t('تمت إضافة السؤال', 'FAQ created'))
      }
      setIsDialogOpen(false)
      await loadData()
    } catch (error) {
      toast.error(error instanceof Error ? error.message : t('تعذر حفظ السؤال', 'Failed to save FAQ'))
    } finally {
      setSaving(false)
    }
  }

  async function handleDelete(id: string) {
    if (!window.confirm(t('هل تريد حذف هذا السؤال؟', 'Delete this FAQ item?'))) {
      return
    }

    try {
      await deleteAdminFaq(id)
      toast.success(t('تم حذف السؤال', 'FAQ deleted'))
      await loadData()
    } catch (error) {
      toast.error(error instanceof Error ? error.message : t('تعذر حذف السؤال', 'Failed to delete FAQ'))
    }
  }

  return (
    <div>
      <div className="mb-8 flex items-center justify-between">
        <div>
          <h1 className="mb-2 text-3xl font-bold">{t('إدارة الأسئلة الشائعة', 'FAQ Management')}</h1>
          <p className="text-muted-foreground">{t('تحرير الأسئلة الشائعة من البيانات الحية', 'Manage live FAQ content')}</p>
        </div>
        <Button onClick={openCreate}>
          <Plus className="mr-2 h-4 w-4" />
          {t('إضافة سؤال', 'Add Question')}
        </Button>
      </div>

      <div className="space-y-4">
        {loading ? (
          <Card>
            <CardContent className="py-8 text-center">{t('جاري التحميل...', 'Loading...')}</CardContent>
          </Card>
        ) : items.length === 0 ? (
          <Card>
            <CardContent className="py-8 text-center">{t('لا توجد أسئلة بعد', 'No FAQs yet')}</CardContent>
          </Card>
        ) : (
          items.map((item) => (
            <Card key={item.id}>
              <CardHeader>
                <div className="flex items-start justify-between gap-4">
                  <div>
                    <CardTitle className="text-lg">{item.questionAr || item.title || item.questionEn}</CardTitle>
                    <p className="mt-2 text-sm text-muted-foreground">
                      {t('التصنيف', 'Category')}: {item.category || '-'} | {t('الترتيب', 'Order')}: {item.displayOrder}
                    </p>
                  </div>
                  <div className="flex gap-2">
                    <Button variant="ghost" size="icon" onClick={() => openEdit(item)}>
                      <Edit className="h-4 w-4" />
                    </Button>
                    <Button variant="ghost" size="icon" onClick={() => handleDelete(item.id)}>
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <p className="text-muted-foreground">{item.answerAr || item.answerEn}</p>
              </CardContent>
            </Card>
          ))
        )}
      </div>

      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="max-h-[90vh] max-w-4xl overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editingId ? t('تعديل سؤال', 'Edit FAQ') : t('إضافة سؤال', 'Add FAQ')}</DialogTitle>
          </DialogHeader>
          <div className="grid gap-4">
            <div className="grid gap-4 md:grid-cols-2">
              <div className="space-y-2">
                <Label>{t('السؤال بالعربية', 'Arabic Question')}</Label>
                <Input dir="rtl" value={formData.questionAr} onChange={(e) => updateField('questionAr', e.target.value)} />
              </div>
              <div className="space-y-2">
                <Label>{t('السؤال بالإنجليزية', 'English Question')}</Label>
                <Input value={formData.questionEn} onChange={(e) => updateField('questionEn', e.target.value)} />
              </div>
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              <div className="space-y-2">
                <Label>{t('الإجابة بالعربية', 'Arabic Answer')}</Label>
                <Textarea dir="rtl" rows={6} value={formData.answerAr} onChange={(e) => updateField('answerAr', e.target.value)} />
              </div>
              <div className="space-y-2">
                <Label>{t('الإجابة بالإنجليزية', 'English Answer')}</Label>
                <Textarea rows={6} value={formData.answerEn} onChange={(e) => updateField('answerEn', e.target.value)} />
              </div>
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              <div className="space-y-2">
                <Label>{t('التصنيف', 'Category')}</Label>
                <Input value={formData.category} onChange={(e) => updateField('category', e.target.value)} />
              </div>
              <div className="space-y-2">
                <Label>{t('ترتيب العرض', 'Display Order')}</Label>
                <Input type="number" value={formData.displayOrder} onChange={(e) => updateField('displayOrder', Number(e.target.value))} />
              </div>
            </div>

            <div className="flex items-center justify-between rounded-lg border p-4">
              <div>
                <p className="font-medium">{t('نشر السؤال', 'Publish FAQ')}</p>
                <p className="text-sm text-muted-foreground">{t('إظهار السؤال في الموقع العام', 'Show the FAQ on the public website')}</p>
              </div>
              <Switch checked={formData.isPublished} onCheckedChange={(checked) => updateField('isPublished', checked)} />
            </div>

            <div className="flex justify-end gap-2">
              <Button variant="outline" onClick={() => setIsDialogOpen(false)}>
                {t('إلغاء', 'Cancel')}
              </Button>
              <Button onClick={handleSubmit} disabled={saving}>
                {saving ? t('جارٍ الحفظ...', 'Saving...') : t('حفظ', 'Save')}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  )
}
