import { useState, useMemo} from "react";
import { Link } from "react-router-dom";
import { useSelector } from "react-redux";
import type { RootState } from "@/store/store";
import { useToast } from "@/common/components/ui/use-toast";
import { Button } from "../../../common/components/ui/button";
import { Card, CardContent } from "../../../common/components/ui/card";
import { Badge } from "../../../common/components/ui/badge";
import { UserPlus, Users, Star, ChevronLeft, ChevronRight, Search } from "lucide-react";
import { motion } from "framer-motion";
import DashboardLayout from "@/features/layouts/DashboardLayout";
import { useListStaff, useGetStaffById } from "@/dataconnect-generated/react";
import { dataConnect } from "@/features/auth/firebase";
import { formatDistanceToNow } from "date-fns";

const ITEMS_PER_PAGE = 10;

function StaffActiveStatus({ staffId }: { staffId: string }) {
  const { data: staffDetail, isLoading } = useGetStaffById(dataConnect, { id: staffId });

  const getLastActiveText = (lastActive?: string) => {
    if (!lastActive) return 'Never';
    try {
      const date = new Date(lastActive);
      return formatDistanceToNow(date, { addSuffix: true });
    } catch (e) {
      return 'Invalid date';
    }
  };

  if (isLoading) return <span className="animate-pulse">Loading...</span>;
  return <span>{getLastActiveText(staffDetail?.staff?.updatedAt)}</span>;
}

