'use client'

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

import { useLanguage } from '@/contexts/LanguageContext'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
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 { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Textarea } from '@/components/ui/textarea'
import {
  createAdminFaculty,
  deleteAdminFaculty,
  getAdminDepartments,
  getAdminFaculty,
  type AdminDepartmentOption,
  type AdminFacultyItem,
  updateAdminFaculty,
} from '@/services/data/admin-content'
import { getAdminColleges } from '@/services/data/admin-colleges'

type FacultyPublication = AdminFacultyItem['publications'][number]
type FacultyCourse = AdminFacultyItem['courses'][number]
type FacultyEducation = AdminFacultyItem['education'][number]
type FacultyExperience = AdminFacultyItem['experience'][number]

const emptyForm: AdminFacultyItem = {
  id: '',
  fullName: '',
  fullNameEn: '',
  academicTitle: '',
  academicTitleEn: '',
  linkedCollege: '',
  linkedProgram: '',
  department: '',
  biography: '',
  biographyEn: '',
  photo: '',
  email: '',
  phone: '',
  officeHours: '',
  officeHoursEn: '',
  researchInterestsAr: [],
  researchInterestsEn: [],
  publications: [],
  courses: [],
  education: [],
  experience: [],
  isActive: true,
}

function initials(name: string) {
  return name
    .split(' ')
    .filter(Boolean)
    .map((part) => part[0])
    .join('')
    .slice(0, 2)
    .toUpperCase()
}

function emptyPublication(): FacultyPublication {
  return { id: '', titleAr: '', titleEn: '', journal: '', year: '', link: '' }
}

function emptyCourse(): FacultyCourse {
  return { id: '', code: '', nameAr: '', nameEn: '', semester: '' }
}

function emptyEducation(): FacultyEducation {
  return { id: '', degreeAr: '', degreeEn: '', institutionAr: '', institutionEn: '', year: '' }
}

function emptyExperience(): FacultyExperience {
  return { id: '', positionAr: '', positionEn: '', organizationAr: '', organizationEn: '', periodAr: '', periodEn: '' }
}

function TableSection({
  title,
  subtitle,
  children,
  onAdd,
  addLabel,
}: {
  title: string
  subtitle?: string
  children: React.ReactNode
  onAdd: () => void
  addLabel: string
}) {
  return (
    <div className="rounded-xl border p-4 space-y-4">
      <div className="flex items-center justify-between gap-4">
        <div>
          <h3 className="font-semibold">{title}</h3>
          {subtitle ? <p className="text-sm text-muted-foreground">{subtitle}</p> : null}
        </div>
        <Button type="button" variant="outline" size="sm" onClick={onAdd}>
          <Plus className="mr-2 h-4 w-4" />
          {addLabel}
        </Button>
      </div>
      {children}
    </div>
  )
}

