
import React from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { Loader2, AlertCircle, CheckCircle2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import PrimaryButton from '@/components/PrimaryButton';

const SmartForm = ({ 
  schema, 
  defaultValues, 
  onSubmit, 
  fields, 
  loading = false, 
  submitLabel = "Enregistrer",
  cancelLabel = "Annuler",
  onCancel 
}) => {
  const {
    register,
    handleSubmit,
    formState: { errors, isDirty, isValid },
    watch
  } = useForm({
    resolver: zodResolver(schema),
    defaultValues,
    mode: "onChange"
  });

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {fields.map((field) => {
          const isError = errors[field.name];
          const value = watch(field.name);
          const isSuccess = !isError && value && field.type !== 'checkbox' && field.type !== 'textarea';

          if (field.type === 'section') {
            return (
              <div key={field.title} className="col-span-1 md:col-span-2 pt-4 pb-2 border-b border-gray-200 dark:border-gray-800">
                <h3 className="text-lg font-medium text-gray-900 dark:text-white">{field.title}</h3>
                {field.description && <p className="text-sm text-gray-500 dark:text-gray-400">{field.description}</p>}
              </div>
            );
          }

          return (
            <div 
              key={field.name} 
              className={cn(
                "space-y-1.5 relative", 
                field.fullWidth && "col-span-1 md:col-span-2"
              )}
            >
              <label className="flex items-center gap-1 text-sm font-medium text-gray-700 dark:text-gray-300">
                {field.label}
                {field.required && <span className="text-red-500">*</span>}
              </label>
              
              <div className="relative">
                {field.type === 'select' ? (
                  <select
                    {...register(field.name)}
                    className={cn(
                      "w-full px-3 py-2 bg-white dark:bg-gray-950 border rounded-xl text-sm shadow-sm transition-all focus:outline-none focus:ring-2",
                      isError 
                        ? "border-red-300 focus:border-red-500 focus:ring-red-200" 
                        : "border-gray-200 dark:border-gray-800 focus:border-[#941403] focus:ring-red-100/50"
                    )}
                  >
                    <option value="">Sélectionner...</option>
                    {field.options?.map(opt => (
                      <option key={opt.value} value={opt.value}>{opt.label}</option>
                    ))}
                  </select>
                ) : field.type === 'textarea' ? (
                  <textarea
                    {...register(field.name)}
                    rows={field.rows || 3}
                    className={cn(
                      "w-full px-3 py-2 bg-white dark:bg-gray-950 border rounded-xl text-sm shadow-sm transition-all focus:outline-none focus:ring-2 resize-none",
                      isError 
                        ? "border-red-300 focus:border-red-500 focus:ring-red-200" 
                        : "border-gray-200 dark:border-gray-800 focus:border-[#941403] focus:ring-red-100/50"
                    )}
                  />
                ) : (
                  <input
                    type={field.type || 'text'}
                    {...register(field.name)}
                    placeholder={field.placeholder}
                    className={cn(
                      "w-full px-3 py-2 bg-white dark:bg-gray-950 border rounded-xl text-sm shadow-sm transition-all focus:outline-none focus:ring-2",
                      isError 
                        ? "border-red-300 focus:border-red-500 focus:ring-red-200 pr-10" 
                        : isSuccess 
                          ? "border-green-300 focus:border-green-500 focus:ring-green-200 pr-10"
                          : "border-gray-200 dark:border-gray-800 focus:border-[#941403] focus:ring-red-100/50"
                    )}
                  />
                )}

                {/* Icons validation indicators */}
                {field.type !== 'select' && field.type !== 'textarea' && (
                  <div className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none">
                    {isError && <AlertCircle className="w-4 h-4 text-red-500" />}
                    {isSuccess && <CheckCircle2 className="w-4 h-4 text-green-500" />}
                  </div>
                )}
              </div>

              {/* Helper Text or Error Message */}
              {isError ? (
                <p className="text-xs text-red-500 animate-in slide-in-from-top-1">{isError.message}</p>
              ) : field.help ? (
                <p className="text-xs text-gray-500 dark:text-gray-400">{field.help}</p>
              ) : null}
            </div>
          );
        })}
      </div>

      <div className="flex items-center justify-end gap-3 pt-6 border-t border-gray-200 dark:border-gray-800">
        {onCancel && (
          <button
            type="button"
            onClick={onCancel}
            className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-xl transition-colors"
          >
            {cancelLabel}
          </button>
        )}
        <PrimaryButton
          type="submit"
          loading={loading}
          disabled={!isDirty || !isValid}
        >
          {submitLabel}
        </PrimaryButton>
      </div>
    </form>
  );
};

export default SmartForm;