export default function StaffList() {
  const { toast } = useToast();
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [skillsFilter, setSkillsFilter] = useState<string[]>([]);
  const [ratingRange, setRatingRange] = useState<[number, number]>([0, 5]);
  const [currentPage, setCurrentPage] = useState(1);

  const user = useSelector((state: RootState) => state.auth.user);
  const isAdmin = user?.userRole === "admin" || user?.userRole === "ADMIN";

  const { data: staffData, isLoading } = useListStaff(dataConnect);

  const handleRestrictedAction = (e: React.MouseEvent) => {
    if (!isAdmin) {
      e.preventDefault();
      toast({
        title: "Access Restricted",
        description: "Only administrators can perform this action.",
        variant: "destructive"
      });
    }
  };

  const staff = useMemo(() => {
    return staffData?.staffs || [];
  }, [staffData]);

  const allSkills = useMemo(() => {
    const skillSet = new Set<string>();
    staff.forEach(member => {
      if (member.skills && Array.isArray(member.skills)) {
        member.skills.forEach(skill => skillSet.add(skill));
      }
    });
    return Array.from(skillSet).sort();
  }, [staff]);

  const filteredStaff = useMemo(() => {
    return staff.filter(member => {
      const matchesSearch = !searchTerm ||
        member.fullName?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        member.email?.toLowerCase().includes(searchTerm.toLowerCase());

      const matchesStatus = statusFilter === "all"; // status field is missing in current schema

      const matchesSkills = skillsFilter.length === 0 ||
        (member.skills && skillsFilter.some(skill => member.skills?.includes(skill)));

      const rating = member.averageRating || 0;
      const matchesRating = rating >= ratingRange[0] && rating <= ratingRange[1];

      return matchesSearch && matchesStatus && matchesSkills && matchesRating;
    });
  }, [staff, searchTerm, statusFilter, skillsFilter, ratingRange]);

  const totalPages = Math.ceil(filteredStaff.length / ITEMS_PER_PAGE);
  const paginatedStaff = useMemo(() => {
    const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
    return filteredStaff.slice(startIndex, startIndex + ITEMS_PER_PAGE);
  }, [filteredStaff, currentPage]);

  const handleSkillToggle = (skill: string) => {
    setSkillsFilter(prev =>
      prev.includes(skill)
        ? prev.filter(s => s !== skill)
        : [...prev, skill]
    );
    setCurrentPage(1);
  };

  const getStatusColor = (status?: string) => {
    switch (status?.toLowerCase()) {
      case 'active':
        return 'bg-emerald-500/10 text-emerald-600 border-emerald-500/20';
      case 'pending':
        return 'bg-amber-500/10 text-amber-600 border-amber-500/20';
      case 'suspended':
        return 'bg-rose-500/10 text-rose-600 border-rose-500/20';
      default:
        return 'bg-muted/50 text-muted-foreground';
    }
  };

  return (
    <DashboardLayout
      title="Staff Directory"
      subtitle={`${filteredStaff.length} staff members`}
      actions={
        <Link to="/staff/add" onClick={handleRestrictedAction}>
          <Button 
            leadingIcon={<UserPlus />}
            className={!isAdmin ? "opacity-50 cursor-not-allowed hover:opacity-50" : ""}
          >
            Add New Staff
          </Button>
        </Link>
      }
    >

      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5, delay: 0.1 }}
        className="mb-8"
      >
        <Card className="border-border/50! glass overflow-visible">
          <CardContent className="p-4">
            <div className="space-y-4">
              {/* Search Bar */}
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                <input
                  type="text"
                  placeholder="Search by name or email..."
                  value={searchTerm}
                  onChange={(e) => {
                    setSearchTerm(e.target.value);
                    setCurrentPage(1);
                  }}
                  className="w-full pl-10 pr-4 py-2.5 bg-background border border-border/50 rounded-xl text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all"
                />
              </div>

              {/* Filters Row */}
              <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                {/* Status Filter */}
                <div className="flex flex-col gap-2">
                  <label className="text-xs font-bold uppercase text-muted-foreground">Status</label>
                  <select
                    value={statusFilter}
                    onChange={(e) => {
                      setStatusFilter(e.target.value);
                      setCurrentPage(1);
                    }}
                    className="px-3 py-2 bg-background border border-border/50 rounded-xl text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all"
                  >
                    <option value="all">All Status</option>
                    <option value="active">Active</option>
                    <option value="pending">Pending</option>
                    <option value="suspended">Suspended</option>
                  </select>
                </div>

                {/* Rating Range Filter */}
                <div className="flex flex-col gap-2">
                  <label className="text-xs font-bold uppercase text-muted-foreground">Rating Range</label>
                  <div className="space-y-2">
                    <div className="flex gap-2 mt-1">
                      <input
                        type="number"
                        min="0"
                        max="5"
                        step="0.1"
                        value={ratingRange[0].toFixed(1)}
                        onChange={(e) => {
                          const val = parseFloat(e.target.value);
                          if (val <= ratingRange[1]) {
                            setRatingRange([val, ratingRange[1]]);
                            setCurrentPage(1);
                          }
                        }}
                        className="w-full px-2 py-1.5 bg-background border border-border/50 rounded-lg text-foreground text-xs focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all"
                        placeholder="Min"
                      />
                      <input
                        type="number"
                        min="0"
                        max="5"
                        step="0.1"
                        value={ratingRange[1].toFixed(1)}
                        onChange={(e) => {
                          const val = parseFloat(e.target.value);
                          if (val >= ratingRange[0]) {
                            setRatingRange([ratingRange[0], val]);
                            setCurrentPage(1);
                          }
                        }}
                        className="w-full px-2 py-1.5 bg-background border border-border/50 rounded-lg text-foreground text-xs focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all"
                        placeholder="Max"
                      />
                    </div>
                  </div>
                </div>

                {/* Skills Filter Label */}
                <div className="flex flex-col gap-2">
                  <label className="text-xs font-bold uppercase text-muted-foreground">Skills</label>
                  <button
                    onClick={() => {
                      const container = document.getElementById('skills-dropdown');
                      if (container) {
                        container.classList.toggle('hidden');
                      }
                    }}
                    className="px-3 py-2 bg-background border border-border/50 rounded-xl text-foreground text-sm text-left focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all"
                  >
                    {skillsFilter.length === 0 ? 'All Skills' : `${skillsFilter.length} selected`}
                  </button>
                </div>

                {/* Clear Filters */}
                <div className="flex items-center mt-6 md:mt-0">
                  <button
                    onClick={() => {
                      setSearchTerm("");
                      setStatusFilter("all");
                      setSkillsFilter([]);
                      setRatingRange([0, 5]);
                      setCurrentPage(1);
                    }}
                    className="w-full px-3 py-2 mt-2 bg-muted/50 hover:bg-muted/70 border border-border/50 rounded-xl text-foreground text-sm font-medium transition-colors"
                  >
                    Clear All
                  </button>
                </div>
              </div>

              {/* Skills Dropdown */}
              <div
                id="skills-dropdown"
                className="hidden pt-4 border-t border-border/40 grid grid-cols-2 md:grid-cols-4 gap-2"
              >
                {allSkills.map(skill => (
                  <label
                    key={skill}
                    className="flex items-center gap-2 p-2 rounded-lg hover:bg-primary/5 cursor-pointer transition-colors"
                  >
                    <input
                      type="checkbox"
                      checked={skillsFilter.includes(skill)}
                      onChange={() => handleSkillToggle(skill)}
                      className="w-4 h-4 rounded border-border/50 text-primary focus:ring-2 focus:ring-primary/20"
                    />
                    <span className="text-sm text-foreground">{skill}</span>
                  </label>
                ))}
              </div>
            </div>
          </CardContent>
        </Card>
      </motion.div>

      {isLoading ? (
        <div className="space-y-4">
          {[...Array(5)].map((_, i) => (
            <div key={i} className="h-20 bg-card border border-border/50 rounded-2xl overflow-hidden animate-pulse" />
          ))}
        </div>
      ) : paginatedStaff.length > 0 ? (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.3 }}
        >
          <Card className="border-border glass overflow-hidden">
            <CardContent className="p-0">
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-muted/40 border-b border-border">
                    <tr>
                      <th className="text-left py-5 px-6 font-bold text-xs uppercase tracking-wider text-secondary-text">Name</th>
                      <th className="text-left py-5 px-6 font-bold text-xs uppercase tracking-wider text-secondary-text">Photo</th>
                      <th className="text-center py-5 px-6 font-bold text-xs uppercase tracking-wider text-secondary-text">Status</th>
                      <th className="text-left py-5 px-6 font-bold text-xs uppercase tracking-wider text-secondary-text">Skills</th>
                      <th className="text-center py-5 px-6 font-bold text-xs uppercase tracking-wider text-secondary-text">Rating</th>
                      <th className="text-left py-5 px-6 font-bold text-xs uppercase tracking-wider text-secondary-text">Last Active</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border/40">
                    {paginatedStaff.map((member) => (
                      <motion.tr
                        key={member.id}
                        initial={{ opacity: 0, x: -10 }}
                        animate={{ opacity: 1, x: 0 }}
                        className="hover:bg-primary/5 transition-colors group"
                      >
                        <td className="py-4 px-6">
                          <Link 
                            to={`/staff/${member.id}/edit`} 
                            onClick={handleRestrictedAction}
                            className={`font-bold transition-colors hover:underline ${!isAdmin ? "text-muted-foreground cursor-not-allowed" : "text-foreground group-hover:text-primary"}`}
                          >
                            {member.fullName || 'N/A'}
                          </Link>
                        </td>
                        <td className="py-4 px-6">
                          <div className="w-10 h-10 bg-primary/10 rounded-xl flex items-center justify-center text-primary font-black text-sm border border-primary/20 group-hover:scale-110 transition-premium">
                            {member.photoUrl ? (
                              <img src={member.photoUrl} alt={member.fullName} className="w-full h-full rounded-xl object-cover" />
                            ) : (
                              member.fullName?.charAt(0) || '?'
                            )}
                          </div>
                        </td>
                        <td className="py-4 px-6 text-center">
                          <Badge className={`${getStatusColor('Active')} font-black text-xs border`}>
                            Active
                          </Badge>
                        </td>
                        <td className="py-4 px-6">
                          <div className="flex flex-wrap gap-1">
                            {member.skills && member.skills.length > 0 ? (
                              member.skills.slice(0, 2).map((skill) => (
                                <Badge key={skill} variant="secondary" className="bg-muted/50 text-muted-foreground font-bold text-[10px] uppercase">
                                  {skill}
                                </Badge>
                              ))
                            ) : (
                              <span className="text-sm text-muted-foreground">—</span>
                            )}
                            {member.skills && member.skills.length > 2 && (
                              <Badge variant="secondary" className="bg-muted/50 text-muted-foreground font-bold text-[10px] uppercase">
                                +{member.skills.length - 2}
                              </Badge>
                            )}
                          </div>
                        </td>
                        <td className="py-4 px-6 text-center">
                          <div className="flex items-center justify-center gap-1.5 font-bold text-sm">
                            <Star className="w-4 h-4 fill-amber-400 text-amber-400" />
                            {member.averageRating ? member.averageRating.toFixed(1) : '0.0'}
                          </div>
                        </td>
                        <td className="py-4 px-6 text-sm text-muted-foreground">
                          <StaffActiveStatus staffId={member.id} />
                        </td>
                      </motion.tr> 
                    ))}
                  </tbody>
                </table>
              </div>
            </CardContent>
          </Card>

          {/* Pagination */}
          {totalPages > 1 && (
            <motion.div
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.3, delay: 0.1 }}
              className="flex items-center justify-center gap-3 mt-8"
            >
              <Button
                variant="outline"
                size="sm"
                onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                disabled={currentPage === 1}
                leadingIcon={<ChevronLeft className="w-4 h-4" />}
              >
                Previous
              </Button>

              <div className="flex items-center gap-2">
                {Array.from({ length: totalPages }, (_, i) => i + 1).map(page => (
                  <button
                    key={page}
                    onClick={() => setCurrentPage(page)}
                    className={`w-10 h-10 rounded-lg font-bold transition-all ${
                      currentPage === page
                        ? 'bg-primary text-primary-foreground'
                        : 'bg-muted hover:bg-muted/70 text-foreground'
                    }`}
                  >
                    {page}
                  </button>
                ))}
              </div>

              <Button
                variant="outline"
                size="sm"
                onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
                disabled={currentPage === totalPages}
                leadingIcon={<ChevronRight className="w-4 h-4" />}
              >
                Next
              </Button>

              <span className="text-sm text-muted-foreground ml-4">
                Page {currentPage} of {totalPages}
              </span>
            </motion.div>
          )}
        </motion.div>
      ) : (
        <motion.div
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          className="text-center py-24 bg-card/60 backdrop-blur-sm rounded-3xl border border-dashed border-border"
        >
          <div className="w-20 h-20 bg-muted/50 rounded-full flex items-center justify-center mx-auto mb-6">
            <Users className="w-10 h-10 text-muted-foreground" />
          </div>
          <h3 className="text-2xl font-black text-foreground mb-3">No Staff Members Found</h3>
          <p className="text-muted-foreground mb-8 max-w-sm mx-auto font-medium">
            {staff.length === 0
              ? "Your directory is currently empty. Start by adding your first team member."
              : "We couldn't find any staff members matching your current filters."}
          </p>
          <Link to="/staff/add">
            <Button leadingIcon={<UserPlus />}>
              Add First Staff Member
            </Button>
          </Link>
        </motion.div>
      )}
    </DashboardLayout>
  );
}