export default function FacultyManagementPage() {
  const { t } = useLanguage()
  const [items, setItems] = useState<AdminFacultyItem[]>([])
  const [loading, setLoading] = useState(true)
  const [collegeOptions, setCollegeOptions] = useState<{ id: string; label: string }[]>([])
  const [programOptions, setProgramOptions] = useState<{ id: string; label: string; collegeId: string }[]>([])
  const [departmentOptions, setDepartmentOptions] = useState<AdminDepartmentOption[]>([])
  const [saving, setSaving] = useState(false)
  const [isDialogOpen, setIsDialogOpen] = useState(false)
  const [editingId, setEditingId] = useState<string | null>(null)
  const [formData, setFormData] = useState<AdminFacultyItem>(emptyForm)

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

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

  async function loadColleges() {
    try {
      const colleges = await getAdminColleges()
      setCollegeOptions(
        colleges.map((college) => ({
          id: college.id,
          label: college.nameAr || college.nameEn || college.collegeName || college.id,
        })),
      )
      const nextPrograms: { id: string; label: string; collegeId: string }[] = []
      colleges.forEach((college) => {
        ;(college.programs || []).forEach((program) => {
          nextPrograms.push({
            id: program.id,
            label: program.nameAr || program.nameEn || program.id,
            collegeId: college.id,
          })
        })
      })
      setProgramOptions(nextPrograms)
    } catch {
      setCollegeOptions([])
      setProgramOptions([])
    }
  }

  async function loadDepartments() {
    try {
      setDepartmentOptions(await getAdminDepartments())
    } catch {
      setDepartmentOptions([])
    }
  }

  function updateField<K extends keyof AdminFacultyItem>(field: K, value: AdminFacultyItem[K]) {
    setFormData((current) => ({ ...current, [field]: value }))
  }

  function updateResearchList(field: 'researchInterestsAr' | 'researchInterestsEn', value: string) {
    updateField(
      field,
      value
        .split('\n')
        .map((entry) => entry.trim())
        .filter(Boolean) as AdminFacultyItem[typeof field],
    )
  }

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

  function openEdit(item: AdminFacultyItem) {
    setEditingId(item.id)
    setFormData({
      ...emptyForm,
      ...item,
      researchInterestsAr: Array.isArray(item.researchInterestsAr) ? item.researchInterestsAr : [],
      researchInterestsEn: Array.isArray(item.researchInterestsEn) ? item.researchInterestsEn : [],
      publications: Array.isArray(item.publications) ? item.publications : [],
      courses: Array.isArray(item.courses) ? item.courses : [],
      education: Array.isArray(item.education) ? item.education : [],
      experience: Array.isArray(item.experience) ? item.experience : [],
    })
    setIsDialogOpen(true)
  }

  async function handleSubmit() {
    if (!formData.fullName.trim()) {
      toast.error(t('اسم عضو هيئة التدريس مطلوب', 'Faculty member name is required'))
      return
    }

    setSaving(true)
    try {
      const payload = {
        full_name: formData.fullName,
        full_name_en: formData.fullNameEn,
        academic_title: formData.academicTitle,
        academic_title_en: formData.academicTitleEn,
        linked_college: formData.linkedCollege,
        linked_program: formData.linkedProgram,
        department: formData.department,
        biography: formData.biography,
        biography_en: formData.biographyEn,
        photo: formData.photo,
        email: formData.email,
        phone: formData.phone,
        office_hours: formData.officeHours,
        office_hours_en: formData.officeHoursEn,
        research_interests_ar: formData.researchInterestsAr,
        research_interests_en: formData.researchInterestsEn,
        publications: formData.publications,
        courses: formData.courses,
        education: formData.education,
        experience: formData.experience,
        is_active: formData.isActive ? 1 : 0,
      }

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

  async function handleDelete(id: string) {
    if (!window.confirm(t('هل تريد حذف هذا العضو؟', 'Delete this faculty member?'))) return
    try {
      await deleteAdminFaculty(id)
      toast.success(t('تم حذف العضو', 'Faculty member deleted'))
      await loadData()
    } catch (error) {
      toast.error(error instanceof Error ? error.message : t('تعذر حذف العضو', 'Failed to delete faculty member'))
    }
  }

  const filteredPrograms = useMemo(
    () => programOptions.filter((program) => !formData.linkedCollege || program.collegeId === formData.linkedCollege),
    [programOptions, formData.linkedCollege],
  )

  function updatePublication(index: number, field: keyof FacultyPublication, value: string) {
    const next = [...formData.publications]
    next[index] = { ...next[index], [field]: value }
    updateField('publications', next)
  }

  function updateCourse(index: number, field: keyof FacultyCourse, value: string) {
    const next = [...formData.courses]
    next[index] = { ...next[index], [field]: value }
    updateField('courses', next)
  }

  function updateEducation(index: number, field: keyof FacultyEducation, value: string) {
    const next = [...formData.education]
    next[index] = { ...next[index], [field]: value }
    updateField('education', next)
  }

  function updateExperience(index: number, field: keyof FacultyExperience, value: string) {
    const next = [...formData.experience]
    next[index] = { ...next[index], [field]: value }
    updateField('experience', next)
  }

  return (
    <div>
      <div className="mb-8 flex items-center justify-between">
        <div>
          <h1 className="mb-2 text-3xl font-bold">{t('إدارة الكادر التعليمي', 'Faculty Management')}</h1>
          <p className="text-muted-foreground">{t('تعديل بيانات صفحة عضو هيئة التدريس بالكامل من نفس الشاشة', 'Manage the full faculty member profile from a single screen')}</p>
        </div>
        <Button onClick={openCreate}>
          <Plus className="mr-2 h-4 w-4" />
          {t('إضافة عضو', 'Add Member')}
        </Button>
      </div>

      <div className="rounded-lg border bg-card">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>{t('العضو', 'Member')}</TableHead>
              <TableHead>{t('الدرجة العلمية', 'Academic Title')}</TableHead>
              <TableHead>{t('الكلية', 'College')}</TableHead>
              <TableHead>{t('التبويبات المعبأة', 'Filled Sections')}</TableHead>
              <TableHead>{t('الحالة', 'Status')}</TableHead>
              <TableHead className="text-right">{t('الإجراءات', 'Actions')}</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              <TableRow>
                <TableCell colSpan={6} className="py-8 text-center">{t('جاري التحميل...', 'Loading...')}</TableCell>
              </TableRow>
            ) : items.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="py-8 text-center">{t('لا يوجد أعضاء بعد', 'No faculty members yet')}</TableCell>
              </TableRow>
            ) : (
              items.map((item) => {
                const sections = [
                  item.biography || item.biographyEn ? t('نبذة', 'About') : '',
                  item.publications.length ? t('أبحاث', 'Research') : '',
                  item.courses.length ? t('مقررات', 'Courses') : '',
                  item.education.length ? t('تعليم', 'Education') : '',
                  item.experience.length ? t('خبرات', 'Experience') : '',
                ].filter(Boolean)
                return (
                  <TableRow key={item.id}>
                    <TableCell>
                      <div className="flex items-center gap-3">
                        <Avatar className="h-10 w-10">
                          <AvatarImage src={item.photo} alt={item.fullName} />
                          <AvatarFallback>{initials(item.fullName || item.fullNameEn)}</AvatarFallback>
                        </Avatar>
                        <div>
                          <p className="font-medium">{item.fullName || item.fullNameEn || '-'}</p>
                          {item.fullNameEn ? <p className="text-sm text-muted-foreground">{item.fullNameEn}</p> : null}
                        </div>
                      </div>
                    </TableCell>
                    <TableCell><Badge variant="outline">{item.academicTitle || item.academicTitleEn || '-'}</Badge></TableCell>
                    <TableCell>{collegeOptions.find((college) => college.id === item.linkedCollege)?.label || '-'}</TableCell>
                    <TableCell className="text-sm text-muted-foreground">{sections.length ? sections.join(' • ') : '-'}</TableCell>
                    <TableCell>
                      <Badge variant={item.isActive ? 'default' : 'secondary'}>
                        {item.isActive ? t('نشط', 'Active') : t('غير نشط', 'Inactive')}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-right">
                      <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>
                    </TableCell>
                  </TableRow>
                )
              })
            )}
          </TableBody>
        </Table>
      </div>

      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="max-h-[92vh] max-w-6xl overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editingId ? t('تعديل عضو هيئة التدريس', 'Edit Faculty Member') : t('إضافة عضو هيئة تدريس', 'Add Faculty Member')}</DialogTitle>
          </DialogHeader>

          <div className="grid gap-6">
            <div className="rounded-xl border p-4 space-y-4">
              <h3 className="font-semibold">{t('البيانات الأساسية', 'Basic Information')}</h3>

              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label>{t('الاسم بالعربية', 'Arabic Name')}</Label>
                  <Input dir="rtl" value={formData.fullName} onChange={(e) => updateField('fullName', e.target.value)} />
                </div>
                <div className="space-y-2">
                  <Label>{t('الاسم بالإنجليزية', 'English Name')}</Label>
                  <Input dir="ltr" value={formData.fullNameEn} onChange={(e) => updateField('fullNameEn', e.target.value)} />
                </div>
              </div>

              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label>{t('اللقب الأكاديمي بالعربية', 'Arabic Academic Title')}</Label>
                  <Input dir="rtl" value={formData.academicTitle} onChange={(e) => updateField('academicTitle', e.target.value)} />
                </div>
                <div className="space-y-2">
                  <Label>{t('اللقب الأكاديمي بالإنجليزية', 'English Academic Title')}</Label>
                  <Input dir="ltr" value={formData.academicTitleEn} onChange={(e) => updateField('academicTitleEn', e.target.value)} />
                </div>
              </div>

              <div className="grid gap-4 md:grid-cols-3">
                <div className="space-y-2">
                  <Label>{t('الكلية المرتبطة', 'Linked College')}</Label>
                  <select
                    className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                    value={formData.linkedCollege}
                    onChange={(e) => updateField('linkedCollege', e.target.value)}
                  >
                    <option value="">{t('اختر الكلية', 'Select college')}</option>
                    {collegeOptions.map((college) => (
                      <option key={college.id} value={college.id}>{college.label}</option>
                    ))}
                  </select>
                </div>

                <div className="space-y-2">
                  <Label>{t('القسم الأكاديمي', 'Academic Department')}</Label>
                  <select
                    className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                    value={formData.department}
                    onChange={(e) => {
                      const nextDepartment = e.target.value
                      const selectedDepartment = departmentOptions.find((department) => department.id === nextDepartment)
                      updateField('department', nextDepartment)
                      if (selectedDepartment?.college) updateField('linkedCollege', selectedDepartment.college)
                    }}
                  >
                    <option value="">{t('اختر القسم', 'Select department')}</option>
                    {departmentOptions.map((department) => (
                      <option key={department.id} value={department.id}>
                        {department.nameAr || department.nameEn} {department.collegeLabel ? `- ${department.collegeLabel}` : ''}
                      </option>
                    ))}
                  </select>
                </div>

                <div className="space-y-2">
                  <Label>{t('البرنامج المرتبط', 'Linked Program')}</Label>
                  <select
                    className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                    value={formData.linkedProgram}
                    onChange={(e) => updateField('linkedProgram', e.target.value)}
                  >
                    <option value="">{t('اختر البرنامج', 'Select program')}</option>
                    {filteredPrograms.map((program) => (
                      <option key={program.id} value={program.id}>{program.label}</option>
                    ))}
                  </select>
                </div>
              </div>

              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label>{t('البريد الإلكتروني', 'Email')}</Label>
                  <Input dir="ltr" value={formData.email} onChange={(e) => updateField('email', e.target.value)} />
                </div>
                <div className="space-y-2">
                  <Label>{t('رقم الهاتف', 'Phone')}</Label>
                  <Input dir="ltr" value={formData.phone} onChange={(e) => updateField('phone', e.target.value)} />
                </div>
              </div>

              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label>{t('ساعات المكتب بالعربية', 'Arabic Office Hours')}</Label>
                  <Input dir="rtl" value={formData.officeHours} onChange={(e) => updateField('officeHours', e.target.value)} />
                </div>
                <div className="space-y-2">
                  <Label>{t('ساعات المكتب بالإنجليزية', 'English Office Hours')}</Label>
                  <Input dir="ltr" value={formData.officeHoursEn} onChange={(e) => updateField('officeHoursEn', e.target.value)} />
                </div>
              </div>

              <div className="space-y-2">
                <Label>{t('رابط الصورة الشخصية', 'Profile Photo URL')}</Label>
                <Input dir="ltr" value={formData.photo} onChange={(e) => updateField('photo', e.target.value)} />
              </div>

              <div className="flex items-center justify-between rounded-lg border p-4">
                <div>
                  <p className="font-medium">{t('تفعيل العضو', 'Activate Member')}</p>
                  <p className="text-sm text-muted-foreground">{t('إظهار العضو في صفحات الموقع العامة', 'Show this member on public pages')}</p>
                </div>
                <Switch checked={formData.isActive} onCheckedChange={(checked) => updateField('isActive', checked)} />
              </div>
            </div>

            <div className="rounded-xl border p-4 space-y-4">
              <h3 className="font-semibold">{t('النبذة والاهتمامات البحثية', 'Biography and Research Interests')}</h3>
              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label>{t('النبذة بالعربية', 'Arabic Biography')}</Label>
                  <Textarea dir="rtl" rows={6} value={formData.biography} onChange={(e) => updateField('biography', e.target.value)} />
                </div>
                <div className="space-y-2">
                  <Label>{t('النبذة بالإنجليزية', 'English Biography')}</Label>
                  <Textarea dir="ltr" rows={6} value={formData.biographyEn} onChange={(e) => updateField('biographyEn', e.target.value)} />
                </div>
              </div>
              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label>{t('الاهتمامات البحثية بالعربية', 'Arabic Research Interests')}</Label>
                  <Textarea
                    dir="rtl"
                    rows={5}
                    value={formData.researchInterestsAr.join('\n')}
                    onChange={(e) => updateResearchList('researchInterestsAr', e.target.value)}
                  />
                  <p className="text-xs text-muted-foreground">{t('كل اهتمام في سطر مستقل', 'One interest per line')}</p>
                </div>
                <div className="space-y-2">
                  <Label>{t('الاهتمامات البحثية بالإنجليزية', 'English Research Interests')}</Label>
                  <Textarea
                    dir="ltr"
                    rows={5}
                    value={formData.researchInterestsEn.join('\n')}
                    onChange={(e) => updateResearchList('researchInterestsEn', e.target.value)}
                  />
                  <p className="text-xs text-muted-foreground">{t('كل اهتمام في سطر مستقل', 'One interest per line')}</p>
                </div>
              </div>
            </div>

            <TableSection
              title={t('الأبحاث والمنشورات', 'Publications')}
              subtitle={t('هذه البيانات تظهر في تبويب الأبحاث في صفحة عضو هيئة التدريس', 'These rows feed the research tab on the faculty profile page')}
              onAdd={() => updateField('publications', [...formData.publications, emptyPublication()])}
              addLabel={t('إضافة منشور', 'Add publication')}
            >
              {formData.publications.length === 0 ? <p className="text-sm text-muted-foreground">{t('لا توجد منشورات مضافة', 'No publications added')}</p> : null}
              {formData.publications.map((publication, index) => (
                <div key={`${publication.id || 'publication'}-${index}`} className="grid gap-3 rounded-lg border p-4 md:grid-cols-2">
                  <Input dir="rtl" placeholder={t('العنوان بالعربية', 'Arabic title')} value={publication.titleAr} onChange={(e) => updatePublication(index, 'titleAr', e.target.value)} />
                  <Input dir="ltr" placeholder={t('العنوان بالإنجليزية', 'English title')} value={publication.titleEn} onChange={(e) => updatePublication(index, 'titleEn', e.target.value)} />
                  <Input dir="rtl" placeholder={t('اسم المجلة/الناشر', 'Journal / publisher')} value={publication.journal} onChange={(e) => updatePublication(index, 'journal', e.target.value)} />
                  <Input dir="ltr" placeholder={t('السنة', 'Year')} value={publication.year} onChange={(e) => updatePublication(index, 'year', e.target.value)} />
                  <Input dir="ltr" className="md:col-span-2" placeholder={t('رابط المنشور', 'Publication link')} value={publication.link} onChange={(e) => updatePublication(index, 'link', e.target.value)} />
                  <div className="md:col-span-2 flex justify-end">
                    <Button type="button" variant="ghost" size="sm" onClick={() => updateField('publications', formData.publications.filter((_, rowIndex) => rowIndex !== index))}>
                      <Trash2 className="mr-2 h-4 w-4" />
                      {t('حذف', 'Remove')}
                    </Button>
                  </div>
                </div>
              ))}
            </TableSection>

            <TableSection
              title={t('المقررات', 'Courses')}
              subtitle={t('هذه البيانات تظهر في تبويب المقررات', 'These rows feed the courses tab')}
              onAdd={() => updateField('courses', [...formData.courses, emptyCourse()])}
              addLabel={t('إضافة مقرر', 'Add course')}
            >
              {formData.courses.length === 0 ? <p className="text-sm text-muted-foreground">{t('لا توجد مقررات مضافة', 'No courses added')}</p> : null}
              {formData.courses.map((course, index) => (
                <div key={`${course.id || 'course'}-${index}`} className="grid gap-3 rounded-lg border p-4 md:grid-cols-2">
                  <Input dir="ltr" placeholder={t('رمز المقرر', 'Course code')} value={course.code} onChange={(e) => updateCourse(index, 'code', e.target.value)} />
                  <Input dir="rtl" placeholder={t('الفصل الدراسي', 'Semester')} value={course.semester} onChange={(e) => updateCourse(index, 'semester', e.target.value)} />
                  <Input dir="rtl" placeholder={t('اسم المقرر بالعربية', 'Arabic course name')} value={course.nameAr} onChange={(e) => updateCourse(index, 'nameAr', e.target.value)} />
                  <Input dir="ltr" placeholder={t('اسم المقرر بالإنجليزية', 'English course name')} value={course.nameEn} onChange={(e) => updateCourse(index, 'nameEn', e.target.value)} />
                  <div className="md:col-span-2 flex justify-end">
                    <Button type="button" variant="ghost" size="sm" onClick={() => updateField('courses', formData.courses.filter((_, rowIndex) => rowIndex !== index))}>
                      <Trash2 className="mr-2 h-4 w-4" />
                      {t('حذف', 'Remove')}
                    </Button>
                  </div>
                </div>
              ))}
            </TableSection>

            <TableSection
              title={t('المؤهلات العلمية', 'Education')}
              subtitle={t('هذه البيانات تظهر في تبويب التعليم', 'These rows feed the education tab')}
              onAdd={() => updateField('education', [...formData.education, emptyEducation()])}
              addLabel={t('إضافة مؤهل', 'Add education')}
            >
              {formData.education.length === 0 ? <p className="text-sm text-muted-foreground">{t('لا توجد مؤهلات مضافة', 'No education entries added')}</p> : null}
              {formData.education.map((education, index) => (
                <div key={`${education.id || 'education'}-${index}`} className="grid gap-3 rounded-lg border p-4 md:grid-cols-2">
                  <Input dir="rtl" placeholder={t('الدرجة بالعربية', 'Arabic degree')} value={education.degreeAr} onChange={(e) => updateEducation(index, 'degreeAr', e.target.value)} />
                  <Input dir="ltr" placeholder={t('الدرجة بالإنجليزية', 'English degree')} value={education.degreeEn} onChange={(e) => updateEducation(index, 'degreeEn', e.target.value)} />
                  <Input dir="rtl" placeholder={t('الجهة التعليمية بالعربية', 'Arabic institution')} value={education.institutionAr} onChange={(e) => updateEducation(index, 'institutionAr', e.target.value)} />
                  <Input dir="ltr" placeholder={t('الجهة التعليمية بالإنجليزية', 'English institution')} value={education.institutionEn} onChange={(e) => updateEducation(index, 'institutionEn', e.target.value)} />
                  <Input dir="ltr" className="md:col-span-2" placeholder={t('السنة', 'Year')} value={education.year} onChange={(e) => updateEducation(index, 'year', e.target.value)} />
                  <div className="md:col-span-2 flex justify-end">
                    <Button type="button" variant="ghost" size="sm" onClick={() => updateField('education', formData.education.filter((_, rowIndex) => rowIndex !== index))}>
                      <Trash2 className="mr-2 h-4 w-4" />
                      {t('حذف', 'Remove')}
                    </Button>
                  </div>
                </div>
              ))}
            </TableSection>

            <TableSection
              title={t('الخبرات المهنية', 'Experience')}
              subtitle={t('هذه البيانات تظهر في تبويب الخبرات', 'These rows feed the experience tab')}
              onAdd={() => updateField('experience', [...formData.experience, emptyExperience()])}
              addLabel={t('إضافة خبرة', 'Add experience')}
            >
              {formData.experience.length === 0 ? <p className="text-sm text-muted-foreground">{t('لا توجد خبرات مضافة', 'No experience entries added')}</p> : null}
              {formData.experience.map((experience, index) => (
                <div key={`${experience.id || 'experience'}-${index}`} className="grid gap-3 rounded-lg border p-4 md:grid-cols-2">
                  <Input dir="rtl" placeholder={t('المنصب بالعربية', 'Arabic position')} value={experience.positionAr} onChange={(e) => updateExperience(index, 'positionAr', e.target.value)} />
                  <Input dir="ltr" placeholder={t('المنصب بالإنجليزية', 'English position')} value={experience.positionEn} onChange={(e) => updateExperience(index, 'positionEn', e.target.value)} />
                  <Input dir="rtl" placeholder={t('الجهة بالعربية', 'Arabic organization')} value={experience.organizationAr} onChange={(e) => updateExperience(index, 'organizationAr', e.target.value)} />
                  <Input dir="ltr" placeholder={t('الجهة بالإنجليزية', 'English organization')} value={experience.organizationEn} onChange={(e) => updateExperience(index, 'organizationEn', e.target.value)} />
                  <Input dir="rtl" placeholder={t('الفترة بالعربية', 'Arabic period')} value={experience.periodAr} onChange={(e) => updateExperience(index, 'periodAr', e.target.value)} />
                  <Input dir="ltr" placeholder={t('الفترة بالإنجليزية', 'English period')} value={experience.periodEn} onChange={(e) => updateExperience(index, 'periodEn', e.target.value)} />
                  <div className="md:col-span-2 flex justify-end">
                    <Button type="button" variant="ghost" size="sm" onClick={() => updateField('experience', formData.experience.filter((_, rowIndex) => rowIndex !== index))}>
                      <Trash2 className="mr-2 h-4 w-4" />
                      {t('حذف', 'Remove')}
                    </Button>
                  </div>
                </div>
              ))}
            </TableSection>

            <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>
  )
}
