'use client'

import { useState, useEffect, useCallback } from 'react'
import ProtectedRoute from '@/components/ProtectedRoute'
import Modal from '@/components/Modal'
import LoadingSpinner from '@/components/LoadingSpinner'
import Link from 'next/link'
import { toast } from 'react-hot-toast'
import {
  CheckSquare,
  Plus,
  Search,
  Calendar,
  Clock,
  AlertCircle,
  ArrowLeft,
  ListTodo,
  CheckCircle2,
  Circle,
  AlertTriangle,
  Flag,
  Edit,
  Trash2,
  Loader2,
  Briefcase,
  User,
  FolderKanban,
  DollarSign,
  Layers
} from 'lucide-react'
import { tasksAPI, Task, CreateTaskData, UpdateTaskData, TaskFilters, projectsAPI, CreateProjectData, Project } from '@/lib/api/tasks'
import { useAuth } from '@/contexts/AuthContext'

function ProjectsContent() {
  const { hasPermission } = useAuth()
  const canCreateProject = hasPermission('projects', 'create')

  // View Mode: 'tasks' shows the tasks dashboard, 'projects' shows the projects gallery
  const [viewMode, setViewMode] = useState<'tasks' | 'projects'>('tasks')

  // Search term for the Projects view (independent of tasks search)
  const [projectSearchTerm, setProjectSearchTerm] = useState('')
  const [projectStatusFilter, setProjectStatusFilter] = useState('all')

  // State Management
  const [tasks, setTasks] = useState<Task[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  
  // Pagination
  const [currentPage, setCurrentPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [total, setTotal] = useState(0)
  const pageSize = 10

  // Filters
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedProject, setSelectedProject] = useState('all')
  const [selectedPriority, setSelectedPriority] = useState('all')
  const [selectedStatus, setSelectedStatus] = useState('all')

  // Modals
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [showEditModal, setShowEditModal] = useState(false)
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [selectedTask, setSelectedTask] = useState<Task | null>(null)

  // Project creation modal
  const [showCreateProjectModal, setShowCreateProjectModal] = useState(false)
  const [submittingProject, setSubmittingProject] = useState(false)
  const [projectFormErrors, setProjectFormErrors] = useState<Record<string, string>>({})

  // Project edit/delete state
  const [showEditProjectModal, setShowEditProjectModal] = useState(false)
  const [showDeleteProjectDialog, setShowDeleteProjectDialog] = useState(false)
  const [selectedProjectForEdit, setSelectedProjectForEdit] = useState<Project | null>(null)
  const canEditProject = hasPermission('projects', 'edit')
  const canDeleteProject = hasPermission('projects', 'delete')
  const canEditTask = hasPermission('projects', 'edit')
  const canDeleteTask = hasPermission('projects', 'delete')

  const emptyProjectForm: CreateProjectData = {
    name: '',
    description: '',
    type: 'INTERNAL',
    startDate: new Date().toISOString().slice(0, 10),
    endDate: '',
    estimatedCost: undefined,
    status: 'PLANNING',
    priority: 'MEDIUM',
    progress: 0,
  }
  const [projectForm, setProjectForm] = useState<CreateProjectData>(emptyProjectForm)

  // Form Data
  const [formData, setFormData] = useState<CreateTaskData>({
    title: '',
    description: '',
    projectId: '',
    assignedToId: '',
    priority: 'MEDIUM',
    status: 'PENDING',
    progress: 0,
    startDate: '',
    dueDate: '',
    estimatedHours: 0,
    tags: []
  })
  const [formErrors, setFormErrors] = useState<Record<string, string>>({})
  const [submitting, setSubmitting] = useState(false)

  // Projects for dropdown and projects view
  const [projects, setProjects] = useState<Project[]>([])
  const [loadingProjects, setLoadingProjects] = useState(false)

  // Fetch Projects for dropdown (re-used after project creation)
  const fetchProjects = useCallback(async () => {
    setLoadingProjects(true)
    try {
      const data = await projectsAPI.getAll()
      setProjects(data)
    } catch (err) {
      console.error('Failed to load projects:', err)
    } finally {
      setLoadingProjects(false)
    }
  }, [])

  useEffect(() => {
    fetchProjects()
  }, [fetchProjects])

  // Fetch Tasks (with debouncing for search)
  const fetchTasks = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const filters: TaskFilters = {
        page: currentPage,
        pageSize,
      }
      
      if (searchTerm) filters.search = searchTerm
      if (selectedProject !== 'all') filters.projectId = selectedProject
      if (selectedPriority !== 'all') filters.priority = selectedPriority
      if (selectedStatus !== 'all') filters.status = selectedStatus

      const data = await tasksAPI.getAll(filters)
      setTasks(data.tasks)
      setTotal(data.total)
      setTotalPages(data.totalPages)
    } catch (err: any) {
      setError(err.response?.data?.message || 'Failed to load tasks')
      toast.error('Failed to load tasks')
    } finally {
      setLoading(false)
    }
  }, [currentPage, searchTerm, selectedProject, selectedPriority, selectedStatus])

  // Debounced search
  useEffect(() => {
    const debounce = setTimeout(() => {
      setCurrentPage(1)
      fetchTasks()
    }, 500)
    return () => clearTimeout(debounce)
  }, [searchTerm])

  // Fetch on filter/page change
  useEffect(() => {
    fetchTasks()
  }, [currentPage, selectedProject, selectedPriority, selectedStatus])

  // Form Validation
  const validateForm = (): boolean => {
    const errors: Record<string, string> = {}
    
    if (!formData.title || formData.title.trim().length < 3) {
      errors.title = 'Title must be at least 3 characters'
    }
    
    if (!formData.priority) {
      errors.priority = 'Priority is required'
    }

    setFormErrors(errors)
    return Object.keys(errors).length === 0
  }

  // Build a clean task payload for the API:
  // - Empty optional strings become undefined (so the column stays NULL)
  // - "YYYY-MM-DD" dates get anchored at UTC midnight ISO (Prisma @db.Date wants
  //   a real DateTime; a bare date string causes "Invalid data")
  // - `tags` (not in the Task schema) is stripped
  // - Numerics fall back cleanly when blank / NaN
  const buildTaskPayload = (data: CreateTaskData): CreateTaskData => {
    const toIsoDateTime = (yyyymmdd?: string) =>
      yyyymmdd ? new Date(`${yyyymmdd}T00:00:00Z`).toISOString() : undefined

    const payload: any = {
      title: data.title?.trim(),
      priority: data.priority || 'MEDIUM',
      status: data.status || 'PENDING',
      progress: Number.isFinite(data.progress as number) ? data.progress : 0,
    }

    if (data.description && data.description.trim()) {
      payload.description = data.description.trim()
    }
    if (data.projectId) payload.projectId = data.projectId
    if (data.assignedToId) payload.assignedToId = data.assignedToId
    const startIso = toIsoDateTime(data.startDate)
    if (startIso) payload.startDate = startIso
    const dueIso = toIsoDateTime(data.dueDate)
    if (dueIso) payload.dueDate = dueIso
    if (
      data.estimatedHours !== undefined &&
      data.estimatedHours !== null &&
      !Number.isNaN(data.estimatedHours) &&
      data.estimatedHours > 0
    ) {
      payload.estimatedHours = data.estimatedHours
    }

    return payload
  }

  // Create Task
  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!validateForm()) {
      toast.error('Please fix form errors')
      return
    }

    setSubmitting(true)
    try {
      await tasksAPI.create(buildTaskPayload(formData))
      toast.success('Task created successfully!')
      setShowCreateModal(false)
      resetForm()
      fetchTasks()
    } catch (err: any) {
      const message = err.response?.data?.message || 'Failed to create task'
      toast.error(message)
    } finally {
      setSubmitting(false)
    }
  }

  // Edit Task
  const handleEdit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!selectedTask || !validateForm()) {
      toast.error('Please fix form errors')
      return
    }

    setSubmitting(true)
    try {
      await tasksAPI.update(selectedTask.id, buildTaskPayload(formData) as UpdateTaskData)
      toast.success('Task updated successfully!')
      setShowEditModal(false)
      resetForm()
      fetchTasks()
    } catch (err: any) {
      const message = err.response?.data?.message || 'Failed to update task'
      toast.error(message)
    } finally {
      setSubmitting(false)
    }
  }

  // Delete Task
  const handleDelete = async () => {
    if (!selectedTask) return

    setSubmitting(true)
    try {
      await tasksAPI.delete(selectedTask.id)
      toast.success('Task deleted successfully!')
      setShowDeleteDialog(false)
      setSelectedTask(null)
      fetchTasks()
    } catch (err: any) {
      const message = err.response?.data?.message || 'Failed to delete task'
      toast.error(message)
    } finally {
      setSubmitting(false)
    }
  }

  // ---------- Project creation ----------

  const resetProjectForm = () => {
    setProjectForm(emptyProjectForm)
    setProjectFormErrors({})
  }

  const validateProjectForm = (): boolean => {
    const errors: Record<string, string> = {}

    if (!projectForm.name || projectForm.name.trim().length < 3) {
      errors.name = 'Name must be at least 3 characters'
    }
    if (!projectForm.type) {
      errors.type = 'Type is required'
    }
    if (!projectForm.startDate) {
      errors.startDate = 'Start date is required'
    }
    if (
      projectForm.startDate &&
      projectForm.endDate &&
      new Date(projectForm.endDate) < new Date(projectForm.startDate)
    ) {
      errors.endDate = 'End date must be after start date'
    }

    setProjectFormErrors(errors)
    return Object.keys(errors).length === 0
  }

  const handleCreateProject = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!validateProjectForm()) {
      toast.error('Please fix form errors')
      return
    }

    setSubmittingProject(true)
    try {
      // Prisma's `DateTime` validator expects a full ISO-8601 string with
      // time component (or a Date object). A plain "YYYY-MM-DD" from
      // <input type="date"> is rejected ("premature end of input").
      // We anchor each date at UTC midnight so it round-trips cleanly into
      // the @db.Date column without timezone drift.
      const toIsoDateTime = (yyyymmdd: string) =>
        new Date(`${yyyymmdd}T00:00:00Z`).toISOString()

      // Build a clean payload: strip empty optional fields.
      const payload: CreateProjectData = {
        name: projectForm.name.trim(),
        type: projectForm.type,
        startDate: toIsoDateTime(projectForm.startDate),
        status: projectForm.status || 'PLANNING',
        priority: projectForm.priority || 'MEDIUM',
        progress: projectForm.progress ?? 0,
      }
      if (projectForm.description && projectForm.description.trim()) {
        payload.description = projectForm.description.trim()
      }
      if (projectForm.endDate) {
        payload.endDate = toIsoDateTime(projectForm.endDate)
      }
      if (
        projectForm.estimatedCost !== undefined &&
        projectForm.estimatedCost !== null &&
        !Number.isNaN(projectForm.estimatedCost)
      ) {
        payload.estimatedCost = projectForm.estimatedCost
      }

      const created = await projectsAPI.create(payload)
      toast.success('Project created successfully!')

      // Refresh the dropdown and pre-select the new project on the open task form.
      await fetchProjects()
      setFormData((prev) => ({ ...prev, projectId: created.id }))

      setShowCreateProjectModal(false)
      resetProjectForm()
    } catch (err: any) {
      const message = err.response?.data?.message || 'Failed to create project'
      toast.error(message)
    } finally {
      setSubmittingProject(false)
    }
  }

  // Open the project edit modal, pre-filled
  const openEditProjectModal = (project: Project) => {
    setSelectedProjectForEdit(project)
    setProjectForm({
      name: project.name || '',
      description: project.description || '',
      type: project.type || 'INTERNAL',
      startDate: project.startDate ? project.startDate.slice(0, 10) : new Date().toISOString().slice(0, 10),
      endDate: project.endDate ? project.endDate.slice(0, 10) : '',
      estimatedCost:
        project.estimatedCost != null ? Number(project.estimatedCost) : undefined,
      status: project.status || 'PLANNING',
      priority: project.priority || 'MEDIUM',
      progress: project.progress ?? 0,
    })
    setProjectFormErrors({})
    setShowEditProjectModal(true)
  }

  const openDeleteProjectDialog = (project: Project) => {
    setSelectedProjectForEdit(project)
    setShowDeleteProjectDialog(true)
  }

  // Update project
  const handleUpdateProject = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!selectedProjectForEdit || !validateProjectForm()) {
      toast.error('Please fix form errors')
      return
    }

    setSubmittingProject(true)
    try {
      const toIsoDateTime = (yyyymmdd: string) =>
        new Date(`${yyyymmdd}T00:00:00Z`).toISOString()

      const payload: any = {
        name: projectForm.name.trim(),
        type: projectForm.type,
        startDate: toIsoDateTime(projectForm.startDate),
        status: projectForm.status || 'PLANNING',
        priority: projectForm.priority || 'MEDIUM',
        progress: projectForm.progress ?? 0,
      }
      if (projectForm.description && projectForm.description.trim()) {
        payload.description = projectForm.description.trim()
      } else {
        payload.description = null
      }
      if (projectForm.endDate) {
        payload.endDate = toIsoDateTime(projectForm.endDate)
      } else {
        payload.endDate = null
      }
      if (
        projectForm.estimatedCost !== undefined &&
        projectForm.estimatedCost !== null &&
        !Number.isNaN(projectForm.estimatedCost)
      ) {
        payload.estimatedCost = projectForm.estimatedCost
      } else {
        payload.estimatedCost = null
      }

      await projectsAPI.update(selectedProjectForEdit.id, payload)
      toast.success('Project updated successfully!')
      await fetchProjects()
      setShowEditProjectModal(false)
      setSelectedProjectForEdit(null)
      resetProjectForm()
    } catch (err: any) {
      const message = err.response?.data?.message || 'Failed to update project'
      toast.error(message)
    } finally {
      setSubmittingProject(false)
    }
  }

  // Delete project
  const handleDeleteProject = async () => {
    if (!selectedProjectForEdit) return

    setSubmittingProject(true)
    try {
      await projectsAPI.delete(selectedProjectForEdit.id)
      toast.success('Project deleted successfully!')
      await fetchProjects()
      // If the deleted project was the active filter, clear it
      if (selectedProject === selectedProjectForEdit.id) {
        setSelectedProject('all')
      }
      setShowDeleteProjectDialog(false)
      setSelectedProjectForEdit(null)
    } catch (err: any) {
      const message =
        err.response?.data?.message ||
        'Failed to delete project (it may have tasks or other related data)'
      toast.error(message)
    } finally {
      setSubmittingProject(false)
    }
  }

  // Utility Functions
  const resetForm = () => {
    setFormData({
      title: '',
      description: '',
      projectId: '',
      assignedToId: '',
      priority: 'MEDIUM',
      status: 'PENDING',
      progress: 0,
      startDate: '',
      dueDate: '',
      estimatedHours: 0,
      tags: []
    })
    setFormErrors({})
    setSelectedTask(null)
  }

  const openEditModal = (task: Task) => {
    setSelectedTask(task)
    setFormData({
      title: task.title,
      description: task.description,
      projectId: task.projectId,
      assignedToId: task.assignedToId,
      priority: task.priority,
      status: task.status,
      progress: task.progress,
      startDate: task.startDate?.split('T')[0],
      dueDate: task.dueDate?.split('T')[0],
      estimatedHours: task.estimatedHours,
      tags: task.tags
    })
    setShowEditModal(true)
  }

  const openDeleteDialog = (task: Task) => {
    setSelectedTask(task)
    setShowDeleteDialog(true)
  }

  const getPriorityColor = (priority: string) => {
    const colors: Record<string, string> = {
      LOW: 'bg-blue-100 text-blue-700',
      MEDIUM: 'bg-orange-100 text-orange-700',
      HIGH: 'bg-red-100 text-red-700',
      CRITICAL: 'bg-purple-100 text-purple-700'
    }
    return colors[priority] || 'bg-gray-100 text-gray-700'
  }

  const getStatusColor = (status: string) => {
    const colors: Record<string, string> = {
      PENDING: 'bg-gray-100 text-gray-700',
      IN_PROGRESS: 'bg-blue-100 text-blue-700',
      REVIEW: 'bg-purple-100 text-purple-700',
      COMPLETED: 'bg-green-100 text-green-700',
      CANCELLED: 'bg-red-100 text-red-700'
    }
    return colors[status] || 'bg-gray-100 text-gray-700'
  }

  // Project-specific helpers
  const getProjectStatusColor = (status: string) => {
    const colors: Record<string, string> = {
      PLANNING: 'bg-yellow-100 text-yellow-700',
      ACTIVE: 'bg-blue-100 text-blue-700',
      ON_HOLD: 'bg-gray-100 text-gray-700',
      COMPLETED: 'bg-green-100 text-green-700',
      CANCELLED: 'bg-red-100 text-red-700',
    }
    return colors[status] || 'bg-gray-100 text-gray-700'
  }

  const getProjectStatusLabel = (status: string) => {
    const labels: Record<string, string> = {
      PLANNING: 'تخطيط',
      ACTIVE: 'نشط',
      ON_HOLD: 'متوقف',
      COMPLETED: 'مكتمل',
      CANCELLED: 'ملغى',
    }
    return labels[status] || status
  }

  const getProjectTypeLabel = (type?: string) => {
    if (!type) return ''
    const labels: Record<string, string> = {
      INTERNAL: 'داخلي',
      CLIENT: 'عميل',
      IMPLEMENTATION: 'تنفيذ',
      MAINTENANCE: 'صيانة',
      GOVERNMENT: 'حكومي',
    }
    return labels[type] || type
  }

  // Count tasks per project (uses the loaded `tasks` for the current page;
  // this is a quick visual indicator, not an exact total across pages).
  const tasksCountByProject = tasks.reduce<Record<string, number>>((acc, t) => {
    if (t.projectId) {
      acc[t.projectId] = (acc[t.projectId] || 0) + 1
    }
    return acc
  }, {})

  // Filter projects for the Projects view
  const filteredProjects = projects.filter((p) => {
    const matchesSearch =
      !projectSearchTerm ||
      p.name.toLowerCase().includes(projectSearchTerm.toLowerCase()) ||
      (p.description || '').toLowerCase().includes(projectSearchTerm.toLowerCase()) ||
      (p.projectNumber || '').toLowerCase().includes(projectSearchTerm.toLowerCase())
    const matchesStatus = projectStatusFilter === 'all' || p.status === projectStatusFilter
    return matchesSearch && matchesStatus
  })

  // Project stats
  const projectsActive = projects.filter((p) => p.status === 'ACTIVE').length
  const projectsCompleted = projects.filter((p) => p.status === 'COMPLETED').length
  const projectsPlanning = projects.filter((p) => p.status === 'PLANNING').length

  // Calculate stats
  const completedTasks = tasks.filter(t => t.status === 'COMPLETED').length
  const inProgressTasks = tasks.filter(t => t.status === 'IN_PROGRESS').length
  const overdueTasks = tasks.filter(t => {
    if (!t.dueDate || t.status === 'COMPLETED') return false
    return new Date(t.dueDate) < new Date()
  }).length

  // Render Form Fields inline (extracted into a stable JSX expression below)
  // NOTE: We intentionally do NOT define FormFields as a component here.
  // Defining a component inside another component re-creates it on every
  // render, which makes React un-mount and re-mount the <input> elements
  // and causes the cursor / focus to be lost after every keystroke.
  const renderTaskFormFields = (isEdit: boolean) => (
    <div className="space-y-4">
      {/* Title */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          Task Title <span className="text-red-500">*</span>
        </label>
        <input
          type="text"
          value={formData.title}
          onChange={(e) => setFormData({ ...formData, title: e.target.value })}
          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
          placeholder="Enter task title"
        />
        {formErrors.title && <p className="text-red-500 text-xs mt-1">{formErrors.title}</p>}
      </div>

      {/* Description */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          Description
        </label>
        <textarea
          value={formData.description || ''}
          onChange={(e) => setFormData({ ...formData, description: e.target.value })}
          rows={3}
          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
          placeholder="Task description"
        />
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* Project */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Project
          </label>
          <div className="flex items-center gap-2">
            <select
              value={formData.projectId || ''}
              onChange={(e) => setFormData({ ...formData, projectId: e.target.value })}
              className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
              disabled={loadingProjects}
            >
              <option value="">No Project</option>
              {projects.map(proj => (
                <option key={proj.id} value={proj.id}>{proj.name}</option>
              ))}
            </select>
            {canCreateProject && (
              <button
                type="button"
                onClick={() => {
                  resetProjectForm()
                  setShowCreateProjectModal(true)
                }}
                className="shrink-0 flex items-center justify-center w-10 h-10 bg-orange-50 text-orange-700 border border-orange-200 rounded-lg hover:bg-orange-100"
                title="إضافة مشروع جديد - Add new project"
                aria-label="إضافة مشروع جديد"
              >
                <Plus className="h-4 w-4" />
              </button>
            )}
          </div>
        </div>

        {/* Priority */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Priority <span className="text-red-500">*</span>
          </label>
          <select
            value={formData.priority}
            onChange={(e) => setFormData({ ...formData, priority: e.target.value })}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
          >
            <option value="LOW">Low - منخفضة</option>
            <option value="MEDIUM">Medium - متوسطة</option>
            <option value="HIGH">High - عالية</option>
            <option value="CRITICAL">Critical - حرجة</option>
          </select>
          {formErrors.priority && <p className="text-red-500 text-xs mt-1">{formErrors.priority}</p>}
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* Status */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Status
          </label>
          <select
            value={formData.status}
            onChange={(e) => setFormData({ ...formData, status: e.target.value })}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
          >
            <option value="PENDING">Pending - قيد الانتظار</option>
            <option value="IN_PROGRESS">In Progress - قيد التنفيذ</option>
            <option value="REVIEW">Review - مراجعة</option>
            <option value="COMPLETED">Completed - مكتمل</option>
          </select>
        </div>

        {/* Progress */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Progress (%)
          </label>
          <input
            type="number"
            min="0"
            max="100"
            value={formData.progress || 0}
            onChange={(e) => setFormData({ ...formData, progress: parseInt(e.target.value) })}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
          />
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* Start Date */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Start Date
          </label>
          <input
            type="date"
            value={formData.startDate || ''}
            onChange={(e) => setFormData({ ...formData, startDate: e.target.value })}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
          />
        </div>

        {/* Due Date */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Due Date
          </label>
          <input
            type="date"
            value={formData.dueDate || ''}
            onChange={(e) => setFormData({ ...formData, dueDate: e.target.value })}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
          />
        </div>
      </div>

      {/* Estimated Hours */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          Estimated Hours
        </label>
        <input
          type="number"
          min="0"
          step="0.5"
          value={formData.estimatedHours || 0}
          onChange={(e) => setFormData({ ...formData, estimatedHours: parseFloat(e.target.value) })}
          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
        />
      </div>

      {/* Form Actions */}
      <div className="flex items-center justify-end gap-3 pt-4 border-t">
        <button
          type="button"
          onClick={() => {
            isEdit ? setShowEditModal(false) : setShowCreateModal(false)
            resetForm()
          }}
          className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
          disabled={submitting}
        >
          Cancel
        </button>
        <button
          type="submit"
          className="flex items-center gap-2 px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          disabled={submitting}
        >
          {submitting ? (
            <>
              <Loader2 className="h-4 w-4 animate-spin" />
              {isEdit ? 'Updating...' : 'Creating...'}
            </>
          ) : (
            <>
              {isEdit ? 'Update Task' : 'Create Task'}
            </>
          )}
        </button>
      </div>
    </div>
  )

  // Reusable project form fields (used by both Create and Edit project modals).
  // Same inline-render pattern as renderTaskFormFields to keep <input> focus stable.
  const renderProjectFormFields = (isEdit: boolean) => (
    <>
      {/* Name */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          Project Name <span className="text-red-500">*</span>
        </label>
        <input
          type="text"
          value={projectForm.name}
          onChange={(e) => setProjectForm({ ...projectForm, name: e.target.value })}
          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
          placeholder="Enter project name"
        />
        {projectFormErrors.name && (
          <p className="text-red-500 text-xs mt-1">{projectFormErrors.name}</p>
        )}
      </div>

      {/* Description */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">Description</label>
        <textarea
          value={projectForm.description || ''}
          onChange={(e) => setProjectForm({ ...projectForm, description: e.target.value })}
          rows={3}
          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
          placeholder="Project description"
        />
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* Type */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Type <span className="text-red-500">*</span>
          </label>
          <select
            value={projectForm.type}
            onChange={(e) => setProjectForm({ ...projectForm, type: e.target.value })}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
          >
            <option value="INTERNAL">Internal - داخلي</option>
            <option value="CLIENT">Client - عميل</option>
            <option value="IMPLEMENTATION">Implementation - تنفيذ</option>
            <option value="MAINTENANCE">Maintenance - صيانة</option>
            <option value="GOVERNMENT">Government - حكومي</option>
          </select>
          {projectFormErrors.type && (
            <p className="text-red-500 text-xs mt-1">{projectFormErrors.type}</p>
          )}
        </div>

        {/* Priority */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Priority</label>
          <select
            value={projectForm.priority || 'MEDIUM'}
            onChange={(e) => setProjectForm({ ...projectForm, priority: e.target.value })}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
          >
            <option value="LOW">Low - منخفضة</option>
            <option value="MEDIUM">Medium - متوسطة</option>
            <option value="HIGH">High - عالية</option>
            <option value="URGENT">Urgent - عاجلة</option>
          </select>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* Status */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Status</label>
          <select
            value={projectForm.status || 'PLANNING'}
            onChange={(e) => setProjectForm({ ...projectForm, status: e.target.value })}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
          >
            <option value="PLANNING">Planning - تخطيط</option>
            <option value="ACTIVE">Active - نشط</option>
            <option value="ON_HOLD">On Hold - متوقف</option>
            <option value="COMPLETED">Completed - مكتمل</option>
            <option value="CANCELLED">Cancelled - ملغى</option>
          </select>
        </div>

        {/* Estimated Cost */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Estimated Cost</label>
          <input
            type="number"
            min="0"
            step="0.01"
            value={projectForm.estimatedCost ?? ''}
            onChange={(e) =>
              setProjectForm({
                ...projectForm,
                estimatedCost: e.target.value === '' ? undefined : parseFloat(e.target.value),
              })
            }
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
            placeholder="0.00"
          />
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* Start Date */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Start Date <span className="text-red-500">*</span>
          </label>
          <input
            type="date"
            value={projectForm.startDate}
            onChange={(e) => setProjectForm({ ...projectForm, startDate: e.target.value })}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
          />
          {projectFormErrors.startDate && (
            <p className="text-red-500 text-xs mt-1">{projectFormErrors.startDate}</p>
          )}
        </div>

        {/* End Date */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">End Date</label>
          <input
            type="date"
            value={projectForm.endDate || ''}
            onChange={(e) => setProjectForm({ ...projectForm, endDate: e.target.value })}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
          />
          {projectFormErrors.endDate && (
            <p className="text-red-500 text-xs mt-1">{projectFormErrors.endDate}</p>
          )}
        </div>
      </div>

      {isEdit && (
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Progress (%)</label>
          <input
            type="number"
            min="0"
            max="100"
            value={projectForm.progress ?? 0}
            onChange={(e) =>
              setProjectForm({ ...projectForm, progress: parseInt(e.target.value) || 0 })
            }
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
          />
        </div>
      )}

      <div className="flex items-center justify-end gap-3 pt-4 border-t">
        <button
          type="button"
          onClick={() => {
            if (isEdit) {
              setShowEditProjectModal(false)
              setSelectedProjectForEdit(null)
            } else {
              setShowCreateProjectModal(false)
            }
            resetProjectForm()
          }}
          className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
          disabled={submittingProject}
        >
          Cancel
        </button>
        <button
          type="submit"
          className="flex items-center gap-2 px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          disabled={submittingProject}
        >
          {submittingProject ? (
            <>
              <Loader2 className="h-4 w-4 animate-spin" />
              {isEdit ? 'Updating...' : 'Creating...'}
            </>
          ) : isEdit ? (
            'Update Project'
          ) : (
            'Create Project'
          )}
        </button>
      </div>
    </>
  )

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <Link
                href="/dashboard"
                className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <ArrowLeft className="h-5 w-5 text-gray-600" />
              </Link>
              <div className="flex items-center gap-3">
                <div className="bg-orange-100 p-2 rounded-lg">
                  <CheckSquare className="h-6 w-6 text-orange-600" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-gray-900">المهام والمشاريع</h1>
                  <p className="text-sm text-gray-600">Tasks & Project Management</p>
                </div>
              </div>
            </div>

            <div className="flex items-center gap-3">
              {canCreateProject && (
                <button
                  onClick={() => {
                    resetProjectForm()
                    setShowCreateProjectModal(true)
                  }}
                  className="flex items-center gap-2 px-4 py-2 bg-white border border-orange-600 text-orange-700 rounded-lg hover:bg-orange-50 transition-colors"
                >
                  <Briefcase className="h-4 w-4" />
                  New Project
                </button>
              )}
              <button
                onClick={() => {
                  resetForm()
                  setShowCreateModal(true)
                }}
                className="flex items-center gap-2 px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700 transition-colors"
              >
                <Plus className="h-4 w-4" />
                New Task
              </button>
            </div>
          </div>

          {/* View Tabs - Tasks / Projects */}
          <div className="mt-4 flex items-center gap-1 border-b border-gray-200 -mb-px">
            <button
              onClick={() => setViewMode('tasks')}
              className={`flex items-center gap-2 px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${
                viewMode === 'tasks'
                  ? 'border-orange-600 text-orange-700'
                  : 'border-transparent text-gray-600 hover:text-gray-900'
              }`}
            >
              <ListTodo className="h-4 w-4" />
              <span>المهام</span>
              <span className="text-xs">/ Tasks</span>
              <span className="ml-1 px-2 py-0.5 bg-gray-100 text-gray-700 rounded-full text-xs">
                {total}
              </span>
            </button>
            <button
              onClick={() => setViewMode('projects')}
              className={`flex items-center gap-2 px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${
                viewMode === 'projects'
                  ? 'border-orange-600 text-orange-700'
                  : 'border-transparent text-gray-600 hover:text-gray-900'
              }`}
            >
              <FolderKanban className="h-4 w-4" />
              <span>المشاريع</span>
              <span className="text-xs">/ Projects</span>
              <span className="ml-1 px-2 py-0.5 bg-gray-100 text-gray-700 rounded-full text-xs">
                {projects.length}
              </span>
            </button>
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {viewMode === 'tasks' ? (
        <>
        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
          <div className="bg-white rounded-xl shadow-sm p-6 border border-gray-200">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Total Tasks</p>
                <p className="text-3xl font-bold text-gray-900 mt-1">{total}</p>
              </div>
              <div className="bg-blue-100 p-3 rounded-lg">
                <ListTodo className="h-8 w-8 text-blue-600" />
              </div>
            </div>
          </div>

          <div className="bg-white rounded-xl shadow-sm p-6 border border-gray-200">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">In Progress</p>
                <p className="text-3xl font-bold text-gray-900 mt-1">{inProgressTasks}</p>
                <p className="text-xs text-blue-600 mt-1">Active</p>
              </div>
              <div className="bg-orange-100 p-3 rounded-lg">
                <Clock className="h-8 w-8 text-orange-600" />
              </div>
            </div>
          </div>

          <div className="bg-white rounded-xl shadow-sm p-6 border border-gray-200">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Completed</p>
                <p className="text-3xl font-bold text-gray-900 mt-1">{completedTasks}</p>
                <p className="text-xs text-green-600 mt-1">
                  {total > 0 ? ((completedTasks / total) * 100).toFixed(0) : 0}% done
                </p>
              </div>
              <div className="bg-green-100 p-3 rounded-lg">
                <CheckCircle2 className="h-8 w-8 text-green-600" />
              </div>
            </div>
          </div>

          <div className="bg-white rounded-xl shadow-sm p-6 border border-gray-200">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Overdue</p>
                <p className="text-3xl font-bold text-gray-900 mt-1">{overdueTasks}</p>
                <p className="text-xs text-red-600 mt-1">Need attention</p>
              </div>
              <div className="bg-red-100 p-3 rounded-lg">
                <AlertTriangle className="h-8 w-8 text-red-600" />
              </div>
            </div>
          </div>
        </div>

        {/* Filters and Search */}
        <div className="bg-white rounded-xl shadow-sm p-6 border border-gray-200 mb-6">
          <div className="flex flex-col md:flex-row gap-4">
            {/* Search */}
            <div className="flex-1 relative">
              <Search className="absolute right-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400" />
              <input
                type="text"
                placeholder="Search tasks..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full pr-10 pl-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
              />
            </div>

            {/* Project Filter */}
            <select
              value={selectedProject}
              onChange={(e) => setSelectedProject(e.target.value)}
              className="px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
            >
              <option value="all">All Projects</option>
              {projects.map(proj => (
                <option key={proj.id} value={proj.id}>{proj.name}</option>
              ))}
            </select>

            {/* Priority Filter */}
            <select
              value={selectedPriority}
              onChange={(e) => setSelectedPriority(e.target.value)}
              className="px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
            >
              <option value="all">All Priorities</option>
              <option value="LOW">Low</option>
              <option value="MEDIUM">Medium</option>
              <option value="HIGH">High</option>
              <option value="CRITICAL">Critical</option>
            </select>

            {/* Status Filter */}
            <select
              value={selectedStatus}
              onChange={(e) => setSelectedStatus(e.target.value)}
              className="px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
            >
              <option value="all">All Status</option>
              <option value="PENDING">Pending</option>
              <option value="IN_PROGRESS">In Progress</option>
              <option value="REVIEW">Review</option>
              <option value="COMPLETED">Completed</option>
            </select>
          </div>
        </div>

        {/* Tasks Table */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
          {loading ? (
            <div className="p-12">
              <LoadingSpinner size="lg" message="Loading tasks..." />
            </div>
          ) : error ? (
            <div className="p-12 text-center">
              <p className="text-red-600 mb-4">{error}</p>
              <button
                onClick={fetchTasks}
                className="px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700"
              >
                Retry
              </button>
            </div>
          ) : tasks.length === 0 ? (
            <div className="p-12 text-center">
              <CheckSquare className="h-12 w-12 text-gray-400 mx-auto mb-4" />
              <p className="text-gray-600 mb-4">No tasks found</p>
              <button
                onClick={() => setShowCreateModal(true)}
                className="px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700"
              >
                Create First Task
              </button>
            </div>
          ) : (
            <>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-gray-50 border-b border-gray-200">
                    <tr>
                      <th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Task</th>
                      <th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Project</th>
                      <th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Priority</th>
                      <th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Status</th>
                      <th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Progress</th>
                      <th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Due Date</th>
                      <th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200">
                    {tasks.map((task) => (
                      <tr key={task.id} className="hover:bg-gray-50 transition-colors">
                        <td className="px-6 py-4">
                          <div>
                            <p className="font-semibold text-gray-900">{task.title}</p>
                            <p className="text-xs text-gray-600">{task.taskNumber}</p>
                          </div>
                        </td>
                        <td className="px-6 py-4">
                          <span className="text-sm text-gray-900">
                            {task.project?.name || 'No Project'}
                          </span>
                        </td>
                        <td className="px-6 py-4">
                          <span className={`inline-flex items-center px-3 py-1 rounded-full text-xs font-medium ${getPriorityColor(task.priority)}`}>
                            {task.priority}
                          </span>
                        </td>
                        <td className="px-6 py-4">
                          <span className={`inline-flex items-center px-3 py-1 rounded-full text-xs font-medium ${getStatusColor(task.status)}`}>
                            {task.status.replace('_', ' ')}
                          </span>
                        </td>
                        <td className="px-6 py-4">
                          <div className="flex items-center gap-2">
                            <div className="w-20 h-2 bg-gray-200 rounded-full overflow-hidden">
                              <div
                                className="h-full bg-orange-500 rounded-full"
                                style={{ width: `${task.progress}%` }}
                              />
                            </div>
                            <span className="text-sm text-gray-600">{task.progress}%</span>
                          </div>
                        </td>
                        <td className="px-6 py-4">
                          {task.dueDate && (
                            <div className="flex items-center gap-2">
                              <Calendar className="h-4 w-4 text-gray-400" />
                              <span className="text-sm text-gray-900">
                                {new Date(task.dueDate).toLocaleDateString()}
                              </span>
                            </div>
                          )}
                        </td>
                        <td className="px-6 py-4">
                          <div className="flex items-center gap-2">
                            {canEditTask && (
                              <button
                                onClick={() => openEditModal(task)}
                                className="p-2 hover:bg-green-50 text-green-600 rounded-lg transition-colors"
                                title="Edit"
                              >
                                <Edit className="h-4 w-4" />
                              </button>
                            )}
                            {canDeleteTask && (
                              <button
                                onClick={() => openDeleteDialog(task)}
                                className="p-2 hover:bg-red-50 text-red-600 rounded-lg transition-colors"
                                title="Delete"
                              >
                                <Trash2 className="h-4 w-4" />
                              </button>
                            )}
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* Pagination */}
              <div className="px-6 py-4 border-t border-gray-200 flex items-center justify-between">
                <p className="text-sm text-gray-600">
                  Showing <span className="font-semibold">{((currentPage - 1) * pageSize) + 1}</span> to{' '}
                  <span className="font-semibold">{Math.min(currentPage * pageSize, total)}</span> of{' '}
                  <span className="font-semibold">{total}</span> tasks
                </p>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => setCurrentPage(currentPage - 1)}
                    disabled={currentPage === 1}
                    className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    Previous
                  </button>
                  {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                    const page = i + 1
                    return (
                      <button
                        key={page}
                        onClick={() => setCurrentPage(page)}
                        className={`px-4 py-2 rounded-lg transition-colors ${
                          currentPage === page
                            ? 'bg-orange-600 text-white'
                            : 'border border-gray-300 text-gray-700 hover:bg-gray-50'
                        }`}
                      >
                        {page}
                      </button>
                    )
                  })}
                  {totalPages > 5 && <span className="px-2">...</span>}
                  <button
                    onClick={() => setCurrentPage(currentPage + 1)}
                    disabled={currentPage === totalPages}
                    className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    Next
                  </button>
                </div>
              </div>
            </>
          )}
        </div>
        </>
        ) : (
          /* ========== Projects View ========== */
          <>
            {/* Project Stats */}
            <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
              <div className="bg-white rounded-xl shadow-sm p-6 border border-gray-200">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600">إجمالي المشاريع - Total</p>
                    <p className="text-3xl font-bold text-gray-900 mt-1">{projects.length}</p>
                  </div>
                  <div className="bg-blue-100 p-3 rounded-lg">
                    <FolderKanban className="h-8 w-8 text-blue-600" />
                  </div>
                </div>
              </div>

              <div className="bg-white rounded-xl shadow-sm p-6 border border-gray-200">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600">نشط - Active</p>
                    <p className="text-3xl font-bold text-gray-900 mt-1">{projectsActive}</p>
                    <p className="text-xs text-blue-600 mt-1">In progress</p>
                  </div>
                  <div className="bg-orange-100 p-3 rounded-lg">
                    <Clock className="h-8 w-8 text-orange-600" />
                  </div>
                </div>
              </div>

              <div className="bg-white rounded-xl shadow-sm p-6 border border-gray-200">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600">تخطيط - Planning</p>
                    <p className="text-3xl font-bold text-gray-900 mt-1">{projectsPlanning}</p>
                    <p className="text-xs text-yellow-700 mt-1">Not started</p>
                  </div>
                  <div className="bg-yellow-100 p-3 rounded-lg">
                    <Layers className="h-8 w-8 text-yellow-600" />
                  </div>
                </div>
              </div>

              <div className="bg-white rounded-xl shadow-sm p-6 border border-gray-200">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600">مكتمل - Completed</p>
                    <p className="text-3xl font-bold text-gray-900 mt-1">{projectsCompleted}</p>
                    <p className="text-xs text-green-600 mt-1">
                      {projects.length > 0
                        ? ((projectsCompleted / projects.length) * 100).toFixed(0)
                        : 0}
                      % done
                    </p>
                  </div>
                  <div className="bg-green-100 p-3 rounded-lg">
                    <CheckCircle2 className="h-8 w-8 text-green-600" />
                  </div>
                </div>
              </div>
            </div>

            {/* Project Filters */}
            <div className="bg-white rounded-xl shadow-sm p-6 border border-gray-200 mb-6">
              <div className="flex flex-col md:flex-row gap-4">
                <div className="flex-1 relative">
                  <Search className="absolute right-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400" />
                  <input
                    type="text"
                    placeholder="ابحث في المشاريع... / Search projects..."
                    value={projectSearchTerm}
                    onChange={(e) => setProjectSearchTerm(e.target.value)}
                    className="w-full pr-10 pl-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
                  />
                </div>
                <select
                  value={projectStatusFilter}
                  onChange={(e) => setProjectStatusFilter(e.target.value)}
                  className="px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500"
                >
                  <option value="all">All Status - الكل</option>
                  <option value="PLANNING">Planning - تخطيط</option>
                  <option value="ACTIVE">Active - نشط</option>
                  <option value="ON_HOLD">On Hold - متوقف</option>
                  <option value="COMPLETED">Completed - مكتمل</option>
                  <option value="CANCELLED">Cancelled - ملغى</option>
                </select>
              </div>
            </div>

            {/* Projects Grid */}
            {loadingProjects ? (
              <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-12">
                <LoadingSpinner size="lg" message="Loading projects..." />
              </div>
            ) : filteredProjects.length === 0 ? (
              <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-12 text-center">
                <FolderKanban className="h-12 w-12 text-gray-400 mx-auto mb-4" />
                <p className="text-gray-600 mb-4">
                  {projects.length === 0
                    ? 'لا توجد مشاريع - No projects found'
                    : 'لا توجد مشاريع مطابقة - No matching projects'}
                </p>
                {canCreateProject && projects.length === 0 && (
                  <button
                    onClick={() => {
                      resetProjectForm()
                      setShowCreateProjectModal(true)
                    }}
                    className="inline-flex items-center gap-2 px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700"
                  >
                    <Plus className="h-4 w-4" />
                    إنشاء أول مشروع - Create First Project
                  </button>
                )}
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {filteredProjects.map((project) => {
                  const taskCount = tasksCountByProject[project.id] || 0
                  const progress = project.progress ?? 0
                  return (
                    <div
                      key={project.id}
                      className="bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-md transition-shadow flex flex-col"
                    >
                      {/* Card header */}
                      <div className="flex items-start justify-between mb-3">
                        <div className="flex items-center gap-3 min-w-0">
                          <div className="bg-orange-100 p-2 rounded-lg shrink-0">
                            <Briefcase className="h-5 w-5 text-orange-600" />
                          </div>
                          <div className="min-w-0">
                            <h3 className="font-semibold text-gray-900 truncate" title={project.name}>
                              {project.name}
                            </h3>
                            {project.projectNumber && (
                              <p className="text-xs text-gray-500 truncate">
                                {project.projectNumber}
                              </p>
                            )}
                          </div>
                        </div>
                        <span
                          className={`shrink-0 inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium ${getProjectStatusColor(
                            project.status,
                          )}`}
                        >
                          {getProjectStatusLabel(project.status)}
                        </span>
                      </div>

                      {/* Description */}
                      {project.description ? (
                        <p className="text-sm text-gray-600 mb-4 line-clamp-2">
                          {project.description}
                        </p>
                      ) : (
                        <p className="text-sm text-gray-400 italic mb-4">No description</p>
                      )}

                      {/* Meta row */}
                      <div className="flex flex-wrap items-center gap-2 mb-4 text-xs">
                        {project.type && (
                          <span className="inline-flex items-center gap-1 px-2 py-1 bg-gray-100 text-gray-700 rounded">
                            <Layers className="h-3 w-3" />
                            {getProjectTypeLabel(project.type)}
                          </span>
                        )}
                        {project.priority && (
                          <span
                            className={`inline-flex items-center gap-1 px-2 py-1 rounded ${getPriorityColor(
                              project.priority,
                            )}`}
                          >
                            <Flag className="h-3 w-3" />
                            {project.priority}
                          </span>
                        )}
                        <span className="inline-flex items-center gap-1 px-2 py-1 bg-blue-50 text-blue-700 rounded">
                          <ListTodo className="h-3 w-3" />
                          {taskCount} {taskCount === 1 ? 'task' : 'tasks'}
                        </span>
                      </div>

                      {/* Progress bar */}
                      <div className="mb-4">
                        <div className="flex items-center justify-between text-xs mb-1">
                          <span className="text-gray-600">Progress</span>
                          <span className="font-medium text-gray-900">{progress}%</span>
                        </div>
                        <div className="w-full h-2 bg-gray-200 rounded-full overflow-hidden">
                          <div
                            className="h-full bg-orange-500 rounded-full transition-all"
                            style={{ width: `${progress}%` }}
                          />
                        </div>
                      </div>

                      {/* Footer: dates + cost */}
                      <div className="mt-auto pt-3 border-t border-gray-100 space-y-1.5 text-xs text-gray-600">
                        {project.startDate && (
                          <div className="flex items-center gap-1.5">
                            <Calendar className="h-3.5 w-3.5 text-gray-400" />
                            <span>Start: {new Date(project.startDate).toLocaleDateString()}</span>
                          </div>
                        )}
                        {project.endDate && (
                          <div className="flex items-center gap-1.5">
                            <Clock className="h-3.5 w-3.5 text-gray-400" />
                            <span>End: {new Date(project.endDate).toLocaleDateString()}</span>
                          </div>
                        )}
                        {project.estimatedCost != null && (
                          <div className="flex items-center gap-1.5">
                            <DollarSign className="h-3.5 w-3.5 text-gray-400" />
                            <span>
                              Estimated:{' '}
                              {Number(project.estimatedCost).toLocaleString(undefined, {
                                minimumFractionDigits: 2,
                                maximumFractionDigits: 2,
                              })}
                            </span>
                          </div>
                        )}
                      </div>

                      {/* Quick action: view its tasks + edit/delete (when permitted) */}
                      <div className="mt-4 flex items-center gap-2">
                        <button
                          onClick={() => {
                            setSelectedProject(project.id)
                            setViewMode('tasks')
                          }}
                          className="flex-1 flex items-center justify-center gap-2 px-3 py-2 text-sm bg-orange-50 text-orange-700 border border-orange-200 rounded-lg hover:bg-orange-100 transition-colors"
                        >
                          <ListTodo className="h-4 w-4" />
                          <span>عرض المهام</span>
                        </button>
                        {canEditProject && (
                          <button
                            onClick={() => openEditProjectModal(project)}
                            className="p-2 text-green-600 border border-green-200 bg-green-50 rounded-lg hover:bg-green-100 transition-colors"
                            title="تعديل - Edit"
                          >
                            <Edit className="h-4 w-4" />
                          </button>
                        )}
                        {canDeleteProject && (
                          <button
                            onClick={() => openDeleteProjectDialog(project)}
                            className="p-2 text-red-600 border border-red-200 bg-red-50 rounded-lg hover:bg-red-100 transition-colors"
                            title="حذف - Delete"
                          >
                            <Trash2 className="h-4 w-4" />
                          </button>
                        )}
                      </div>
                    </div>
                  )
                })}
              </div>
            )}
          </>
        )}
      </main>

      {/* Create Modal */}
      <Modal
        isOpen={showCreateModal}
        onClose={() => {
          setShowCreateModal(false)
          resetForm()
        }}
        title="Create New Task"
        size="xl"
      >
        <form onSubmit={handleCreate}>
          {renderTaskFormFields(false)}
        </form>
      </Modal>

      {/* Project Create Modal */}
      <Modal
        isOpen={showCreateProjectModal}
        onClose={() => {
          setShowCreateProjectModal(false)
          resetProjectForm()
        }}
        title="إنشاء مشروع جديد - Create New Project"
        size="lg"
      >
        <form onSubmit={handleCreateProject} className="space-y-4">
          {renderProjectFormFields(false)}
        </form>
      </Modal>

      {/* Project Edit Modal */}
      <Modal
        isOpen={showEditProjectModal}
        onClose={() => {
          setShowEditProjectModal(false)
          setSelectedProjectForEdit(null)
          resetProjectForm()
        }}
        title="تعديل المشروع - Edit Project"
        size="lg"
      >
        <form onSubmit={handleUpdateProject} className="space-y-4">
          {renderProjectFormFields(true)}
        </form>
      </Modal>

      {/* Project Delete Confirmation Dialog */}
      {showDeleteProjectDialog && selectedProjectForEdit && (
        <div className="fixed inset-0 z-50 overflow-y-auto">
          <div
            className="fixed inset-0 bg-black bg-opacity-50"
            onClick={() => setShowDeleteProjectDialog(false)}
          />
          <div className="flex min-h-screen items-center justify-center p-4">
            <div className="relative bg-white rounded-xl shadow-2xl p-6 max-w-md w-full">
              <div className="flex items-center gap-4 mb-4">
                <div className="bg-red-100 p-3 rounded-full">
                  <Trash2 className="h-6 w-6 text-red-600" />
                </div>
                <div>
                  <h3 className="text-lg font-bold text-gray-900">حذف المشروع - Delete Project</h3>
                  <p className="text-sm text-gray-600">This action cannot be undone</p>
                </div>
              </div>
              <p className="text-gray-700 mb-2">
                هل أنت متأكد من حذف المشروع{' '}
                <span className="font-semibold">{selectedProjectForEdit.name}</span>؟
              </p>
              <p className="text-xs text-gray-500 mb-6">
                لن يتم حذف المشروع إذا كان مرتبطاً بمهام أو بيانات أخرى.
              </p>
              <div className="flex items-center justify-end gap-3">
                <button
                  onClick={() => {
                    setShowDeleteProjectDialog(false)
                    setSelectedProjectForEdit(null)
                  }}
                  className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                  disabled={submittingProject}
                >
                  Cancel
                </button>
                <button
                  onClick={handleDeleteProject}
                  className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50"
                  disabled={submittingProject}
                >
                  {submittingProject ? (
                    <>
                      <Loader2 className="h-4 w-4 animate-spin" />
                      Deleting...
                    </>
                  ) : (
                    'Delete Project'
                  )}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Edit Modal */}
      <Modal
        isOpen={showEditModal}
        onClose={() => {
          setShowEditModal(false)
          resetForm()
        }}
        title="Edit Task"
        size="xl"
      >
        <form onSubmit={handleEdit}>
          {renderTaskFormFields(true)}
        </form>
      </Modal>

      {/* Delete Confirmation Dialog */}
      {showDeleteDialog && selectedTask && (
        <div className="fixed inset-0 z-50 overflow-y-auto">
          <div className="fixed inset-0 bg-black bg-opacity-50" onClick={() => setShowDeleteDialog(false)} />
          <div className="flex min-h-screen items-center justify-center p-4">
            <div className="relative bg-white rounded-xl shadow-2xl p-6 max-w-md w-full">
              <div className="flex items-center gap-4 mb-4">
                <div className="bg-red-100 p-3 rounded-full">
                  <Trash2 className="h-6 w-6 text-red-600" />
                </div>
                <div>
                  <h3 className="text-lg font-bold text-gray-900">Delete Task</h3>
                  <p className="text-sm text-gray-600">This action cannot be undone</p>
                </div>
              </div>
              <p className="text-gray-700 mb-6">
                Are you sure you want to delete <span className="font-semibold">{selectedTask.title}</span>?
              </p>
              <div className="flex items-center justify-end gap-3">
                <button
                  onClick={() => {
                    setShowDeleteDialog(false)
                    setSelectedTask(null)
                  }}
                  className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
                  disabled={submitting}
                >
                  Cancel
                </button>
                <button
                  onClick={handleDelete}
                  className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50"
                  disabled={submitting}
                >
                  {submitting ? (
                    <>
                      <Loader2 className="h-4 w-4 animate-spin" />
                      Deleting...
                    </>
                  ) : (
                    'Delete Task'
                  )}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default function ProjectsPage() {
  return (
    <ProtectedRoute>
      <ProjectsContent />
    </ProtectedRoute>
  )
}
