// components/members/MembersList.tsx
import React, { useMemo } from "react"
import { Search, Users, Filter, X, Check, AlertCircle } from "lucide-react"
import { MemberCard } from "./member-card"
import { Member } from "@/lib/types"

interface MembersListProps {
  members: Member[]
  currentUserId: string
  isAdmin: boolean
  updatingMember: string | null
  error: string | null
  success: string | null
  searchQuery: string
  filterRole: "all" | "owner" | "admin" | "member"
  onSearchChange: (query: string) => void
  onFilterChange: (role: "all" | "owner" | "admin" | "member") => void
  onUpdateRole: (memberId: string, newRole: "admin" | "member" | "owner") => void
  onRemove: (memberId: string, memberUsername: string) => void
  onDismissError: () => void
  onDismissSuccess: () => void
  headerIcon?: React.ReactNode
  headerTitle?: string
  headerStats?: string
}

export const MembersList: React.FC<MembersListProps> = ({
  members,
  currentUserId,
  isAdmin,
  updatingMember,
  error,
  success,
  searchQuery,
  filterRole,
  onSearchChange,
  onFilterChange,
  onUpdateRole,
  onRemove,
  onDismissError,
  onDismissSuccess,
  headerIcon,
  headerTitle = "Members",
  headerStats,
}) => {
  const filteredMembers = useMemo(() => {
    return members.filter(member => {
      const matchesSearch = member.username.toLowerCase().includes(searchQuery.toLowerCase())
      const matchesRole = filterRole === "all" || member.role === filterRole
      return matchesSearch && matchesRole
    })
  }, [members, searchQuery, filterRole])

  return (
    <>
      {/* Search and Filter */}
      <div className="p-6 border-b border-border bg-accent/20">
        <div className="flex items-center justify-between gap-4 mb-4">
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-3 mb-2">
              {headerIcon && <div className="p-2 rounded-lg bg-primary/10">{headerIcon}</div>}
              <h2 className="text-xl font-semibold text-foreground">{headerTitle}</h2>
            </div>
            {headerStats && <p className="text-sm text-muted-foreground">{headerStats}</p>}
          </div>
        </div>

        <div className="flex flex-col sm:flex-row gap-3">
          <div className="relative flex-1">
            <Search
              size={18}
              className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground"
            />
            <input
              type="text"
              placeholder="Search members..."
              value={searchQuery}
              onChange={e => onSearchChange(e.target.value)}
              className="w-full pl-10 pr-4 py-2.5 bg-background border border-border rounded-xl focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all text-sm placeholder:text-muted-foreground"
            />
          </div>
          <div className="relative">
            <Filter
              size={18}
              className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground pointer-events-none"
            />
            <select
              value={filterRole}
              onChange={e => onFilterChange(e.target.value as "all" | "owner" | "admin" | "member")}
              className="pl-10 pr-4 py-2.5 bg-background border border-border rounded-xl focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent transition-all text-sm appearance-none cursor-pointer min-w-[140px]"
            >
              <option value="all">All Roles</option>
              <option value="owner">Owner</option>
              <option value="admin">Admin</option>
              <option value="member">Member</option>
            </select>
          </div>
        </div>
      </div>

      {/* Notifications */}
      {error && (
        <div className="mx-6 mt-4 p-4 bg-destructive/10 border border-destructive/20 text-destructive rounded-xl text-sm flex items-start gap-3 animate-in slide-in-from-top-2">
          <AlertCircle size={18} className="flex-shrink-0 mt-0.5" />
          <div className="flex-1">
            <p className="font-medium mb-1">Error</p>
            <p className="text-sm opacity-90">{error}</p>
          </div>
          <button
            onClick={onDismissError}
            className="text-destructive hover:bg-destructive/10 p-1 rounded transition-colors"
          >
            <X size={16} />
          </button>
        </div>
      )}

      {success && (
        <div className="mx-6 mt-4 p-4 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 text-green-700 dark:text-green-400 rounded-xl text-sm flex items-start gap-3 animate-in slide-in-from-top-2">
          <Check size={18} className="flex-shrink-0 mt-0.5" />
          <div className="flex-1">
            <p className="font-medium mb-1">Success</p>
            <p className="text-sm opacity-90">{success}</p>
          </div>
          <button
            onClick={onDismissSuccess}
            className="text-green-700 dark:text-green-400 hover:bg-green-100 dark:hover:bg-green-900/30 p-1 rounded transition-colors"
          >
            <X size={16} />
          </button>
        </div>
      )}

      {/* Members List */}
      {filteredMembers.length === 0 ? (
        <div className="p-12 text-center">
          <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-accent mb-4">
            {searchQuery || filterRole !== "all" ? (
              <Search size={32} className="text-muted-foreground" />
            ) : (
              <Users size={32} className="text-muted-foreground" />
            )}
          </div>
          <p className="text-foreground font-medium">
            {searchQuery || filterRole !== "all" ? "No members found" : "No members"}
          </p>
          <p className="text-sm text-muted-foreground mt-1">
            {searchQuery || filterRole !== "all"
              ? "Try adjusting your search or filter"
              : "Add members to get started"}
          </p>
        </div>
      ) : (
        <div className="divide-y divide-border">
          {filteredMembers.map(member => {
            const canModify = isAdmin && member.user_id !== currentUserId && member.role !== "owner"
            const canRemove = isAdmin && member.role !== "owner" && member.user_id !== currentUserId
            const isLastAdmin =
              (member.role === "admin" || member.role === "owner") &&
              members.filter(m => m.role === "admin" || m.role === "owner").length === 1

            return (
              <MemberCard
                key={member.id}
                member={member}
                currentUserId={currentUserId}
                canModify={canModify}
                canRemove={canRemove}
                isLastAdmin={isLastAdmin}
                updatingMember={updatingMember}
                onUpdateRole={onUpdateRole}
                onRemove={onRemove}
              />
            )
          })}
        </div>
      )}

      {/* Results Count */}
      {(searchQuery || filterRole !== "all") && filteredMembers.length > 0 && (
        <div className="px-6 py-3 bg-accent/20 border-t border-border text-sm text-muted-foreground">
          Showing {filteredMembers.length} of {members.length} members
        </div>
      )}
    </>
  )
}
