'use client';

import { useState, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import type { Role } from '@/modules/Roles/apis/type';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  RiShieldKeyholeLine,
  RiSearchLine,
  RiAddLine,
  RiEditLine,
  RiEyeLine,
  RiTeamLine,
  RiShieldCheckLine,
} from '@remixicon/react';

const RolesList = ({ roles }: { roles: Role[] | null }) => {
  const router = useRouter();
  const [search, setSearch] = useState('');

  const filteredRoles = useMemo(() => {
    if (!roles) return [];
    if (!search.trim()) return roles;
    const q = search.toLowerCase();
    return roles.filter(
      (r) =>
        r.name?.toLowerCase().includes(q) ||
        r.name_ar?.toLowerCase().includes(q) ||
        r.permissions?.some(
          (p) =>
            p.name_en?.toLowerCase().includes(q) ||
            p.section?.toLowerCase().includes(q),
        ),
    );
  }, [roles, search]);

  const totalPermissions = useMemo(() => {
    const all = new Set<string>();
    roles?.forEach((r) => r.permissions?.forEach((p) => all.add(p.name)));
    return all.size;
  }, [roles]);

  const totalSections = useMemo(() => {
    const all = new Set<string>();
    roles?.forEach((r) =>
      r.permissions?.forEach((p) => {
        if (p.section) all.add(p.section);
      }),
    );
    return all.size;
  }, [roles]);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Roles & Permissions</h1>
          <p className="text-muted-foreground text-sm mt-1">
            Manage roles and their associated permissions across your system
          </p>
        </div>
        <Button onClick={() => router.push('/roles/add')}>
          <RiAddLine className="size-4 mr-1.5" />
          Create Role
        </Button>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <Card>
          <CardContent className="flex items-center gap-4 p-5">
            <div className="flex items-center justify-center size-11 rounded-xl bg-primary/10">
              <RiTeamLine className="size-5 text-primary" />
            </div>
            <div>
              <p className="text-2xl font-bold">{roles?.length ?? 0}</p>
              <p className="text-xs text-muted-foreground">Total Roles</p>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="flex items-center gap-4 p-5">
            <div className="flex items-center justify-center size-11 rounded-xl bg-green-500/10">
              <RiShieldCheckLine className="size-5 text-green-600" />
            </div>
            <div>
              <p className="text-2xl font-bold">{totalPermissions}</p>
              <p className="text-xs text-muted-foreground">Unique Permissions</p>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="flex items-center gap-4 p-5">
            <div className="flex items-center justify-center size-11 rounded-xl bg-violet-500/10">
              <RiShieldKeyholeLine className="size-5 text-violet-600" />
            </div>
            <div>
              <p className="text-2xl font-bold">{totalSections}</p>
              <p className="text-xs text-muted-foreground">Permission Sections</p>
            </div>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader className="flex-row items-center justify-between gap-4">
          <CardTitle className="text-base">All Roles</CardTitle>
          <div className="relative w-72">
            <RiSearchLine className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
            <Input
              placeholder="Search roles or permissions..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="pl-9"
            />
          </div>
        </CardHeader>
        <CardContent className="p-0">
          <Table>
            <TableHeader>
              <TableRow className="bg-accent/60">
                <TableHead className="min-w-[200px] h-10">Role Name</TableHead>
                <TableHead className="min-w-[200px] h-10">Role Name (AR)</TableHead>
                <TableHead className="min-w-[120px] h-10 text-center">Permissions</TableHead>
                <TableHead className="min-w-[250px] h-10">Sections</TableHead>
                <TableHead className="min-w-[120px] h-10 text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredRoles.length > 0 ? (
                filteredRoles.map((role) => {
                  const sections = Array.from(
                    new Set(
                      role.permissions?.map((p) => p.section).filter(Boolean),
                    ),
                  );
                  return (
                    <TableRow
                      key={role.id}
                      className="cursor-pointer hover:bg-accent/50 focus:bg-accent/50"
                      onClick={() => router.push(`/roles/${role.id}`)}
                      role="button"
                      tabIndex={0}
                      onKeyDown={(e) => {
                        if (e.key === 'Enter' || e.key === ' ') {
                          e.preventDefault();
                          router.push(`/roles/${role.id}`);
                        }
                      }}
                    >
                      <TableCell>
                        <div className="flex items-center gap-2.5">
                          <div className="flex items-center justify-center size-8 rounded-lg bg-primary/10">
                            <RiShieldKeyholeLine className="size-4 text-primary" />
                          </div>
                          <span className="font-medium text-sm">{role.name}</span>
                        </div>
                      </TableCell>
                      <TableCell className="text-sm text-muted-foreground">
                        {role.name_ar || '-'}
                      </TableCell>
                      <TableCell className="text-center">
                        <Badge variant="info" appearance="outline">
                          {role.permissions?.length ?? 0}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <div className="flex flex-wrap gap-1.5">
                          {sections.slice(0, 3).map((s) => (
                            <Badge
                              key={s}
                              variant="mono"
                              appearance="outline"
                              className="text-xs"
                            >
                              {s}
                            </Badge>
                          ))}
                          {sections.length > 3 && (
                            <Badge variant="secondary" className="text-xs">
                              +{sections.length - 3}
                            </Badge>
                          )}
                          {sections.length === 0 && (
                            <span className="text-xs text-muted-foreground">
                              No sections
                            </span>
                          )}
                        </div>
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex items-center justify-end gap-1">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={(e) => {
                              e.stopPropagation();
                              router.push(`/roles/${role.id}`);
                            }}
                          >
                            <RiEyeLine className="size-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={(e) => {
                              e.stopPropagation();
                              router.push(`/roles/add/${role.id}`);
                            }}
                          >
                            <RiEditLine className="size-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  );
                })
              ) : (
                <TableRow>
                  <TableCell
                    colSpan={5}
                    className="text-center py-12 text-muted-foreground"
                  >
                    {search
                      ? 'No roles match your search'
                      : 'No roles found. Create your first role to get started.'}
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
};

export { RolesList };
