'use client';

import { useState } from 'react';

interface DeletePageModalProps {
  pageId: number;
  slug: string;
  pageTitle: string;
  onClose: () => void;
  onSuccess: () => void;
}

export function DeletePageModal({ pageId, slug, pageTitle, onClose, onSuccess }: DeletePageModalProps) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleDelete = async () => {
    setLoading(true);
    setError('');
    try {
      const res = await fetch(`/api/custom-pages?id=${pageId}&slug=${slug}`, {
        method: 'DELETE',
      });
      const data = await res.json();
      
      if (!res.ok) throw new Error(data.error || 'Failed to delete page');
      
      onSuccess();
    } catch (err: any) {
      setError(err.message);
      setLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[100]">
      <div className="bg-white p-6 rounded-lg shadow-xl w-full max-w-sm max-h-[90vh] overflow-y-auto">
        <div className="flex items-center gap-3 mb-4 text-red-600">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M3 6h18"></path>
            <path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"></path>
            <path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"></path>
          </svg>
          <h2 className="text-xl font-bold text-gray-800">Delete Page</h2>
        </div>
        
        {error && <div className="mb-4 text-red-500 text-sm">{error}</div>}
        
        <p className="text-gray-700 mb-6 text-sm">
          Are you sure you want to permanently delete <strong>{pageTitle}</strong>? This will remove the page, its content, and all associated navigation links. This action cannot be undone.
        </p>

        <div className="flex justify-end gap-3 mt-4">
          <button 
            type="button" 
            onClick={onClose} 
            disabled={loading}
            className="px-4 py-2 border rounded text-sm hover:bg-gray-50"
          >
            Cancel
          </button>
          <button 
            type="button" 
            onClick={handleDelete}
            disabled={loading} 
            className="px-4 py-2 bg-red-600 text-white rounded text-sm hover:bg-red-700 disabled:opacity-50"
          >
            {loading ? 'Deleting...' : 'Delete Page'}
          </button>
        </div>
      </div>
    </div>
  );
}
