import React, { useState } from 'react';
import { useForm } from 'react-hook-form';
import { useNumerology } from '../../hooks/useNumerology';
import { useAuth } from '../../hooks/useAuth';
import { CalculateNumerologyRequest } from '../../services/numerology';
import { validateName, validateDate } from '../../utils/validation';
import { DATE_FORMAT_EXAMPLES, COMMON_INDUSTRIES } from '../../utils/constants';
import { User, Calendar, Briefcase, Calculator as CalculatorIcon, Save, Info } from 'lucide-react';
import CalculationResults from '../Numerology/CalculationResults';

interface FormData extends CalculateNumerologyRequest {}

const Calculator: React.FC = () => {
  const { isAuthenticated } = useAuth();
  const { 
    currentCalculation, 
    calculate, 
    saveCalculation,
    isCalculating, 
    isSaving,
    calculationError,
    saveError 
  } = useNumerology();
  
  const [saveSuccess, setSaveSuccess] = useState(false);

  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
    setError,
  } = useForm<FormData>({
    defaultValues: {
      name: '',
      birthdate: '',
      industry: '',
    },
  });

  const onSubmit = async (data: FormData) => {
    // Additional client-side validation
    const nameValidation = validateName(data.name);
    if (!nameValidation.isValid) {
      setError('name', { message: nameValidation.error });
      return;
    }

    const dateValidation = validateDate(data.birthdate);
    if (!dateValidation.isValid) {
      setError('birthdate', { message: dateValidation.error });
      return;
    }

    const result = await calculate(data);
    if (result.success) {
      // Scroll to results section
      setTimeout(() => {
        document.getElementById('results')?.scrollIntoView({ 
          behavior: 'smooth',
          block: 'start'
        });
      }, 100);
    }
  };

  const handleSaveCalculation = async () => {
    if (!isAuthenticated) {
      alert('Please login to save calculations');
      return;
    }

    const result = await saveCalculation();
    if (result.success) {
      setSaveSuccess(true);
      setTimeout(() => setSaveSuccess(false), 3000);
    }
  };

  const handleNewCalculation = () => {
    reset();
    setSaveSuccess(false);
  };

  return (
    <div className="space-y-8">
      {/* Header */}
      <div className="text-center text-white space-y-4">
        <div className="flex items-center justify-center space-x-3">
          <CalculatorIcon className="h-12 w-12" />
          <h1 className="text-4xl md:text-5xl font-bold">Numerology Calculator</h1>
        </div>
        <p className="text-xl opacity-90 max-w-2xl mx-auto">
          Enter your details below to discover your numerology pyramid, SWOT analysis, and business guidance.
        </p>
      </div>

      {/* Calculator Form */}
      <div className="bg-white rounded-xl shadow-lg p-8">
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
          <div className="grid md:grid-cols-2 gap-6">
            {/* Name Field */}
            <div>
              <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-2">
                Full Name *
              </label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <User className="h-5 w-5 text-gray-400" />
                </div>
                <input
                  {...register('name', {
                    required: 'Name is required',
                    validate: (value) => {
                      const validation = validateName(value);
                      return validation.isValid || validation.error;
                    },
                  })}
                  type="text"
                  className="block w-full pl-10 pr-3 py-3 border border-gray-300 rounded-md focus:outline-none focus:ring-purple-500 focus:border-purple-500"
                  placeholder="Enter your full name"
                />
              </div>
              {errors.name && (
                <p className="mt-1 text-sm text-red-600">{errors.name.message}</p>
              )}
            </div>

            {/* Industry Field */}
            <div>
              <label htmlFor="industry" className="block text-sm font-medium text-gray-700 mb-2">
                Industry (Optional)
              </label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <Briefcase className="h-5 w-5 text-gray-400" />
                </div>
                <select
                  {...register('industry')}
                  className="block w-full pl-10 pr-3 py-3 border border-gray-300 rounded-md focus:outline-none focus:ring-purple-500 focus:border-purple-500"
                >
                  <option value="">Select your industry</option>
                  {COMMON_INDUSTRIES.map((industry) => (
                    <option key={industry} value={industry}>
                      {industry}
                    </option>
                  ))}
                </select>
              </div>
            </div>
          </div>

          {/* Birthdate Field */}
          <div>
            <label htmlFor="birthdate" className="block text-sm font-medium text-gray-700 mb-2">
              Birthdate *
            </label>
            <div className="relative">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <Calendar className="h-5 w-5 text-gray-400" />
              </div>
              <input
                {...register('birthdate', {
                  required: 'Birthdate is required',
                  validate: (value) => {
                    const validation = validateDate(value);
                    return validation.isValid || validation.error;
                  },
                })}
                type="text"
                className="block w-full pl-10 pr-3 py-3 border border-gray-300 rounded-md focus:outline-none focus:ring-purple-500 focus:border-purple-500"
                placeholder="e.g., 31-July-1985"
              />
            </div>
            {errors.birthdate ? (
              <p className="mt-1 text-sm text-red-600">{errors.birthdate.message}</p>
            ) : (
              <div className="mt-2 p-3 bg-blue-50 border border-blue-200 rounded-md">
                <div className="flex items-start space-x-2">
                  <Info className="h-5 w-5 text-blue-500 mt-0.5 flex-shrink-0" />
                  <div>
                    <p className="text-sm text-blue-700 font-medium">Supported date formats:</p>
                    <p className="text-sm text-blue-600 mt-1">
                      {DATE_FORMAT_EXAMPLES.join(' • ')}
                    </p>
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* Error Display */}
          {calculationError && (
            <div className="bg-red-50 border border-red-200 rounded-md p-4">
              <p className="text-sm text-red-600">{calculationError}</p>
            </div>
          )}

          {/* Submit Button */}
          <div className="flex flex-col sm:flex-row gap-4">
            <button
              type="submit"
              disabled={isCalculating}
              className="flex-1 flex items-center justify-center space-x-2 py-3 px-6 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-purple-600 hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-purple-500 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-300"
            >
              {isCalculating ? (
                <>
                  <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                  <span>Calculating...</span>
                </>
              ) : (
                <>
                  <CalculatorIcon className="h-5 w-5" />
                  <span>Calculate Numerology</span>
                </>
              )}
            </button>
            
            {currentCalculation && (
              <button
                type="button"
                onClick={handleNewCalculation}
                className="px-6 py-3 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-purple-500 transition-all duration-300"
              >
                New Calculation
              </button>
            )}
          </div>
        </form>
      </div>

      {/* Results Section */}
      {currentCalculation && (
        <div id="results">
          <CalculationResults 
            result={currentCalculation}
            onSave={handleSaveCalculation}
            isSaving={isSaving}
            saveError={saveError}
            saveSuccess={saveSuccess}
            showSaveButton={isAuthenticated}
          />
        </div>
      )}

      {/* Login Prompt for Non-Authenticated Users */}
      {currentCalculation && !isAuthenticated && (
        <div className="bg-yellow-50 border border-yellow-200 rounded-xl p-6">
          <div className="text-center">
            <h3 className="text-lg font-medium text-yellow-800 mb-2">
              Want to save your results?
            </h3>
            <p className="text-yellow-700 mb-4">
              Create an account to save and manage your numerology calculations.
            </p>
            <div className="flex flex-col sm:flex-row gap-3 justify-center">
              <a
                href="/register"
                className="px-6 py-2 bg-yellow-600 text-white font-medium rounded-md hover:bg-yellow-700 transition-colors duration-300"
              >
                Create Account
              </a>
              <a
                href="/login"
                className="px-6 py-2 border border-yellow-600 text-yellow-600 font-medium rounded-md hover:bg-yellow-50 transition-colors duration-300"
              >
                Sign In
              </a>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Calculator;