import { useState, useMemo } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { useSelector } from "react-redux";
import type { RootState } from "@/store/store";
import { Button } from "@/common/components/ui/button";
import { ArrowLeft, Loader2, Edit, Save, X, AlertCircle } from "lucide-react";
import StaffForm from "./components/StaffForm";
import DashboardLayout from "@/features/layouts/DashboardLayout";
import { useGetStaffById, useUpdateStaff, useCreateActivityLog } from "@/dataconnect-generated/react";
import { dataConnect } from "@/features/auth/firebase";
import type { Staff } from "../type";
import { Badge } from "@/common/components/ui/badge";
import { ActivityIconType, ActivityType } from "@/dataconnect-generated";

export default function EditStaff() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [isEditing, setIsEditing] = useState(false);
  const { user } = useSelector((state: RootState) => state.auth);

  const { data: staffData, isLoading, refetch } = useGetStaffById(dataConnect, { id: id || "" });
  const { mutateAsync: updateStaff } = useUpdateStaff(dataConnect);
  const { mutateAsync: createActivityLog } = useCreateActivityLog(dataConnect);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const isAdmin = user?.userRole === 'admin' || user?.userRole === 'ADMIN';

  const staff = useMemo(() => {
    if (!staffData?.staff) return null;
    const s = staffData.staff;
    return {
      id: s.id,
      employee_name: s.fullName,
      initial: s.initial || "",
      position: s.role || "",
      position_2: "",
      profile_type: s.level || "",
      employment_type: s.employmentType || "",
      manager: s.manager || "",
      email: s.email || "",
      contact_number: s.phone || "",
      phone: s.phone || "",
      photo: s.photoUrl || "",
      status: "Active", // Default for now
      skills: (s.skills as string[]) || [],
      averageRating: s.averageRating || 0,
      reliability_score: s.reliabilityScore || 0,
      shift_coverage_percentage: s.onTimeRate || 0,
      total_shifts: s.totalShifts || 0,
      department: s.department || "",
      city: s.city || "",
      address: s.addres || "", // Using misspelled field from schema
      notes: s.bio || "",
    } as Staff;
  }, [staffData]);

  const handleSubmit = async (staffData: Staff) => {
    if (!id || !isAdmin) return;
    setIsSubmitting(true);
    try {
      await updateStaff({
        id: id,
        fullName: staffData.employee_name,
        role: staffData.position,
        level: staffData.profile_type,
        email: staffData.email,
        phone: staffData.contact_number,
        photoUrl: staffData.photo,
        initial: staffData.initial,
        bio: staffData.notes,
        skills: staffData.skills,
        averageRating: staffData.averageRating,
        reliabilityScore: staffData.reliability_score,
        onTimeRate: staffData.shift_coverage_percentage,
        totalShifts: staffData.total_shifts,
        city: staffData.city,
        addres: staffData.address,
      });

      // Audit Log
      await createActivityLog({
        userId: user?.uid || "system",
        date: new Date().toISOString(),
        title: "Staff Profile Updated",
        description: `Administrator ${user?.displayName || user?.email} updated professional records for ${staffData.employee_name}`,
        activityType: ActivityType.SYSTEM_UPDATE,
        iconType: ActivityIconType.CHECK,
        iconColor: "emerald",
      });

      await refetch();
      setIsEditing(false);
    } catch (error) {
      console.error("Failed to update staff", error);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleCancel = () => {
    setIsEditing(false);
  };

  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[60vh] gap-4">
        <Loader2 className="w-10 h-10 animate-spin text-primary" />
        <p className="text-muted-foreground font-bold text-sm uppercase tracking-widest">Loading Profile...</p>
      </div>
    );
  }

  if (!isAdmin) {
    return (
      <DashboardLayout title="Access Denied" subtitle="Unauthorized Access">
        <div className="flex flex-col items-center justify-center min-h-[40vh] gap-6 bg-card/60 backdrop-blur-md border border-border rounded-3xl p-12 text-center">
          <div className="w-20 h-20 bg-rose-500/10 rounded-full flex items-center justify-center text-rose-500 border border-rose-500/20 shadow-lg">
            <AlertCircle className="w-10 h-10" />
          </div>
          <div className="space-y-2">
            <h2 className="text-2xl font-black text-foreground">Restricted Access</h2>
            <p className="text-muted-foreground max-w-md mx-auto">
              Only administrators are authorized to modify staff professional records. Please contact your system administrator if you believe this is an error.
            </p>
          </div>
          <Button onClick={() => navigate("/staff")} variant="outline" leadingIcon={<ArrowLeft />} className="rounded-xl font-bold">
            Return to Directory
          </Button>
        </div>
      </DashboardLayout>
    );
  }

  return (
    <DashboardLayout
      title={isEditing ? `Edit: ${staff?.employee_name || 'Staff Member'}` : staff?.employee_name || 'Staff Member'}
      subtitle={isEditing ? `Modifying ${staff?.employee_name}'s professional records` : `Management of ${staff?.employee_name}'s professional records`}
      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>
      }
    >
      {staff && (
        <div className="space-y-6">
          {/* Profile Header */}
          <div className="bg-card/60 backdrop-blur-md border border-border p-6 rounded-3xl flex flex-col md:flex-row items-center justify-between gap-6">
            <div className="flex flex-col md:flex-row items-center gap-6 text-center md:text-left">
              <div className="w-24 h-24 bg-primary/10 rounded-2xl flex items-center justify-center text-primary font-black text-3xl border-2 border-primary/20 shadow-xl overflow-hidden group">
                {staff.photo ? (
                  <img src={staff.photo} alt={staff.employee_name} className="w-full h-full object-cover" />
                ) : (
                  staff.employee_name.charAt(0)
                )}
              </div>
              <div>
                <h2 className="text-3xl font-black text-foreground mb-1">{staff.employee_name}</h2>
                <div className="flex flex-wrap items-center justify-center md:justify-start gap-2">
                  <Badge className="bg-emerald-500/10 text-emerald-600 border-emerald-500/20 font-black text-xs uppercase px-3 py-1">
                    {staff.status || 'Active'}
                  </Badge>
                  <span className="text-muted-foreground font-bold text-sm">•</span>
                  <span className="text-muted-foreground font-bold text-sm">{staff.position || 'No Role Assigned'}</span>
                  {staff.profile_type && (
                    <>
                      <span className="text-muted-foreground font-bold text-sm">•</span>
                      <span className="text-primary font-bold text-sm">{staff.profile_type}</span>
                    </>
                  )}
                </div>
              </div>
            </div>

            <div className="flex gap-3">
              {!isEditing ? (
                <Button 
                  onClick={() => setIsEditing(true)} 
                  variant="secondary"
                  leadingIcon={<Edit className="w-4 h-4" />}
                  className="rounded-xl px-6 font-bold"
                >
                  Edit Profile
                </Button>
              ) : (
                <>
                  <Button
                    onClick={handleCancel}
                    variant="outline"
                    disabled={isSubmitting}
                    leadingIcon={<X className="w-4 h-4" />}
                    className="rounded-xl font-bold"
                  >
                    Cancel
                  </Button>
                  <Button
                    onClick={() => {
                      const form = document.querySelector('form');
                      if (form) form.requestSubmit();
                    }}
                    disabled={isSubmitting}
                    leadingIcon={isSubmitting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
                    className="rounded-xl px-6 font-bold"
                  >
                    {isSubmitting ? 'Saving...' : 'Save Changes'}
                  </Button>
                </>
              )}
            </div>
          </div>

          <StaffForm
            staff={staff}
            onSubmit={handleSubmit}
            isSubmitting={isSubmitting}
            disabled={!isEditing}
          />
        </div>
      )}
    </DashboardLayout>
  );
}
