// apps/verify/src/features/audit/AuditForm.jsx
import React, { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { Loader2, ChevronRight, ChevronLeft, AlertCircle } from 'lucide-react';
import { Button } from '@skillnexus/ui';
import { auditSchema, calculateSeverityScore } from '@skillnexus/core-logic';

const steps = [
  { id: 'company', title: 'Company Details' },
  { id: 'hiring', title: 'Hiring Challenges' },
  { id: 'budget', title: 'Budget & Timeline' }
];

export function AuditForm({ onComplete, onStepChange }) {
  const [currentStep, setCurrentStep] = useState(0);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState(null);

  const {
    register,
    handleSubmit,
    formState: { errors },
    trigger,
    getValues
  } = useForm({
    resolver: zodResolver(auditSchema),
    mode: 'onTouched',
    defaultValues: {
      companyName: '',
      companySize: '',
      industry: '',
      monthlyHires: '',
      avgTimeToHire: '',
      budgetRange: '',
      painPoints: [],
      timeline: ''
    }
  });

  const stepFields = [
    ['companyName', 'companySize', 'industry'],
    ['monthlyHires', 'avgTimeToHire', 'painPoints'],
    ['budgetRange', 'timeline']
  ];

  const handleNext = async () => {
    const fields = stepFields[currentStep];
    const isValid = await trigger(fields);
    if (isValid) {
      if (currentStep < steps.length - 1) {
        const nextStep = currentStep + 1;
        setCurrentStep(nextStep);
        onStepChange?.(nextStep);
      }
    }
  };

  const handleBack = () => {
    if (currentStep > 0) {
      const prevStep = currentStep - 1;
      setCurrentStep(prevStep);
      onStepChange?.(prevStep);
    }
  };

  // Prevent ENTER key on early steps from triggering form submission
  const handleKeyDown = (e) => {
    if (e.key === 'Enter' && currentStep < steps.length - 1) {
      e.preventDefault();
      handleNext();
    }
  };

  const onSubmit = async (data) => {
    setIsSubmitting(true);
    setSubmitError(null);

    try {
      const result = calculateSeverityScore(data);
      const score = result.score;

      const response = await fetch('/api/audit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...data, score, breakdown: result.breakdown })
      });

      if (!response.ok) {
        throw new Error(`Server returned ${response.status}`);
      }

      const apiResult = await response.json();
      onComplete?.(apiResult);
    } catch (error) {
      console.error('Audit submission failed:', error);
      setSubmitError(error.message || 'Failed to submit audit. Please try again.');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <form 
      onSubmit={handleSubmit(onSubmit)} 
      onKeyDown={handleKeyDown}
      className="max-w-3xl mx-auto p-6"
    >
      {/* Progress Steps */}
      <div className="flex justify-between mb-8">
        {steps.map((step, index) => (
          <div key={step.id} className="flex items-center">
            <div
              className={`
                w-10 h-10 rounded-full flex items-center justify-center font-semibold transition-colors
                ${index <= currentStep ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-600'}
              `}
            >
              {index + 1}
            </div>
            <span className={`ml-2 text-sm font-medium ${index <= currentStep ? 'text-gray-900' : 'text-gray-500'}`}>
              {step.title}
            </span>
            {index < steps.length - 1 && (
              <div className={`w-12 h-px mx-4 ${index < currentStep ? 'bg-blue-600' : 'bg-gray-300'}`} />
            )}
          </div>
        ))}
      </div>

      {submitError && (
        <div className="mb-6 p-4 rounded-md bg-red-50 border border-red-200 flex items-center text-red-700 text-sm">
          <AlertCircle className="w-5 h-5 mr-2 flex-shrink-0" />
          <span>{submitError}</span>
        </div>
      )}

      {/* Step Content */}
      <div className="space-y-6 min-h-[300px]">
        {currentStep === 0 && (
          <>
            <div>
              <label className="block text-sm font-medium text-gray-700">Company Name</label>
              <input
                {...register('companyName')}
                type="text"
                placeholder="Acme Inc."
                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm"
              />
              {errors.companyName && (
                <p className="mt-1 text-sm text-red-600">{errors.companyName.message}</p>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700">Company Size</label>
              <select
                {...register('companySize')}
                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm"
              >
                <option value="">Select size...</option>
                <option value="1-10">1-10 employees</option>
                <option value="10-50">10-50 employees</option>
                <option value="50+">50+ employees</option>
              </select>
              {errors.companySize && (
                <p className="mt-1 text-sm text-red-600">{errors.companySize.message}</p>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700">Industry</label>
              <input
                {...register('industry')}
                type="text"
                placeholder="Software / FinTech"
                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm"
              />
              {errors.industry && (
                <p className="mt-1 text-sm text-red-600">{errors.industry.message}</p>
              )}
            </div>
          </>
        )}

        {currentStep === 1 && (
          <>
            <div>
              <label className="block text-sm font-medium text-gray-700">Monthly Hires</label>
              <input
                {...register('monthlyHires', { valueAsNumber: true })}
                type="number"
                min="0"
                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm"
              />
              {errors.monthlyHires && (
                <p className="mt-1 text-sm text-red-600">{errors.monthlyHires.message}</p>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700">Average Time to Hire (days)</label>
              <input
                {...register('avgTimeToHire', { valueAsNumber: true })}
                type="number"
                min="0"
                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm"
              />
              {errors.avgTimeToHire && (
                <p className="mt-1 text-sm text-red-600">{errors.avgTimeToHire.message}</p>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Pain Points</label>
              <div className="space-y-2">
                {['Slow screening', 'High candidate drop-off', 'Poor quality hires', 'Expensive agencies'].map((point) => (
                  <label key={point} className="flex items-center space-x-2 cursor-pointer">
                    <input
                      type="checkbox"
                      value={point}
                      {...register('painPoints')}
                      className="rounded border-gray-300 text-blue-600 focus:ring-blue-500 h-4 w-4"
                    />
                    <span className="text-sm text-gray-700">{point}</span>
                  </label>
                ))}
              </div>
              {errors.painPoints && (
                <p className="mt-1 text-sm text-red-600">{errors.painPoints.message}</p>
              )}
            </div>
          </>
        )}

        {currentStep === 2 && (
          <>
            <div>
              <label className="block text-sm font-medium text-gray-700">Budget Range</label>
              <select
                {...register('budgetRange')}
                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm"
              >
                <option value="">Select budget...</option>
                <option value="<5000">Less than $5,000/month</option>
                <option value="5000-15000">$5,000 - $15,000/month</option>
                <option value=">15000">$15,000+ /month</option>
              </select>
              {errors.budgetRange && (
                <p className="mt-1 text-sm text-red-600">{errors.budgetRange.message}</p>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700">Timeline for Implementation</label>
              <select
                {...register('timeline')}
                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm"
              >
                <option value="">Select timeline...</option>
                <option value="immediate">Immediate (0-2 weeks)</option>
                <option value="short">Short-term (1-2 months)</option>
                <option value="planning">Planning (3-6 months)</option>
              </select>
              {errors.timeline && (
                <p className="mt-1 text-sm text-red-600">{errors.timeline.message}</p>
              )}
            </div>
          </>
        )}
      </div>

      {/* Navigation Buttons */}
      <div className="flex justify-between mt-8 pt-6 border-t border-gray-200">
        <Button
          type="button"
          variant="outline"
          onClick={handleBack}
          disabled={currentStep === 0 || isSubmitting}
        >
          <ChevronLeft className="w-4 h-4 mr-2" />
          Back
        </Button>

        {currentStep === steps.length - 1 ? (
          <Button
            type="submit"
            disabled={isSubmitting}
            className="bg-blue-600 hover:bg-blue-700 text-white"
          >
            {isSubmitting ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Analyzing...
              </>
            ) : (
              <>
                Submit Audit
                <ChevronRight className="w-4 h-4 ml-2" />
              </>
            )}
          </Button>
        ) : (
          <Button
            type="button"
            onClick={handleNext}
            className="bg-blue-600 hover:bg-blue-700 text-white"
          >
            Next
            <ChevronRight className="w-4 h-4 ml-2" />
          </Button>
        )}
      </div>
    </form>
  );
}