'use client';

import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '@/store/store';
import { fetchTeams, removeTeamMember, fetchTeamDetail } from '@/store/slices/adminSlice';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Plus, Trash2, ArrowLeft, Users2 } from 'lucide-react';
import Link from 'next/link';
import RoleBadge from '../../../components/RoleBadge';
import TeamMemberDialog from '../../../components/TeamMemberDialog';
import { toast } from 'sonner';
import type { AdminTeam } from '@/store/slices/adminSlice';

export default function ClientTeamsPage() {
  const params = useParams();
  const clientId = params.id as string;
  const dispatch = useDispatch<AppDispatch>();
  const { teams } = useSelector((state: RootState) => state.admin);
  const [selectedTeam, setSelectedTeam] = useState<AdminTeam | null>(null);
  const [teamDetail, setTeamDetail] = useState<any>(null);
  const [addMemberOpen, setAddMemberOpen] = useState(false);

  useEffect(() => {
    dispatch(fetchTeams(clientId));
  }, [dispatch, clientId]);

  const loadTeamDetail = async (teamId: string) => {
    const result = await dispatch(fetchTeamDetail(teamId)).unwrap();
    setTeamDetail(result);
    setSelectedTeam(teams.find((t) => t.id === teamId) || null);
  };

  const handleRemoveMember = async (teamId: string, userId: string) => {
    try {
      await dispatch(removeTeamMember({ teamId, userId })).unwrap();
      toast.success('Member removed');
      loadTeamDetail(teamId);
    } catch (err) {
      toast.error(typeof err === 'string' ? err : 'Failed to remove member');
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-3">
        <Link href={`/admin/clients/${clientId}`}>
          <Button variant="ghost" size="sm">
            <ArrowLeft className="w-4 h-4 mr-1" />Back
          </Button>
        </Link>
        <h1 className="text-2xl font-semibold">Teams</h1>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="space-y-3">
          {teams.map((team) => (
            <Card
              key={team.id}
              className={`cursor-pointer hover:shadow-md transition-shadow ${selectedTeam?.id === team.id ? 'ring-2 ring-[#5146E5]' : ''}`}
              onClick={() => loadTeamDetail(team.id)}
            >
              <CardHeader className="py-3 px-4">
                <CardTitle className="text-sm flex items-center gap-2">
                  <Users2 className="w-4 h-4" />
                  {team.name}
                  {team.is_default && (
                    <span className="text-xs bg-yellow-100 text-yellow-700 px-1.5 py-0.5 rounded">Default</span>
                  )}
                </CardTitle>
              </CardHeader>
            </Card>
          ))}
          {teams.length === 0 && (
            <p className="text-sm text-gray-500">No teams for this client.</p>
          )}
        </div>

        <div className="lg:col-span-2">
          {teamDetail ? (
            <div className="bg-white rounded-lg border p-6 space-y-4">
              <div className="flex items-center justify-between">
                <h2 className="text-lg font-semibold">{teamDetail.name} — Members</h2>
                <Button size="sm" onClick={() => setAddMemberOpen(true)}>
                  <Plus className="w-4 h-4 mr-1" />Add Member
                </Button>
              </div>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Name</TableHead>
                    <TableHead>Email</TableHead>
                    <TableHead>Role</TableHead>
                    <TableHead></TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {teamDetail.members?.map((m: any) => (
                    <TableRow key={m.id}>
                      <TableCell>{m.display_name}</TableCell>
                      <TableCell>{m.email}</TableCell>
                      <TableCell><RoleBadge role={m.role} /></TableCell>
                      <TableCell>
                        <Button
                          variant="ghost"
                          size="sm"
                          className="text-red-500 hover:text-red-700"
                          onClick={() => handleRemoveMember(teamDetail.id, m.id)}
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                  {(!teamDetail.members || teamDetail.members.length === 0) && (
                    <TableRow>
                      <TableCell colSpan={4} className="text-center text-gray-500 py-4">
                        No members yet.
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>

              <TeamMemberDialog
                open={addMemberOpen}
                onOpenChange={(open) => {
                  setAddMemberOpen(open);
                  if (!open) loadTeamDetail(teamDetail.id);
                }}
                teamId={teamDetail.id}
                existingMemberIds={teamDetail.members?.map((m: any) => m.id) || []}
              />
            </div>
          ) : (
            <div className="flex items-center justify-center h-48 text-gray-400">
              Select a team to view members
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
