import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { Progress } from "@/components/ui/progress";
import { useToast } from "@/hooks/use-toast";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@/lib/queryClient";
import { 
  Trophy, 
  Users, 
  Settings, 
  CheckCircle, 
  ArrowRight, 
  ArrowLeft,
  Upload,
  FileText,
  Globe
} from "lucide-react";

interface OnboardingData {
  clubInfo: {
    name: string;
    description: string;
    website: string;
    email: string;
    phone: string;
    address: string;
    founded: string;
  };
  preferences: {
    rugbyFormat: string[];
    seasonType: string;
    competitionLevel: string;
    enableBiometrics: boolean;
    enableInjuryTracking: boolean;
    enablePerformanceAnalytics: boolean;
  };
  initialData: {
    importSampleData: boolean;
    setupCalendar: boolean;
    inviteMembers: boolean;
  };
}

interface OnboardingWizardProps {
  onComplete: () => void;
}

export default function OnboardingWizard({ onComplete }: OnboardingWizardProps) {
  const [currentStep, setCurrentStep] = useState(1);
  const [data, setData] = useState<OnboardingData>({
    clubInfo: {
      name: "",
      description: "",
      website: "",
      email: "",
      phone: "",
      address: "",
      founded: "",
    },
    preferences: {
      rugbyFormat: [],
      seasonType: "year-round",
      competitionLevel: "club",
      enableBiometrics: false,
      enableInjuryTracking: true,
      enablePerformanceAnalytics: true,
    },
    initialData: {
      importSampleData: false,
      setupCalendar: true,
      inviteMembers: false,
    },
  });

  const { toast } = useToast();
  const queryClient = useQueryClient();

  const completeOnboardingMutation = useMutation({
    mutationFn: async (onboardingData: OnboardingData) => {
      await apiRequest("POST", "/api/onboarding/complete", onboardingData);
    },
    onSuccess: () => {
      toast({
        title: "Welcome to your rugby management system!",
        description: "Your club setup is complete. Let's start managing your teams.",
      });
      queryClient.invalidateQueries();
      onComplete();
    },
    onError: (error: Error) => {
      toast({
        title: "Setup failed",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const totalSteps = 4;
  const progress = (currentStep / totalSteps) * 100;

  const updateData = (section: keyof OnboardingData, updates: Partial<OnboardingData[keyof OnboardingData]>) => {
    setData(prev => ({
      ...prev,
      [section]: { ...prev[section], ...updates }
    }));
  };

  const handleNext = () => {
    if (currentStep < totalSteps) {
      setCurrentStep(currentStep + 1);
    } else {
      completeOnboardingMutation.mutate(data);
    }
  };

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

  const isStepValid = () => {
    switch (currentStep) {
      case 1:
        return data.clubInfo.name.trim() !== "";
      case 2:
        return data.preferences.rugbyFormat.length > 0;
      default:
        return true;
    }
  };

  const renderStep = () => {
    switch (currentStep) {
      case 1:
        return (
          <div className="space-y-6">
            <div className="text-center mb-6">
              <Trophy className="h-12 w-12 text-primary mx-auto mb-4" />
              <h2 className="text-2xl font-bold">Tell us about your rugby club</h2>
              <p className="text-gray-600">Let's start with some basic information about your organization.</p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="clubName">Club Name *</Label>
                <Input
                  id="clubName"
                  value={data.clubInfo.name}
                  onChange={(e) => updateData("clubInfo", { name: e.target.value })}
                  placeholder="e.g., City Rugby Club"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="founded">Founded Year</Label>
                <Input
                  id="founded"
                  type="number"
                  value={data.clubInfo.founded}
                  onChange={(e) => updateData("clubInfo", { founded: e.target.value })}
                  placeholder="e.g., 1995"
                />
              </div>

              <div className="space-y-2 md:col-span-2">
                <Label htmlFor="description">Club Description</Label>
                <Textarea
                  id="description"
                  value={data.clubInfo.description}
                  onChange={(e) => updateData("clubInfo", { description: e.target.value })}
                  placeholder="Brief description of your rugby club..."
                  rows={3}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="email">Contact Email</Label>
                <Input
                  id="email"
                  type="email"
                  value={data.clubInfo.email}
                  onChange={(e) => updateData("clubInfo", { email: e.target.value })}
                  placeholder="contact@rugbyclub.com"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="phone">Phone Number</Label>
                <Input
                  id="phone"
                  value={data.clubInfo.phone}
                  onChange={(e) => updateData("clubInfo", { phone: e.target.value })}
                  placeholder="+1 (555) 123-4567"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="website">Website</Label>
                <Input
                  id="website"
                  value={data.clubInfo.website}
                  onChange={(e) => updateData("clubInfo", { website: e.target.value })}
                  placeholder="https://yourclub.com"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="address">Address</Label>
                <Input
                  id="address"
                  value={data.clubInfo.address}
                  onChange={(e) => updateData("clubInfo", { address: e.target.value })}
                  placeholder="123 Rugby Field Ave, City, State"
                />
              </div>
            </div>
          </div>
        );

      case 2:
        return (
          <div className="space-y-6">
            <div className="text-center mb-6">
              <Settings className="h-12 w-12 text-primary mx-auto mb-4" />
              <h2 className="text-2xl font-bold">Configure your preferences</h2>
              <p className="text-gray-600">Set up how you want to manage your rugby operations.</p>
            </div>

            <div className="space-y-6">
              <div className="space-y-4">
                <Label className="text-base font-semibold">Rugby Formats *</Label>
                <p className="text-sm text-gray-600">Select the rugby formats your club plays:</p>
                <div className="grid grid-cols-3 gap-4">
                  {["15s Rugby", "7s Rugby", "10s Rugby"].map((format) => (
                    <div key={format} className="flex items-center space-x-2">
                      <Checkbox
                        id={format}
                        checked={data.preferences.rugbyFormat.includes(format)}
                        onCheckedChange={(checked) => {
                          if (checked) {
                            updateData("preferences", {
                              rugbyFormat: [...data.preferences.rugbyFormat, format]
                            });
                          } else {
                            updateData("preferences", {
                              rugbyFormat: data.preferences.rugbyFormat.filter(f => f !== format)
                            });
                          }
                        }}
                      />
                      <Label htmlFor={format}>{format}</Label>
                    </div>
                  ))}
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="seasonType">Season Type</Label>
                  <Select
                    value={data.preferences.seasonType}
                    onValueChange={(value) => updateData("preferences", { seasonType: value })}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="year-round">Year Round</SelectItem>
                      <SelectItem value="seasonal">Seasonal</SelectItem>
                      <SelectItem value="tournament">Tournament Based</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="competitionLevel">Competition Level</Label>
                  <Select
                    value={data.preferences.competitionLevel}
                    onValueChange={(value) => updateData("preferences", { competitionLevel: value })}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="youth">Youth/Junior</SelectItem>
                      <SelectItem value="club">Club Level</SelectItem>
                      <SelectItem value="regional">Regional</SelectItem>
                      <SelectItem value="national">National</SelectItem>
                      <SelectItem value="international">International</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div className="space-y-4">
                <Label className="text-base font-semibold">Feature Preferences</Label>
                <div className="space-y-3">
                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="biometrics"
                      checked={data.preferences.enableBiometrics}
                      onCheckedChange={(checked) => 
                        updateData("preferences", { enableBiometrics: checked as boolean })
                      }
                    />
                    <Label htmlFor="biometrics">Enable biometric fingerprint scanning</Label>
                  </div>

                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="injuries"
                      checked={data.preferences.enableInjuryTracking}
                      onCheckedChange={(checked) => 
                        updateData("preferences", { enableInjuryTracking: checked as boolean })
                      }
                    />
                    <Label htmlFor="injuries">Enable injury tracking and management</Label>
                  </div>

                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="analytics"
                      checked={data.preferences.enablePerformanceAnalytics}
                      onCheckedChange={(checked) => 
                        updateData("preferences", { enablePerformanceAnalytics: checked as boolean })
                      }
                    />
                    <Label htmlFor="analytics">Enable performance analytics and reporting</Label>
                  </div>
                </div>
              </div>
            </div>
          </div>
        );

      case 3:
        return (
          <div className="space-y-6">
            <div className="text-center mb-6">
              <Users className="h-12 w-12 text-primary mx-auto mb-4" />
              <h2 className="text-2xl font-bold">Import data and setup</h2>
              <p className="text-gray-600">Choose how you'd like to start populating your system.</p>
            </div>

            <div className="space-y-6">
              <Card>
                <CardHeader>
                  <div className="flex items-center space-x-3">
                    <div className="w-10 h-10 bg-primary/10 rounded-lg flex items-center justify-center">
                      <FileText className="h-6 w-6 text-primary" />
                    </div>
                    <div>
                      <CardTitle>Sample Data</CardTitle>
                      <CardDescription>Add demo teams, players, and coaches to explore features</CardDescription>
                    </div>
                    <Checkbox
                      checked={data.initialData.importSampleData}
                      onCheckedChange={(checked) => 
                        updateData("initialData", { importSampleData: checked as boolean })
                      }
                    />
                  </div>
                </CardHeader>
              </Card>

              <Card>
                <CardHeader>
                  <div className="flex items-center space-x-3">
                    <div className="w-10 h-10 bg-secondary/10 rounded-lg flex items-center justify-center">
                      <Globe className="h-6 w-6 text-secondary" />
                    </div>
                    <div>
                      <CardTitle>Setup Calendar</CardTitle>
                      <CardDescription>Create initial calendar structure for activities and training</CardDescription>
                    </div>
                    <Checkbox
                      checked={data.initialData.setupCalendar}
                      onCheckedChange={(checked) => 
                        updateData("initialData", { setupCalendar: checked as boolean })
                      }
                    />
                  </div>
                </CardHeader>
              </Card>

              <Card>
                <CardHeader>
                  <div className="flex items-center space-x-3">
                    <div className="w-10 h-10 bg-success/10 rounded-lg flex items-center justify-center">
                      <Users className="h-6 w-6 text-success" />
                    </div>
                    <div>
                      <CardTitle>Invite Members</CardTitle>
                      <CardDescription>Send invitations to coaches and staff to join the platform</CardDescription>
                    </div>
                    <Checkbox
                      checked={data.initialData.inviteMembers}
                      onCheckedChange={(checked) => 
                        updateData("initialData", { inviteMembers: checked as boolean })
                      }
                    />
                  </div>
                </CardHeader>
              </Card>

              <div className="bg-blue-50 dark:bg-blue-900/20 p-4 rounded-lg">
                <h4 className="font-semibold text-blue-900 dark:text-blue-100 mb-2">Data Import Options</h4>
                <p className="text-sm text-blue-700 dark:text-blue-200 mb-3">
                  You can also import existing data later from CSV files or other rugby management systems.
                </p>
                <Button variant="outline" size="sm">
                  <Upload className="h-4 w-4 mr-2" />
                  Upload CSV Files
                </Button>
              </div>
            </div>
          </div>
        );

      case 4:
        return (
          <div className="space-y-6">
            <div className="text-center mb-6">
              <CheckCircle className="h-12 w-12 text-success mx-auto mb-4" />
              <h2 className="text-2xl font-bold">All set! Let's get started</h2>
              <p className="text-gray-600">Review your setup and complete the onboarding process.</p>
            </div>

            <div className="space-y-4">
              <Card>
                <CardHeader>
                  <CardTitle className="text-lg">Club Information</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div>
                      <span className="font-medium">Name:</span> {data.clubInfo.name}
                    </div>
                    <div>
                      <span className="font-medium">Founded:</span> {data.clubInfo.founded || "Not specified"}
                    </div>
                    <div>
                      <span className="font-medium">Email:</span> {data.clubInfo.email || "Not specified"}
                    </div>
                    <div>
                      <span className="font-medium">Phone:</span> {data.clubInfo.phone || "Not specified"}
                    </div>
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle className="text-lg">Rugby Formats</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="flex flex-wrap gap-2">
                    {data.preferences.rugbyFormat.map((format) => (
                      <span key={format} className="px-3 py-1 bg-primary/10 text-primary rounded-full text-sm">
                        {format}
                      </span>
                    ))}
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle className="text-lg">Initial Setup</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-2 text-sm">
                    {data.initialData.importSampleData && (
                      <div className="flex items-center text-success">
                        <CheckCircle className="h-4 w-4 mr-2" />
                        Sample data will be imported
                      </div>
                    )}
                    {data.initialData.setupCalendar && (
                      <div className="flex items-center text-success">
                        <CheckCircle className="h-4 w-4 mr-2" />
                        Calendar structure will be created
                      </div>
                    )}
                    {data.initialData.inviteMembers && (
                      <div className="flex items-center text-success">
                        <CheckCircle className="h-4 w-4 mr-2" />
                        Member invitation system will be enabled
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <div className="max-w-4xl mx-auto p-6">
      <div className="mb-8">
        <div className="flex items-center justify-between mb-4">
          <h1 className="text-3xl font-bold">Welcome to Rugby Manager</h1>
          <span className="text-sm text-gray-500">Step {currentStep} of {totalSteps}</span>
        </div>
        <Progress value={progress} className="w-full" />
      </div>

      <Card>
        <CardContent className="p-8">
          {renderStep()}
        </CardContent>
      </Card>

      <div className="flex justify-between mt-6">
        <Button
          variant="outline"
          onClick={handleBack}
          disabled={currentStep === 1}
        >
          <ArrowLeft className="h-4 w-4 mr-2" />
          Back
        </Button>

        <Button
          onClick={handleNext}
          disabled={!isStepValid() || completeOnboardingMutation.isPending}
        >
          {currentStep === totalSteps ? (
            completeOnboardingMutation.isPending ? (
              "Setting up..."
            ) : (
              "Complete Setup"
            )
          ) : (
            <>
              Next
              <ArrowRight className="h-4 w-4 ml-2" />
            </>
          )}
        </Button>
      </div>
    </div>
  );
}