import React, { useState } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery, useMutation } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import { createPageUrl } from "@/utils";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { CheckCircle2, UserPlus, User, Lock, Briefcase } from "lucide-react";
import { useToast } from "@/components/ui/use-toast";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";

export default function Onboarding() {
  const navigate = useNavigate();
  const { toast } = useToast();
  const urlParams = new URLSearchParams(window.location.search);
  const inviteCode = urlParams.get('invite');

  const [formData, setFormData] = useState({
    first_name: "",
    last_name: "",
    email: "",
    phone: "",
    title: "",
    department: "",
    hub: "",
    password: "",
    confirmPassword: ""
  });

  // Fetch invite details if invite code exists
  const { data: invite } = useQuery({
    queryKey: ['team-invite', inviteCode],
    queryFn: async () => {
      const allInvites = await base44.entities.TeamMemberInvite.list();
      const foundInvite = allInvites.find(inv => inv.invite_code === inviteCode && inv.invite_status === 'pending');

      if (foundInvite) {
        // Pre-fill form with invite data
        const nameParts = (foundInvite.full_name || "").split(' ');
        setFormData(prev => ({
          ...prev,
          email: foundInvite.email,
          first_name: nameParts[0] || "",
          last_name: nameParts.slice(1).join(' ') || "",
          phone: foundInvite.phone || "",
          department: foundInvite.department || "",
          hub: foundInvite.hub || "",
          title: foundInvite.title || ""
        }));
      }

      return foundInvite;
    },
    enabled: !!inviteCode,
  });

  // Fetch available hubs for the team
  const { data: hubs = [] } = useQuery({
    queryKey: ['team-hubs-onboarding', invite?.team_id],
    queryFn: async () => {
      if (!invite?.team_id) return [];
      const allHubs = await base44.entities.TeamHub.list();
      return allHubs.filter(h => h.team_id === invite.team_id && h.is_active);
    },
    enabled: !!invite?.team_id,
    initialData: [],
  });

  // Fetch team to get departments
  const { data: team } = useQuery({
    queryKey: ['team-for-departments', invite?.team_id],
    queryFn: async () => {
      if (!invite?.team_id) return null;
      const allTeams = await base44.entities.Team.list();
      return allTeams.find(t => t.id === invite.team_id);
    },
    enabled: !!invite?.team_id,
  });

  // Get all unique departments from team and hubs
  const availableDepartments = React.useMemo(() => {
    const depts = new Set();

    // Add team departments
    if (team?.departments) {
      team.departments.forEach(d => depts.add(d));
    }

    // Add hub departments
    hubs.forEach(hub => {
      if (hub.departments) {
        hub.departments.forEach(dept => {
          if (dept.department_name) {
            depts.add(dept.department_name);
          }
        });
      }
    });

    return Array.from(depts);
  }, [team, hubs]);

  const registerMutation = useMutation({
    mutationFn: async (data) => {
      if (!invite) {
        throw new Error("Invalid invitation. Please contact your team administrator.");
      }

      // Check if invite was already accepted
      if (invite.invite_status !== 'pending') {
        throw new Error("This invitation has already been used. Please contact your team administrator for a new invitation.");
      }

      // Check for duplicate email in TeamMember
      const allMembers = await base44.entities.TeamMember.list();
      const existingMemberByEmail = allMembers.find(m => 
        m.email?.toLowerCase() === data.email.toLowerCase() && m.team_id === invite.team_id
      );

      if (existingMemberByEmail) {
        throw new Error(`A team member with email ${data.email} already exists in this team. Please contact your team administrator.`);
      }

      // Check for duplicate phone in TeamMember
      if (data.phone) {
        const existingMemberByPhone = allMembers.find(m => 
          m.phone === data.phone && m.team_id === invite.team_id
        );

        if (existingMemberByPhone) {
          throw new Error(`A team member with phone number ${data.phone} already exists in this team. Please contact your team administrator.`);
        }
      }

      // Create team member record
      const member = await base44.entities.TeamMember.create({
        team_id: invite.team_id,
        member_name: `${data.first_name} ${data.last_name}`.trim(),
        email: data.email,
        phone: data.phone,
        title: data.title,
        department: data.department,
        hub: data.hub,
        role: invite.role || "member",
        is_active: true,
      });

      // Update invite status to accepted
      await base44.entities.TeamMemberInvite.update(invite.id, {
        invite_status: "accepted",
        accepted_date: new Date().toISOString()
      });

      // Update team member counts and refresh
      const allTeams = await base44.entities.Team.list();
      const team = allTeams.find(t => t.id === invite.team_id);
      if (team) {
        const allMembers = await base44.entities.TeamMember.list();
        const teamMembers = allMembers.filter(m => m.team_id === team.id);
        const activeCount = teamMembers.filter(m => m.is_active).length;

        await base44.entities.Team.update(team.id, {
          total_members: teamMembers.length,
          active_members: activeCount,
          total_hubs: team.total_hubs || 0
        });
      }

      return { member, invite, team };
      },
    onSuccess: () => {
      // Registration complete - user will see success message in UI
    },
    onError: (error) => {
      toast({
        title: "❌ Registration Failed",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // Validate all fields
    if (!formData.first_name || !formData.last_name || !formData.email || !formData.phone) {
      toast({
        title: "Missing Information",
        description: "Please fill in your name, email, and phone number",
        variant: "destructive",
      });
      return;
    }
    
    if (!formData.title || !formData.department) {
      toast({
        title: "Missing Information",
        description: "Please fill in your title and department",
        variant: "destructive",
      });
      return;
    }
    
    if (!formData.password || formData.password !== formData.confirmPassword) {
      toast({
        title: "Password Mismatch",
        description: "Passwords do not match",
        variant: "destructive",
      });
      return;
    }
    
    if (formData.password.length < 6) {
      toast({
        title: "Password Too Short",
        description: "Password must be at least 6 characters",
        variant: "destructive",
      });
      return;
    }
    
    // Submit registration
    registerMutation.mutate(formData);
  };

  if (!inviteCode || !invite) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50 flex items-center justify-center p-4">
        <Card className="max-w-md w-full border-2 border-red-200">
          <CardContent className="p-12 text-center">
            <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-6">
              <span className="text-4xl">❌</span>
            </div>
            <h2 className="text-2xl font-bold text-[#1C323E] mb-4">Invalid Invitation</h2>
            <p className="text-slate-600 mb-6">
              This invitation link is invalid or has expired. Please contact your team administrator for a new invitation.
            </p>
            <Button onClick={() => navigate(createPageUrl("Home"))} variant="outline">
              Go to Home
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  // Check if invite was already accepted
  if (invite.invite_status === 'accepted') {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50 flex items-center justify-center p-4">
        <Card className="max-w-md w-full border-2 border-blue-200">
          <CardContent className="p-12 text-center">
            <div className="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-6">
              <span className="text-4xl">⚠️</span>
            </div>
            <h2 className="text-2xl font-bold text-[#1C323E] mb-4">Invitation Already Used</h2>
            <p className="text-slate-600 mb-6">
              This invitation has already been accepted. If you need access, please contact your team administrator.
            </p>
            <Button onClick={() => navigate(createPageUrl("Home"))} variant="outline">
              Go to Home
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50 flex items-center justify-center p-4">
      <div className="max-w-4xl w-full">
        {/* Header */}
        <div className="text-center mb-8">
          <div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-br from-[#0A39DF] to-[#1C323E] rounded-full mb-4">
            <UserPlus className="w-8 h-8 text-white" />
          </div>
          <h1 className="text-4xl font-bold bg-gradient-to-r from-[#1C323E] to-[#0A39DF] bg-clip-text text-transparent mb-2">
            Join {invite.team_name}
          </h1>
          {invite.hub && (
            <div className="inline-block bg-blue-600 text-white px-6 py-2 rounded-full font-bold mb-3 shadow-lg">
              📍 {invite.hub}
            </div>
          )}
          <p className="text-slate-600">
            You've been invited by {invite.invited_by} as a <strong>{invite.role}</strong>
            {invite.department && <span> in <strong>{invite.department}</strong></span>}
          </p>
        </div>

        <form onSubmit={handleSubmit}>
          {registerMutation.isSuccess ? (
            <Card className="border-2 border-green-200 shadow-xl">
              <CardContent className="p-12 text-center">
                <div className="inline-flex items-center justify-center w-20 h-20 bg-green-100 rounded-full mb-6">
                  <CheckCircle2 className="w-12 h-12 text-green-600" />
                </div>
                <h2 className="text-3xl font-bold text-[#1C323E] mb-4">
                  Welcome to {invite.team_name}! 🎉
                </h2>
                <p className="text-slate-600 mb-2">
                  Your registration has been completed successfully!
                </p>
                <div className="bg-blue-50 border border-blue-200 p-6 rounded-lg mb-8">
                  <h3 className="font-semibold text-blue-900 mb-3 text-lg">Your Profile Summary:</h3>
                  <div className="space-y-2 text-sm text-slate-700">
                    <p><strong>Name:</strong> {formData.first_name} {formData.last_name}</p>
                    <p><strong>Email:</strong> {formData.email}</p>
                    <p><strong>Title:</strong> {formData.title}</p>
                    <p><strong>Department:</strong> {formData.department}</p>
                    {formData.hub && <p><strong>Hub:</strong> {formData.hub}</p>}
                    <p><strong>Team:</strong> {invite.team_name}</p>
                    <p><strong>Role:</strong> {invite.role}</p>
                  </div>
                </div>
                <div className="bg-white border-2 border-blue-600 p-4 rounded-lg mb-6">
                  <p className="text-slate-700 mb-2">
                    <strong>Next Step:</strong> Please sign in with your new credentials to access your dashboard.
                  </p>
                  <p className="text-sm text-slate-500">
                    Use the email <strong>{formData.email}</strong> and the password you just created.
                  </p>
                </div>
                <Button
                  onClick={() => base44.auth.redirectToLogin()}
                  className="w-full bg-blue-600 hover:bg-blue-700 text-white h-12 text-lg font-bold"
                >
                  Sign In Now →
                </Button>
              </CardContent>
            </Card>
          ) : (
            <Card className="border-2 border-slate-200 shadow-xl">
              <CardHeader className="bg-gradient-to-r from-slate-50 to-blue-50 border-b">
                <CardTitle className="text-xl">Complete Your Registration</CardTitle>
                <p className="text-sm text-slate-500 mt-2">Fill in all the details below to join the team</p>
              </CardHeader>
              <CardContent className="p-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  {/* Basic Information */}
                  <div className="md:col-span-2">
                    <div className="flex items-center gap-2 mb-4 pb-2 border-b">
                      <User className="w-5 h-5 text-[#0A39DF]" />
                      <h3 className="font-bold text-[#1C323E]">Basic Information</h3>
                    </div>
                  </div>
                  
                  <div>
                    <Label htmlFor="first_name">First Name *</Label>
                    <Input
                      id="first_name"
                      value={formData.first_name}
                      onChange={(e) => setFormData({ ...formData, first_name: e.target.value })}
                      placeholder="John"
                      className="mt-2"
                    />
                  </div>
                  
                  <div>
                    <Label htmlFor="last_name">Last Name *</Label>
                    <Input
                      id="last_name"
                      value={formData.last_name}
                      onChange={(e) => setFormData({ ...formData, last_name: e.target.value })}
                      placeholder="Doe"
                      className="mt-2"
                    />
                  </div>

                  <div>
                    <Label htmlFor="email">Email *</Label>
                    <Input
                      id="email"
                      type="email"
                      value={formData.email}
                      onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                      placeholder="john@example.com"
                      className="mt-2"
                      disabled={!!invite}
                    />
                  </div>

                  <div>
                    <Label htmlFor="phone">Phone Number *</Label>
                    <Input
                      id="phone"
                      type="tel"
                      value={formData.phone}
                      onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                      placeholder="+1 (555) 123-4567"
                      className="mt-2"
                    />
                  </div>

                  {/* Work Information */}
                  <div className="md:col-span-2">
                    <div className="flex items-center gap-2 mb-4 pb-2 border-b mt-4">
                      <Briefcase className="w-5 h-5 text-[#0A39DF]" />
                      <h3 className="font-bold text-[#1C323E]">Work Information</h3>
                    </div>
                  </div>

                  <div>
                    <Label htmlFor="title">Job Title *</Label>
                    <Input
                      id="title"
                      value={formData.title}
                      onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                      placeholder="e.g., Manager, Coordinator"
                      className="mt-2"
                    />
                  </div>

                  <div>
                    <Label htmlFor="department">Department *</Label>
                    <Select value={formData.department} onValueChange={(value) => setFormData({ ...formData, department: value })}>
                      <SelectTrigger className="mt-2">
                        <SelectValue placeholder="Select department" />
                      </SelectTrigger>
                      <SelectContent>
                        {availableDepartments.length > 0 ? (
                          availableDepartments.map((dept) => (
                            <SelectItem key={dept} value={dept}>
                              {dept}
                            </SelectItem>
                          ))
                        ) : (
                          <SelectItem value="Operations">Operations</SelectItem>
                        )}
                      </SelectContent>
                    </Select>
                  </div>

                  {hubs.length > 0 && (
                    <div className="md:col-span-2">
                      <Label htmlFor="hub">Hub Location</Label>
                      <Select value={formData.hub} onValueChange={(value) => setFormData({ ...formData, hub: value })}>
                        <SelectTrigger className="mt-2">
                          <SelectValue placeholder="Select hub location" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value={null}>No Hub</SelectItem>
                          {hubs.map((hub) => (
                            <SelectItem key={hub.id} value={hub.hub_name}>
                              {hub.hub_name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      {formData.hub && (
                        <p className="text-xs text-blue-600 font-semibold mt-1 bg-blue-50 p-2 rounded">📍 You're joining {formData.hub}!</p>
                      )}
                    </div>
                  )}

                  {/* Account Security */}
                  <div className="md:col-span-2">
                    <div className="flex items-center gap-2 mb-4 pb-2 border-b mt-4">
                      <Lock className="w-5 h-5 text-[#0A39DF]" />
                      <h3 className="font-bold text-[#1C323E]">Account Security</h3>
                    </div>
                  </div>

                  <div>
                    <Label htmlFor="password">Password *</Label>
                    <Input
                      id="password"
                      type="password"
                      value={formData.password}
                      onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                      placeholder="••••••••"
                      className="mt-2"
                    />
                    <p className="text-xs text-slate-500 mt-1">Minimum 6 characters</p>
                  </div>

                  <div>
                    <Label htmlFor="confirmPassword">Confirm Password *</Label>
                    <Input
                      id="confirmPassword"
                      type="password"
                      value={formData.confirmPassword}
                      onChange={(e) => setFormData({ ...formData, confirmPassword: e.target.value })}
                      placeholder="••••••••"
                      className="mt-2"
                    />
                  </div>
                </div>

                <Button
                  type="submit"
                  disabled={registerMutation.isPending}
                  className="w-full mt-8 bg-blue-600 hover:bg-blue-700 text-white h-12 text-lg font-bold"
                >
                  {registerMutation.isPending ? 'Creating Account...' : '🚀 Complete Registration'}
                </Button>
              </CardContent>
            </Card>
          )}
        </form>
      </div>
    </div>
  );
}