'use client';

import { useCallback, useEffect, useState } from 'react';
import { Users, Plus, UserPlus, Trash2, Loader2, Crown } from 'lucide-react';
import { apiClient } from '@/lib/apiClient';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useToast } from '@/components/ui/toast';
import { useI18n } from '@/lib/i18n';
import { PageHeader } from '@/components/layout/page-header';

interface WorkspaceMember {
  id: string;
  user_id: string;
  role: string;
  created_at: string | null;
}

interface Workspace {
  id: string;
  name: string;
  owner_id: string;
  member_count: number;
  members: WorkspaceMember[];
  my_role?: string;
  seat_limit?: number; // -1 = illimité
}

export default function TeamsPage() {
  const notify = useToast();
  const { t } = useI18n();
  const [workspaces, setWorkspaces] = useState<Workspace[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [needsBusiness, setNeedsBusiness] = useState(false);
  const [newName, setNewName] = useState('');
  const [isCreating, setIsCreating] = useState(false);
  const [inviteEmail, setInviteEmail] = useState<Record<string, string>>({});
  const [inviteRole, setInviteRole] = useState<Record<string, string>>({});
  const [busyWs, setBusyWs] = useState<string | null>(null);
  const [confirmDeleteMember, setConfirmDeleteMember] = useState<{ wsId: string; userId: string } | null>(null);

  const load = useCallback(async () => {
    setIsLoading(true);
    try {
      const res = await apiClient.get<{ data: Workspace[] }>('/api/v1/workspaces');
      setWorkspaces(res.data);
      setNeedsBusiness(false);
    } catch (err) {
      const message = err instanceof Error ? err.message : '';
      if (message.includes('Business') || message.includes('PLAN_REQUIRED')) {
        setNeedsBusiness(true);
      } else {
        notify.error({ title: t('teams.error.title'), description: message || t('teams.error.load') });
      }
    } finally {
      setIsLoading(false);
    }
  }, [notify]);

  useEffect(() => {
    load();
  }, [load]);

  const createWorkspace = async () => {
    if (!newName.trim()) return;
    setIsCreating(true);
    try {
      await apiClient.post('/api/v1/workspaces', { name: newName.trim() });
      setNewName('');
      notify.success({ title: t('teams.created'), description: t('teams.createdDesc') });
      await load();
    } catch (err) {
      notify.error({
        title: t('teams.createFailed'),
        description: err instanceof Error ? err.message : undefined,
      });
    } finally {
      setIsCreating(false);
    }
  };

  const inviteMember = async (wsId: string) => {
    const email = (inviteEmail[wsId] || '').trim();
    if (!email) return;
    setBusyWs(wsId);
    try {
      await apiClient.post(`/api/v1/workspaces/${wsId}/members`, {
        email,
        role: inviteRole[wsId] || 'member',
      });
      setInviteEmail((p) => ({ ...p, [wsId]: '' }));
      notify.success({ title: t('teams.memberAdded'), description: email });
      await load();
    } catch (err) {
      notify.error({
        title: t('teams.addFailed'),
        description: err instanceof Error ? err.message : undefined,
      });
    } finally {
      setBusyWs(null);
    }
  };

  const removeMember = async (wsId: string, userId: string) => {
    setBusyWs(wsId);
    try {
      await apiClient.delete(`/api/v1/workspaces/${wsId}/members/${userId}`);
      await load();
    } catch (err) {
      notify.error({
        title: t('teams.removeFailed'),
        description: err instanceof Error ? err.message : undefined,
      });
    } finally {
      setBusyWs(null);
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-16">
        <Loader2 className="size-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <PageHeader
        pill={t('teams.pill')}
        titleBase={t('teams.titleBase')}
        titleAccent={t('teams.titleAccent')}
        subtitle={t('teams.subtitle')}
      />

      {needsBusiness ? (
        <div className="rounded-lg border border-border bg-card p-6 text-center">
          <p className="text-sm text-muted-foreground">
            {t('teams.needsBusiness')}
          </p>
        </div>
      ) : (
        <>
          <div className="flex flex-wrap items-end gap-3 rounded-lg border border-border bg-card p-4">
            <div className="flex-1 min-w-56 space-y-1.5">
              <Label htmlFor="ws-name">{t('teams.newWorkspace')}</Label>
              <Input
                id="ws-name"
                placeholder={t('teams.newPlaceholder')}
                value={newName}
                onChange={(e) => setNewName(e.target.value)}
              />
            </div>
            <Button onClick={createWorkspace} disabled={isCreating || !newName.trim()}>
              {isCreating ? <Loader2 className="size-4 animate-spin" /> : <Plus className="size-4" />}
              {t('teams.create')}
            </Button>
          </div>

          <div className="space-y-4">
            {workspaces.map((ws) => (
              <div key={ws.id} className="rounded-lg border border-border bg-card p-4 space-y-4">
                <div className="flex items-center justify-between gap-2">
                  <div className="flex items-center gap-2">
                    <span className="font-medium text-foreground">{ws.name}</span>
                    {ws.my_role === 'owner' && (
                      <Badge className="gap-1 bg-amber-500/15 text-amber-600 border-amber-500/30">
                        <Crown className="size-3" /> {t('teams.owner')}
                      </Badge>
                    )}
                  </div>
                  <span className="text-xs text-muted-foreground">
                    {ws.seat_limit === -1
                      ? t('teams.seatsUnlimited', { count: ws.member_count })
                      : t('teams.seats', { count: ws.member_count, limit: ws.seat_limit ?? '?' })}
                  </span>
                </div>

                <ul className="divide-y divide-border rounded-md border border-border">
                  {ws.members.map((m) => {
                    const isConfirming = confirmDeleteMember?.wsId === ws.id && confirmDeleteMember?.userId === m.user_id;
                    return (
                      <li key={m.id} className="flex items-center justify-between px-3 py-2 text-sm">
                        <span className="flex items-center gap-2">
                          <span className="text-muted-foreground">{m.user_id.slice(0, 8)}…</span>
                          <Badge variant="outline">{m.role}</Badge>
                        </span>
                        {m.role !== 'owner' && (
                          isConfirming ? (
                            <div className="flex items-center gap-1.5 animate-fade-in">
                              <span className="text-xs text-red-500 font-medium mr-1">
                                {t('teams.removeConfirm')}
                              </span>
                              <Button
                                size="sm"
                                variant="destructive"
                                className="h-6 px-2 text-[10px]"
                                disabled={busyWs === ws.id}
                                onClick={async () => {
                                  await removeMember(ws.id, m.user_id);
                                  setConfirmDeleteMember(null);
                                }}
                              >
                                {t('teams.confirm')}
                              </Button>
                              <Button
                                size="sm"
                                variant="ghost"
                                className="h-6 px-2 text-[10px]"
                                onClick={() => setConfirmDeleteMember(null)}
                              >
                                {t('teams.cancel')}
                              </Button>
                            </div>
                          ) : (
                            <Button
                              size="sm"
                              variant="ghost"
                              className="h-7 px-2 text-red-500"
                              disabled={busyWs === ws.id || ws.my_role === 'member'}
                              onClick={() => setConfirmDeleteMember({ wsId: ws.id, userId: m.user_id })}
                              title={t('teams.removeMember')}
                            >
                              <Trash2 className="size-3.5" />
                            </Button>
                          )
                        )}
                      </li>
                    );
                  })}
                </ul>

                {(ws.my_role === 'owner' || ws.my_role === 'admin') && (
                  <div className="flex flex-wrap items-end gap-2">
                    <div className="flex-1 min-w-48 space-y-1.5">
                      <Label htmlFor={`invite-${ws.id}`}>{t('teams.addMember')}</Label>
                      <Input
                        id={`invite-${ws.id}`}
                        type="email"
                        placeholder={t('teams.emailPlaceholder')}
                        value={inviteEmail[ws.id] || ''}
                        onChange={(e) =>
                          setInviteEmail((p) => ({ ...p, [ws.id]: e.target.value }))
                        }
                      />
                    </div>
                    <Select
                      value={inviteRole[ws.id] || 'member'}
                      onValueChange={(v) => setInviteRole((p) => ({ ...p, [ws.id]: v }))}
                    >
                      <SelectTrigger className="w-32">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="member">{t('teams.role.member')}</SelectItem>
                        <SelectItem value="admin">{t('teams.role.admin')}</SelectItem>
                      </SelectContent>
                    </Select>
                    <Button
                      size="sm"
                      onClick={() => inviteMember(ws.id)}
                      disabled={busyWs === ws.id || !(inviteEmail[ws.id] || '').trim()}
                    >
                      {busyWs === ws.id ? (
                        <Loader2 className="size-3.5 animate-spin" />
                      ) : (
                        <UserPlus className="size-3.5" />
                      )}
                      {t('teams.invite')}
                    </Button>
                  </div>
                )}
              </div>
            ))}

            {workspaces.length === 0 && (
              <div className="rounded-lg border border-border bg-card p-6 text-center text-sm text-muted-foreground">
                {t('teams.empty')}
              </div>
            )}
          </div>
        </>
      )}
    </div>
  );
}
