import React, { useState, useEffect } from 'react'; import { X, Calendar, Eye, EyeOff } from 'lucide-react'; import type { CounterFormData } from '../types'; import { getTodayISOString, isDateValid } from '../utils/date'; import { deriveCounterType } from '../utils/nostr'; interface CounterFormModalProps { isOpen: boolean; onClose: () => void; onSubmit: (data: CounterFormData) => Promise; initialData?: CounterFormData; isLoading?: boolean; } export const CounterFormModal: React.FC = ({ isOpen, onClose, onSubmit, initialData, isLoading = false, }) => { const [formData, setFormData] = useState({ title: '', date: getTodayISOString(), type: 'since', visibility: 'private', }); const [errors, setErrors] = useState>({}); useEffect(() => { if (initialData) { setFormData(initialData); } else { setFormData({ title: '', date: getTodayISOString(), type: 'since', visibility: 'private', }); } setErrors({}); }, [initialData, isOpen]); // Auto-derive type from date const derivedType = deriveCounterType(formData.date); const typeDescription = derivedType === 'since' ? 'Days Since' : 'Days Until'; const validateForm = (): boolean => { const newErrors: Partial = {}; if (!formData.title.trim()) { newErrors.title = 'Title is required'; } else if (formData.title.length > 100) { newErrors.title = 'Title must be 100 characters or less'; } if (!formData.date) { newErrors.date = 'Date is required'; } else if (!isDateValid(formData.date)) { newErrors.date = 'Invalid date format'; } setErrors(newErrors); return Object.keys(newErrors).length === 0; }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!validateForm()) return; try { // Use the derived type instead of the form type const submitData = { ...formData, type: derivedType, }; await onSubmit(submitData); onClose(); } catch (error) { console.error('Error submitting form:', error); } }; const handleInputChange = ( field: keyof CounterFormData, value: string ) => { setFormData(prev => ({ ...prev, [field]: value })); // Clear error for this field if (errors[field]) { setErrors(prev => ({ ...prev, [field]: undefined })); } }; if (!isOpen) return null; return (

{initialData ? 'Edit Counter' : 'Create Counter'}

handleInputChange('title', e.target.value)} className={`w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 ${ errors.title ? 'border-red-500' : 'border-gray-300' }`} placeholder="e.g., Quit smoking" disabled={isLoading} /> {errors.title && (

{errors.title}

)}
handleInputChange('date', e.target.value)} className={`w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 ${ errors.date ? 'border-red-500' : 'border-gray-300' }`} disabled={isLoading} />
{errors.date && (

{errors.date}

)}

{typeDescription} (auto-detected from date)

); };