// src/components/permissions/PermissionForm.tsx
'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import toast from 'react-hot-toast';
import { getApiErrorMessage } from '@/lib/utils/apiError';

interface PermissionData {
  id: string;
  name: string;
  description: string;
  module: string;
  action: string;
  [key: string]: unknown;
}

interface PermissionFormProps {
  mode: 'create' | 'edit';
  initialData?: PermissionData | null;
}

export default function PermissionForm({ mode, initialData }: PermissionFormProps) {
  const router = useRouter();
  const isEditing = mode === 'edit';
  
  const [formData, setFormData] = useState({
    name: initialData?.name || '',
    description: initialData?.description || '',
    module: initialData?.module || '',
    action: initialData?.action || '',
  });
  
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  
  const actions = [
    { value: 'read', label: 'Read' },
    { value: 'create', label: 'Create' },
    { value: 'update', label: 'Update' },
    { value: 'delete', label: 'Delete' },
    { value: 'bulkdelete', label: 'Bulk Delete' },
    { value: 'active_deactive', label: 'Activate/Deactivate' },
    { value: 'view_deleted', label: 'View Deleted Rows' },
    { value: 'delete_permanent', label: 'Delete Permanently' },
    { value: 'restore', label: 'Restore Data' },
    { value: 'restore_permanent', label: 'Bulk Restore' },
    { value: 'popularity', label: 'Popularity' },
    { value: 'view_timeline', label: 'View Timeline' },
    { value: 'manage_overrides', label: 'Manage Overrides' },
    { value: 'change_password', label: 'Change Password' },
    { value: 'approve', label: 'Approve' },
    { value: 'reject', label: 'Reject' },
    { value: 'export', label: 'Export' },
    { value: 'import', label: 'Import' },
    { value: 'change_status', label: 'Change Status' },
    { value: 'merked_featured', label: 'Marked Featured' },
    { value: 'logout_devices', label: 'Logout Devices' },
    { value: 'set_default', label: 'Set Default' },
    { value: 'order_cancel', label: 'Cancel Order' },
    { value: 'refund_return', label: 'Refund Order' },
    { value: 'single_item_status', label: 'Single Item Status' },
    { value: 'view_payment', label: 'View Payment' },
    { value: 'manage_payments', label: 'Manage Payments' },
    { value: 'delete_payments', label: 'Delete Payments' },
    { value: 'view_deleted_payments', label: 'View Deleted Payments' },
    { value: 'permanent_delete_payments', label: 'Permanent Delete Payments' },
    { value: 'payment-timeline', label: 'Payment Timeline' },
    { value: 'restore-payments', label: 'Restore Payments' },
    { value: 'bulk_update', label: 'Bulk Update' },
    { value: 'view_analytics', label: 'View Analytics' },
    { value: 'menu_reorder', label: 'Menu Reorder' },

    
  ];
  
  const handleChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: '' }));
    }
  };
  
  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setErrors({});
    setLoading(true);
    
    try {
      const url = isEditing ? `/api/permissions/${initialData?.id}` : '/api/permissions';
      const method = isEditing ? 'PUT' : 'POST';
      
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      });
      
      const data = await res.json();
      
      if (!res.ok || !data.success) {
        if (data.errors) {
          const fieldErrors: Record<string, string> = {};
          data.errors.forEach((err: { path: string[]; message: string }) => {
            fieldErrors[err.path[0]] = err.message;
          });
          setErrors(fieldErrors);
          toast.error('Please fix the validation errors');
        } else {
          toast.error(getApiErrorMessage(data, 'Failed to save permission'));
        }
        return;
      }
      
      toast.success(data.message || (isEditing ? 'Permission updated successfully' : 'Permission created successfully'));
      router.push('/admin/dashboard/employees/permissions');
      router.refresh();
    } catch (err) {
      console.error('[PermissionForm]', err);
      toast.error('Network error — please try again');
    } finally {
      setLoading(false);
    }
  }
  
  // Form styles - Left aligned with proper max width
  const formStyles = {
    background: 'var(--color-surface)',
    border: '1px solid var(--color-border)',
    borderRadius: 'var(--radius-card)',
    boxShadow: 'var(--shadow-card-md)',
    width: '100%',
    maxWidth: '800px', // Form won't go beyond this width
  };
  
  const inputStyle = {
    background: 'var(--color-surface-alt)',
    border: '1px solid var(--color-border)',
    color: 'var(--color-text)',
  };
  
  const labelStyle = {
    color: 'var(--color-text-secondary)',
  };
  
  const errorStyle = {
    color: 'var(--color-danger)',
  };
  
  return (
    <div style={formStyles} className="p-6 md:p-8">
      <form onSubmit={handleSubmit}>
        <div className="space-y-6">
          <div>
            <label htmlFor="name" className="block text-sm font-medium mb-1.5" style={labelStyle}>
              Permission Name <span className="text-red-500">*</span>
            </label>
            <input
              id="name"
              type="text"
              required
              value={formData.name}
              onChange={(e) => handleChange('name', e.target.value)}
              placeholder="e.g., employees:read"
              className={`w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 ${errors.name ? 'border-red-500' : ''}`}
              style={inputStyle}
            />
            {errors.name && <p className="text-xs mt-1" style={errorStyle}>{errors.name}</p>}
            <p className="text-xs mt-1" style={{ color: 'var(--color-text-muted)' }}>
              Format: module:action (e.g., employees:read)
            </p>
          </div>
          
          <div>
            <label htmlFor="module" className="block text-sm font-medium mb-1.5" style={labelStyle}>
              Module <span className="text-red-500">*</span>
            </label>
            <input
              id="module"
              type="text"
              required
              value={formData.module}
              onChange={(e) => handleChange('module', e.target.value.toLowerCase())}
              placeholder="e.g., employees, roles, permissions"
              className={`w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 ${errors.module ? 'border-red-500' : ''}`}
              style={inputStyle}
            />
            {errors.module && <p className="text-xs mt-1" style={errorStyle}>{errors.module}</p>}
          </div>
          
          <div>
            <label htmlFor="action" className="block text-sm font-medium mb-1.5" style={labelStyle}>
              Action <span className="text-red-500">*</span>
            </label>
            <select
              id="action"
              required
              value={formData.action}
              onChange={(e) => handleChange('action', e.target.value)}
              className={`w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 ${errors.action ? 'border-red-500' : ''}`}
              style={inputStyle}
            >
              <option value="">Select action</option>
              {actions.map((act) => (
                <option key={act.value} value={act.value}>
                  {act.label}
                </option>
              ))}
            </select>
            {errors.action && <p className="text-xs mt-1" style={errorStyle}>{errors.action}</p>}
          </div>
          
          <div>
            <label htmlFor="description" className="block text-sm font-medium mb-1.5" style={labelStyle}>
              Description
            </label>
            <textarea
              id="description"
              rows={4}
              value={formData.description}
              onChange={(e) => handleChange('description', e.target.value)}
              placeholder="What does this permission allow?"
              className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 resize-none"
              style={inputStyle}
            />
          </div>
          
          <div className="flex gap-3 pt-4">
            <button
              type="submit"
              disabled={loading}
              className="px-6 py-2.5 rounded-lg text-sm font-medium transition-all disabled:opacity-50 hover:opacity-90"
              style={{ background: 'var(--color-cta)', color: 'white' }}
            >
              {loading ? 'Saving...' : (isEditing ? 'Update Permission' : 'Create Permission')}
            </button>
            <button
              type="button"
              onClick={() => router.back()}
              className="px-6 py-2.5 rounded-lg text-sm font-medium transition-all hover:opacity-80"
              style={{
                background: 'var(--color-surface-alt)',
                color: 'var(--color-text)',
                border: '1px solid var(--color-border)',
              }}
            >
              Cancel
            </button>
          </div>
        </div>
      </form>
    </div>
  );
}