'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 {
  Megaphone,
  Plus,
  Search,
  DollarSign,
  TrendingUp,
  Target,
  BarChart3,
  ArrowLeft,
  Calendar,
  Mail,
  MessageSquare,
  Share2,
  Edit,
  Trash2,
  Loader2,
  PlayCircle,
  PauseCircle,
  CheckCircle2,
  XCircle
} from 'lucide-react'
import { campaignsAPI, Campaign, CreateCampaignData, UpdateCampaignData, CampaignFilters } from '@/lib/api/campaigns'

function MarketingContent() {
  // State Management
  const [campaigns, setCampaigns] = useState<Campaign[]>([])
  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 [selectedType, setSelectedType] = useState('all')
  const [selectedStatus, setSelectedStatus] = useState('all')

  // Modals
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [showEditModal, setShowEditModal] = useState(false)
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [selectedCampaign, setSelectedCampaign] = useState<Campaign | null>(null)

  // Form Data
  const [formData, setFormData] = useState<CreateCampaignData>({
    name: '',
    nameAr: '',
    type: 'EMAIL',
    description: '',
    budget: 0,
    expectedROI: 0,
    startDate: '',
    endDate: ''
  })
  const [formErrors, setFormErrors] = useState<Record<string, string>>({})
  const [submitting, setSubmitting] = useState(false)

  // Fetch Campaigns (with debouncing for search)
  const fetchCampaigns = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const filters: CampaignFilters = {
        page: currentPage,
        pageSize,
      }
      
      if (searchTerm) filters.search = searchTerm
      if (selectedType !== 'all') filters.type = selectedType
      if (selectedStatus !== 'all') filters.status = selectedStatus

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

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

  // Fetch on filter/page change
  useEffect(() => {
    fetchCampaigns()
  }, [currentPage, selectedType, selectedStatus])

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

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

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

    setSubmitting(true)
    try {
      await campaignsAPI.create(formData)
      toast.success('Campaign created successfully!')
      setShowCreateModal(false)
      resetForm()
      fetchCampaigns()
    } catch (err: any) {
      const message = err.response?.data?.message || 'Failed to create campaign'
      toast.error(message)
    } finally {
      setSubmitting(false)
    }
  }

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

    setSubmitting(true)
    try {
      await campaignsAPI.update(selectedCampaign.id, formData as UpdateCampaignData)
      toast.success('Campaign updated successfully!')
      setShowEditModal(false)
      resetForm()
      fetchCampaigns()
    } catch (err: any) {
      const message = err.response?.data?.message || 'Failed to update campaign'
      toast.error(message)
    } finally {
      setSubmitting(false)
    }
  }

  // Delete Campaign
  const handleDelete = async () => {
    if (!selectedCampaign) return

    setSubmitting(true)
    try {
      await campaignsAPI.delete(selectedCampaign.id)
      toast.success('Campaign deleted successfully!')
      setShowDeleteDialog(false)
      setSelectedCampaign(null)
      fetchCampaigns()
    } catch (err: any) {
      const message = err.response?.data?.message || 'Failed to delete campaign'
      toast.error(message)
    } finally {
      setSubmitting(false)
    }
  }

  // Utility Functions
  const resetForm = () => {
    setFormData({
      name: '',
      nameAr: '',
      type: 'EMAIL',
      description: '',
      budget: 0,
      expectedROI: 0,
      startDate: '',
      endDate: ''
    })
    setFormErrors({})
    setSelectedCampaign(null)
  }

  const openEditModal = (campaign: Campaign) => {
    setSelectedCampaign(campaign)
    setFormData({
      name: campaign.name,
      nameAr: campaign.nameAr,
      type: campaign.type,
      description: campaign.description,
      budget: campaign.budget,
      expectedROI: campaign.expectedROI,
      startDate: campaign.startDate?.split('T')[0],
      endDate: campaign.endDate?.split('T')[0]
    })
    setShowEditModal(true)
  }

  const openDeleteDialog = (campaign: Campaign) => {
    setSelectedCampaign(campaign)
    setShowDeleteDialog(true)
  }

  const getTypeIcon = (type: string) => {
    const icons: Record<string, any> = {
      EMAIL: Mail,
      WHATSAPP: MessageSquare,
      SOCIAL: Share2,
      EXHIBITION: Target,
      MULTI_CHANNEL: BarChart3
    }
    return icons[type] || Mail
  }

  const getTypeColor = (type: string) => {
    const colors: Record<string, string> = {
      EMAIL: 'bg-blue-100 text-blue-700',
      WHATSAPP: 'bg-green-100 text-green-700',
      SOCIAL: 'bg-purple-100 text-purple-700',
      EXHIBITION: 'bg-orange-100 text-orange-700',
      MULTI_CHANNEL: 'bg-pink-100 text-pink-700'
    }
    return colors[type] || 'bg-gray-100 text-gray-700'
  }

  const getStatusColor = (status: string) => {
    const colors: Record<string, string> = {
      PLANNED: 'bg-gray-100 text-gray-700',
      ACTIVE: 'bg-green-100 text-green-700',
      PAUSED: 'bg-orange-100 text-orange-700',
      COMPLETED: 'bg-blue-100 text-blue-700',
      CANCELLED: 'bg-red-100 text-red-700'
    }
    return colors[status] || 'bg-gray-100 text-gray-700'
  }

  // Calculate stats
  const totalBudget = campaigns.reduce((sum, c) => sum + (c.budget || 0), 0)
  const totalCost = campaigns.reduce((sum, c) => sum + (c.actualCost || 0), 0)
  const activeCampaigns = campaigns.filter(c => c.status === 'ACTIVE').length
  const completedCampaigns = campaigns.filter(c => c.status === 'COMPLETED').length

  // Render Form Fields Component
  const FormFields = ({ isEdit = false }: { isEdit?: boolean }) => (
    <div className="space-y-4">
      {/* Name */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          Campaign Name <span className="text-red-500">*</span>
        </label>
        <input
          type="text"
          value={formData.name}
          onChange={(e) => setFormData({ ...formData, 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-pink-500"
          placeholder="Enter campaign name"
        />
        {formErrors.name && <p className="text-red-500 text-xs mt-1">{formErrors.name}</p>}
      </div>

      {/* Arabic Name */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          Arabic Name - الاسم بالعربية
        </label>
        <input
          type="text"
          value={formData.nameAr || ''}
          onChange={(e) => setFormData({ ...formData, nameAr: e.target.value })}
          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-pink-500"
          placeholder="أدخل الاسم بالعربية"
          dir="rtl"
        />
      </div>

      {/* Type */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          Campaign Type <span className="text-red-500">*</span>
        </label>
        <select
          value={formData.type}
          onChange={(e) => setFormData({ ...formData, 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-pink-500"
        >
          <option value="EMAIL">Email - بريد إلكتروني</option>
          <option value="WHATSAPP">WhatsApp - واتساب</option>
          <option value="SOCIAL">Social Media - وسائل التواصل</option>
          <option value="EXHIBITION">Exhibition - معرض</option>
          <option value="MULTI_CHANNEL">Multi-Channel - متعدد القنوات</option>
        </select>
        {formErrors.type && <p className="text-red-500 text-xs mt-1">{formErrors.type}</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-pink-500"
          placeholder="Campaign description"
        />
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* Budget */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Budget (SAR)
          </label>
          <input
            type="number"
            min="0"
            value={formData.budget || 0}
            onChange={(e) => setFormData({ ...formData, budget: 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-pink-500"
          />
        </div>

        {/* Expected ROI */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Expected ROI (%)
          </label>
          <input
            type="number"
            min="0"
            step="0.1"
            value={formData.expectedROI || 0}
            onChange={(e) => setFormData({ ...formData, expectedROI: 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-pink-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-pink-500"
          />
        </div>

        {/* End Date */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            End Date
          </label>
          <input
            type="date"
            value={formData.endDate || ''}
            onChange={(e) => setFormData({ ...formData, 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-pink-500"
          />
        </div>
      </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-pink-600 text-white rounded-lg hover:bg-pink-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 Campaign' : 'Create Campaign'}
            </>
          )}
        </button>
      </div>
    </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-pink-100 p-2 rounded-lg">
                  <Megaphone className="h-6 w-6 text-pink-600" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-gray-900">إدارة التسويق</h1>
                  <p className="text-sm text-gray-600">Marketing Management</p>
                </div>
              </div>
            </div>

            <div className="flex items-center gap-3">
              <button
                onClick={() => {
                  resetForm()
                  setShowCreateModal(true)
                }}
                className="flex items-center gap-2 px-4 py-2 bg-pink-600 text-white rounded-lg hover:bg-pink-700 transition-colors"
              >
                <Plus className="h-4 w-4" />
                New Campaign
              </button>
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* 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 Campaigns</p>
                <p className="text-3xl font-bold text-gray-900 mt-1">{total}</p>
              </div>
              <div className="bg-blue-100 p-3 rounded-lg">
                <Megaphone 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">Total Budget</p>
                <p className="text-3xl font-bold text-gray-900 mt-1">
                  {(totalBudget / 1000).toFixed(0)}K
                </p>
                <p className="text-xs text-gray-600 mt-1">SAR</p>
              </div>
              <div className="bg-green-100 p-3 rounded-lg">
                <DollarSign 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">Active</p>
                <p className="text-3xl font-bold text-gray-900 mt-1">{activeCampaigns}</p>
                <p className="text-xs text-orange-600 mt-1">Running now</p>
              </div>
              <div className="bg-orange-100 p-3 rounded-lg">
                <PlayCircle 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">{completedCampaigns}</p>
                <p className="text-xs text-green-600 mt-1">
                  {total > 0 ? ((completedCampaigns / total) * 100).toFixed(0) : 0}% rate
                </p>
              </div>
              <div className="bg-purple-100 p-3 rounded-lg">
                <CheckCircle2 className="h-8 w-8 text-purple-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 campaigns..."
                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-pink-500"
              />
            </div>

            {/* Type Filter */}
            <select
              value={selectedType}
              onChange={(e) => setSelectedType(e.target.value)}
              className="px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-pink-500"
            >
              <option value="all">All Types</option>
              <option value="EMAIL">Email</option>
              <option value="WHATSAPP">WhatsApp</option>
              <option value="SOCIAL">Social Media</option>
              <option value="EXHIBITION">Exhibition</option>
              <option value="MULTI_CHANNEL">Multi-Channel</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-pink-500"
            >
              <option value="all">All Status</option>
              <option value="PLANNED">Planned</option>
              <option value="ACTIVE">Active</option>
              <option value="PAUSED">Paused</option>
              <option value="COMPLETED">Completed</option>
              <option value="CANCELLED">Cancelled</option>
            </select>
          </div>
        </div>

        {/* Campaigns 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 campaigns..." />
            </div>
          ) : error ? (
            <div className="p-12 text-center">
              <p className="text-red-600 mb-4">{error}</p>
              <button
                onClick={fetchCampaigns}
                className="px-4 py-2 bg-pink-600 text-white rounded-lg hover:bg-pink-700"
              >
                Retry
              </button>
            </div>
          ) : campaigns.length === 0 ? (
            <div className="p-12 text-center">
              <Megaphone className="h-12 w-12 text-gray-400 mx-auto mb-4" />
              <p className="text-gray-600 mb-4">No campaigns found</p>
              <button
                onClick={() => setShowCreateModal(true)}
                className="px-4 py-2 bg-pink-600 text-white rounded-lg hover:bg-pink-700"
              >
                Create First Campaign
              </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">Campaign</th>
                      <th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Type</th>
                      <th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Budget</th>
                      <th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Expected ROI</th>
                      <th className="px-6 py-4 text-right text-xs font-semibold text-gray-700 uppercase">Dates</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">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200">
                    {campaigns.map((campaign) => {
                      const TypeIcon = getTypeIcon(campaign.type)
                      return (
                        <tr key={campaign.id} className="hover:bg-gray-50 transition-colors">
                          <td className="px-6 py-4">
                            <div>
                              <p className="font-semibold text-gray-900">{campaign.name}</p>
                              <p className="text-xs text-gray-600">{campaign.campaignNumber}</p>
                            </div>
                          </td>
                          <td className="px-6 py-4">
                            <span className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-medium ${getTypeColor(campaign.type)}`}>
                              <TypeIcon className="h-3 w-3" />
                              {campaign.type.replace('_', ' ')}
                            </span>
                          </td>
                          <td className="px-6 py-4">
                            <div>
                              <span className="text-sm font-semibold text-gray-900">
                                {(campaign.budget || 0).toLocaleString()} SAR
                              </span>
                              {(campaign.actualCost ?? 0) > 0 && (
                                <p className="text-xs text-gray-600">
                                  Spent: {(campaign.actualCost ?? 0).toLocaleString()}
                                </p>
                              )}
                            </div>
                          </td>
                          <td className="px-6 py-4">
                            <span className="text-sm text-gray-900">
                              {campaign.expectedROI || 0}%
                            </span>
                          </td>
                          <td className="px-6 py-4">
                            <div className="text-sm text-gray-600">
                              {campaign.startDate && (
                                <div>{new Date(campaign.startDate).toLocaleDateString()}</div>
                              )}
                              {campaign.endDate && (
                                <div className="text-xs">to {new Date(campaign.endDate).toLocaleDateString()}</div>
                              )}
                            </div>
                          </td>
                          <td className="px-6 py-4">
                            <span className={`inline-flex items-center px-3 py-1 rounded-full text-xs font-medium ${getStatusColor(campaign.status)}`}>
                              {campaign.status}
                            </span>
                          </td>
                          <td className="px-6 py-4">
                            <div className="flex items-center gap-2">
                              <button 
                                onClick={() => openEditModal(campaign)}
                                className="p-2 hover:bg-green-50 text-green-600 rounded-lg transition-colors"
                                title="Edit"
                              >
                                <Edit className="h-4 w-4" />
                              </button>
                              <button 
                                onClick={() => openDeleteDialog(campaign)}
                                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> campaigns
                </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-pink-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>
      </main>

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

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

      {/* Delete Confirmation Dialog */}
      {showDeleteDialog && selectedCampaign && (
        <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 Campaign</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">{selectedCampaign.name}</span>?
              </p>
              <div className="flex items-center justify-end gap-3">
                <button
                  onClick={() => {
                    setShowDeleteDialog(false)
                    setSelectedCampaign(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 Campaign'
                  )}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default function MarketingPage() {
  return (
    <ProtectedRoute>
      <MarketingContent />
    </ProtectedRoute>
  )
}
