import React, { useState } from "react";
import { base44 } from "@/api/base44Client";
import { useMutation, useQueryClient, useQuery } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { CheckCircle, Circle } from "lucide-react";
import { useToast } from "@/components/ui/use-toast";
import ProfileSetupStep from "../components/onboarding/ProfileSetupStep";
import DocumentUploadStep from "../components/onboarding/DocumentUploadStep";
import TrainingStep from "../components/onboarding/TrainingStep";
import CompletionStep from "../components/onboarding/CompletionStep";

const steps = [
  { id: 1, name: "Profile Setup", description: "Basic information" },
  { id: 2, name: "Documents", description: "Upload required documents" },
  { id: 3, name: "Training", description: "Complete compliance training" },
  { id: 4, name: "Complete", description: "Finish onboarding" },
];

export default function StaffOnboarding() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { toast } = useToast();
  const [currentStep, setCurrentStep] = useState(1);
  const [onboardingData, setOnboardingData] = useState({
    profile: {},
    documents: [],
    training: { completed: [] },
  });

  const { data: currentUser } = useQuery({
    queryKey: ['current-user-onboarding'],
    queryFn: () => base44.auth.me(),
  });

  const createStaffMutation = useMutation({
    mutationFn: (staffData) => base44.entities.Staff.create(staffData),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['staff'] });
      toast({
        title: "✅ Onboarding Complete",
        description: "Welcome to KROW! Your profile is now active.",
      });
      navigate(createPageUrl("WorkforceDashboard"));
    },
    onError: (error) => {
      toast({
        title: "❌ Onboarding Failed",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const handleNext = (stepData) => {
    setOnboardingData(prev => ({
      ...prev,
      [stepData.type]: stepData.data,
    }));
    
    if (currentStep < steps.length) {
      setCurrentStep(currentStep + 1);
    }
  };

  const handleBack = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
    }
  };

  const handleComplete = () => {
    const staffData = {
      employee_name: onboardingData.profile.full_name,
      email: onboardingData.profile.email || currentUser?.email,
      phone: onboardingData.profile.phone,
      address: onboardingData.profile.address,
      city: onboardingData.profile.city,
      position: onboardingData.profile.position,
      department: onboardingData.profile.department,
      hub_location: onboardingData.profile.hub_location,
      employment_type: onboardingData.profile.employment_type,
      english: onboardingData.profile.english_level,
      certifications: onboardingData.documents.filter(d => d.type === 'certification').map(d => ({
        name: d.name,
        issued_date: d.issued_date,
        expiry_date: d.expiry_date,
        document_url: d.url,
      })),
      background_check_status: onboardingData.documents.some(d => d.type === 'background_check') ? 'pending' : 'not_required',
      notes: `Onboarding completed: ${new Date().toISOString()}. Training modules completed: ${onboardingData.training.completed.length}`,
    };

    createStaffMutation.mutate(staffData);
  };

  const renderStep = () => {
    switch (currentStep) {
      case 1:
        return (
          <ProfileSetupStep
            data={onboardingData.profile}
            onNext={handleNext}
            currentUser={currentUser}
          />
        );
      case 2:
        return (
          <DocumentUploadStep
            data={onboardingData.documents}
            onNext={handleNext}
            onBack={handleBack}
          />
        );
      case 3:
        return (
          <TrainingStep
            data={onboardingData.training}
            onNext={handleNext}
            onBack={handleBack}
          />
        );
      case 4:
        return (
          <CompletionStep
            data={onboardingData}
            onComplete={handleComplete}
            onBack={handleBack}
            isSubmitting={createStaffMutation.isPending}
          />
        );
      default:
        return null;
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-blue-50 p-4 md:p-8">
      <div className="max-w-4xl mx-auto">
        {/* Header */}
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-slate-900 mb-2">
            Welcome to KROW! 👋
          </h1>
          <p className="text-slate-600">
            Let's get you set up in just a few steps
          </p>
        </div>

        {/* Progress Steps */}
        <div className="mb-8">
          <div className="flex items-center justify-between">
            {steps.map((step, idx) => (
              <React.Fragment key={step.id}>
                <div className="flex flex-col items-center flex-1">
                  <div className={`w-12 h-12 rounded-full flex items-center justify-center ${
                    currentStep > step.id 
                      ? "bg-green-500 text-white" 
                      : currentStep === step.id 
                      ? "bg-[#0A39DF] text-white" 
                      : "bg-slate-200 text-slate-400"
                  }`}>
                    {currentStep > step.id ? (
                      <CheckCircle className="w-6 h-6" />
                    ) : (
                      <span className="font-bold">{step.id}</span>
                    )}
                  </div>
                  <p className={`text-sm font-medium mt-2 ${
                    currentStep >= step.id ? "text-slate-900" : "text-slate-400"
                  }`}>
                    {step.name}
                  </p>
                  <p className="text-xs text-slate-500">{step.description}</p>
                </div>
                {idx < steps.length - 1 && (
                  <div className={`flex-1 h-1 ${
                    currentStep > step.id ? "bg-green-500" : "bg-slate-200"
                  }`} />
                )}
              </React.Fragment>
            ))}
          </div>
        </div>

        {/* Step Content */}
        <Card>
          <CardContent className="p-6 md:p-8">
            {renderStep()}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}