import React, { useState } from 'react';
import { useForm } from 'react-hook-form';
import { useCountersContext } from '../contexts/CountersContext';
import { CreateCounterRequest } from '../types';
import { X } from 'lucide-react';

interface CreateCounterModalProps {
  onClose: () => void;
}

export const CreateCounterModal: React.FC<CreateCounterModalProps> = ({ onClose }) => {
  const { createCounter } = useCountersContext();
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<CreateCounterRequest>();

  const onSubmit = async (data: CreateCounterRequest) => {
    setIsLoading(true);
    setError(null);
    try {
      await createCounter(data);
      onClose();
    } catch (err: any) {
      setError(err.message || 'Failed to create counter');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
      <div className="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
        <div className="flex justify-between items-center mb-4">
          <h3 className="text-lg font-medium text-gray-900">Create New Counter</h3>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600"
          >
            <X className="h-6 w-6" />
          </button>
        </div>

        {error && (
          <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md mb-4">
            {error}
          </div>
        )}

        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
          <div>
            <label htmlFor="name" className="block text-sm font-medium text-gray-700">
              Name *
            </label>
            <input
              {...register('name', { 
                required: 'Name is required',
                maxLength: { value: 100, message: 'Name must be less than 100 characters' }
              })}
              type="text"
              className="input mt-1"
              placeholder="e.g., Cigarettes Smoked"
            />
            {errors.name && (
              <p className="mt-1 text-sm text-red-600">{errors.name.message}</p>
            )}
          </div>

          <div>
            <label htmlFor="description" className="block text-sm font-medium text-gray-700">
              Description
            </label>
            <textarea
              {...register('description', {
                maxLength: { value: 500, message: 'Description must be less than 500 characters' }
              })}
              rows={3}
              className="input mt-1"
              placeholder="Optional description..."
            />
            {errors.description && (
              <p className="mt-1 text-sm text-red-600">{errors.description.message}</p>
            )}
          </div>

          <div className="flex justify-end space-x-3 pt-4">
            <button
              type="button"
              onClick={onClose}
              className="btn btn-secondary"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={isLoading}
              className="btn btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isLoading ? 'Creating...' : 'Create Counter'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};
