import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { Button } from "@/common/components/ui/button";
import { Input } from "@/common/components/ui/input";
import { Label } from "@/common/components/ui/label";
import { ArrowLeft, Loader2, Save, Mail, Phone, User, Award } from "lucide-react";
import DashboardLayout from "@/features/layouts/DashboardLayout";
import { useCreateStaff } from "@/dataconnect-generated/react";
import { dataConnect } from "@/features/auth/firebase";
import { useForm, Controller } from "react-hook-form";
import { Checkbox } from "@/common/components/ui/checkbox";
import { BackgroundCheckStatus } from "@/dataconnect-generated";

const COMMON_SKILLS = [
  "Barista",
  "Server",
  "Cook",
  "Dishwasher",
  "Bartender",
  "Manager"
];

interface AddStaffFormData {
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  skills: string[];
}

export default function AddStaff() {
  const navigate = useNavigate();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { mutateAsync: createStaff } = useCreateStaff(dataConnect);

  const { register, handleSubmit, control, formState: { errors } } = useForm<AddStaffFormData>({
    defaultValues: {
      firstName: "",
      lastName: "",
      email: "",
      phone: "",
      skills: []
    }
  });

  const onSubmit = async (data: AddStaffFormData) => {
    setIsSubmitting(true);
    try {
      await createStaff({
        userId: `user_${Math.random().toString(36).substring(2, 11)}`,
        fullName: `${data.firstName} ${data.lastName}`,
        email: data.email,
        phone: data.phone,
        skills: data.skills,
        backgroundCheckStatus: BackgroundCheckStatus.PENDING,
        initial: `${data.firstName.charAt(0)}${data.lastName.charAt(0)}`.toUpperCase(),
      });
      navigate("/staff");
    } catch (error) {
      console.error("Failed to create staff", error);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <DashboardLayout
      title="Add New Staff"
      subtitle="Invite a new team member to join the platform"
      backAction={
        <Button
          variant="ghost"
          onClick={() => navigate("/staff")}
          leadingIcon={<ArrowLeft />}
          className="mb-6 text-muted-foreground hover:bg-primary/5 hover:text-primary rounded-xl transition-premium -ml-2"
        >
          Back to Directory
        </Button>
      }
    >
      <div className="max-w-2xl mx-auto">
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-8 animate-in-slide-up">
          <div className="bg-card/60 backdrop-blur-md border border-border p-8 rounded-3xl shadow-xl space-y-8">
            {/* Identity Section */}
            <div>
              <h3 className="text-sm font-black text-muted-foreground/80 mb-6 flex items-center gap-2 uppercase tracking-wider">
                <User className="w-4 h-4 text-primary" />
                Staff Identity
              </h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-2">
                  <Label className="text-xs font-black text-muted-foreground/80 pl-1">First Name <span className="text-rose-500">*</span></Label>
                  <Input
                    {...register("firstName", { required: "First name is required" })}
                    placeholder="John"
                    className="rounded-xl"
                  />
                  {errors.firstName && <p className="text-xs text-rose-500 font-bold mt-1">{errors.firstName.message}</p>}
                </div>
                <div className="space-y-2">
                  <Label className="text-xs font-black text-muted-foreground/80 pl-1">Last Name <span className="text-rose-500">*</span></Label>
                  <Input
                    {...register("lastName", { required: "Last name is required" })}
                    placeholder="Doe"
                    className="rounded-xl"
                  />
                  {errors.lastName && <p className="text-xs text-rose-500 font-bold mt-1">{errors.lastName.message}</p>}
                </div>
              </div>
            </div>

            {/* Contact Section */}
            <div>
              <h3 className="text-sm font-black text-muted-foreground/80 mb-6 flex items-center gap-2 uppercase tracking-wider">
                <Mail className="w-4 h-4 text-primary" />
                Contact Information
              </h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-2">
                  <Label className="text-xs font-black text-muted-foreground/80 pl-1">Email Address <span className="text-rose-500">*</span></Label>
                  <Input
                    {...register("email", { 
                      required: "Email is required",
                      pattern: {
                        value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
                        message: "Invalid email address"
                      }
                    })}
                    type="email"
                    leadingIcon={<Mail className="w-4 h-4" />}
                    placeholder="john.doe@example.com"
                    className="rounded-xl"
                  />
                  {errors.email && <p className="text-xs text-rose-500 font-bold mt-1">{errors.email.message}</p>}
                </div>
                <div className="space-y-2">
                  <Label className="text-xs font-black text-muted-foreground/80 pl-1">Phone Number <span className="text-rose-500">*</span></Label>
                  <Input
                    {...register("phone", { required: "Phone number is required" })}
                    type="tel"
                    leadingIcon={<Phone className="w-4 h-4" />}
                    placeholder="+1 (555) 000-0000"
                    className="rounded-xl"
                  />
                  {errors.phone && <p className="text-xs text-rose-500 font-bold mt-1">{errors.phone.message}</p>}
                </div>
              </div>
            </div>

            {/* Skills Section */}
            <div>
              <h3 className="text-sm font-black text-muted-foreground/80 mb-6 flex items-center gap-2 uppercase tracking-wider">
                <Award className="w-4 h-4 text-primary" />
                Selection of Skills
              </h3>
              <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                {COMMON_SKILLS.map((skill) => (
                  <Controller
                    key={skill}
                    name="skills"
                    control={control}
                    render={({ field }) => (
                      <div className="flex items-center space-x-3 p-3 rounded-xl hover:bg-primary/5 transition-premium border border-transparent hover:border-primary/10">
                        <Checkbox
                          id={skill}
                          checked={field.value?.includes(skill)}
                          onCheckedChange={(checked) => {
                            const updatedSkills = checked
                              ? [...(field.value || []), skill]
                              : field.value?.filter((s: string) => s !== skill);
                            field.onChange(updatedSkills);
                          }}
                        />
                        <label
                          htmlFor={skill}
                          className="text-sm font-bold leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
                        >
                          {skill}
                        </label>
                      </div>
                    )}
                  />
                ))}
              </div>
            </div>

            {/* Action Buttons */}
            <div className="pt-6 flex gap-4">
              <Button
                type="button"
                variant="outline"
                onClick={() => navigate("/staff")}
                className="flex-1 rounded-2xl font-bold py-6"
              >
                Cancel
              </Button>
              <Button
                type="submit"
                disabled={isSubmitting}
                className="flex-1 rounded-2xl font-bold py-6 shadow-lg shadow-primary/20"
                leadingIcon={isSubmitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
              >
                {isSubmitting ? "Inviting..." : "Send Invitation"}
              </Button>
            </div>
          </div>
        </form>
      </div>=    </DashboardLayout>
  );
}
