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
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
import React, { useState, useEffect } from "react";
import Link from "next/link";
import { Typography } from "antd";
import { teamDeleteCall, teamUpdateCall, teamInfoCall, Organization, DEFAULT_ORGANIZATION } from "./networking";
import TeamMemberModal from "@/components/team/edit_membership";
import { fetchTeams } from "./common_components/fetch_teams";
import {
  InformationCircleIcon,
  PencilAltIcon,
  PencilIcon,
  RefreshIcon,
  StatusOnlineIcon,
  TrashIcon,
} from "@heroicons/react/outline";
import {
  Button as Button2,
  Modal,
  Form,
  Input,
  Select as Select2,
  message,
  Tooltip
} from "antd";
import NumericalInput from "./shared/numerical_input";
import { fetchAvailableModelsForTeamOrKey, getModelDisplayName, unfurlWildcardModelsInList } from "./key_team_helpers/fetch_available_models_team_key";
import { Select, SelectItem } from "@tremor/react";
import { InfoCircleOutlined } from '@ant-design/icons';
import { getGuardrailsList } from "./networking";
import TeamInfoView from "@/components/team/team_info";
import TeamSSOSettings from "@/components/TeamSSOSettings";
import { isAdminRole } from "@/utils/roles";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeaderCell,
  TableRow,
  TextInput,
  Card,
  Icon,
  Button,
  Badge,
  Col,
  Text,
  Grid,
  Accordion,
  AccordionHeader,
  AccordionBody,
  TabGroup,
  TabList,
  TabPanel,
  TabPanels,
  Tab
} from "@tremor/react";
import { CogIcon } from "@heroicons/react/outline";
import AvailableTeamsPanel from "@/components/team/available_teams";
import type { Team } from "./key_team_helpers/key_list";
const isLocal = process.env.NODE_ENV === "development";
const proxyBaseUrl = isLocal ? "http://localhost:4000" : null;
if (isLocal != true) {
  console.log = function() {};
}
interface TeamProps {
  teams: Team[] | null;
  searchParams: any;
  accessToken: string | null;
  setTeams: React.Dispatch<React.SetStateAction<Team[] | null>>;
  userID: string | null;
  userRole: string | null;
  organizations: Organization[] | null;
}

interface FilterState {
  team_id: string;
  team_alias: string;
  organization_id: string;
  sort_by: string;
  sort_order: 'asc' | 'desc';
}

interface EditTeamModalProps {
  visible: boolean;
  onCancel: () => void;
  team: any; // Assuming TeamType is a type representing your team object
  onSubmit: (data: FormData) => void; // Assuming FormData is the type of data to be submitted
}

import {
  teamCreateCall,
  teamMemberAddCall,
  teamMemberUpdateCall,
  Member,
  modelAvailableCall,
  v2TeamListCall
} from "./networking";
import { updateExistingKeys } from "@/utils/dataUtils";

const getOrganizationModels = (organization: Organization | null, userModels: string[]) => {
  let tempModelsToPick = [];

  if (organization) {
    if (organization.models.length > 0) {
      console.log(`organization.models: ${organization.models}`);
      tempModelsToPick = organization.models;
    } else {
      // show all available models if the team has no models set
      tempModelsToPick = userModels;
    }
  } else {
    // no team set, show all available models
    tempModelsToPick = userModels;
  }

  return unfurlWildcardModelsInList(tempModelsToPick, userModels);
}

const Teams: React.FC<TeamProps> = ({
  teams,
  searchParams,
  accessToken,
  setTeams,
  userID,
  userRole,
  organizations
}) => {
  const [lastRefreshed, setLastRefreshed] = useState("");
  const [currentOrg, setCurrentOrg] = useState<Organization | null>(null);
  const [currentOrgForCreateTeam, setCurrentOrgForCreateTeam] = useState<Organization | null>(null);
  const [showFilters, setShowFilters] = useState(false);
  const [filters, setFilters] = useState<FilterState>({
    team_id: "",
    team_alias: "",
    organization_id: "",
    sort_by: "created_at",
    sort_order: "desc"
  });

  useEffect(() => {
    console.log(`inside useeffect - ${lastRefreshed}`)
    if (accessToken) {
      // Call your function here
      fetchTeams(accessToken, userID, userRole, currentOrg, setTeams)
    }
    handleRefreshClick()
  }, [lastRefreshed]);

  const [form] = Form.useForm();
  const [memberForm] = Form.useForm();
  const { Title, Paragraph } = Typography;
  const [value, setValue] = useState("");
  const [editModalVisible, setEditModalVisible] = useState(false);

  const [selectedTeam, setSelectedTeam] = useState<null | any>(
    null
  );
  const [selectedTeamId, setSelectedTeamId] = useState<string | null>(null);
  const [editTeam, setEditTeam] = useState<boolean>(false);

  const [isTeamModalVisible, setIsTeamModalVisible] = useState(false);
  const [isAddMemberModalVisible, setIsAddMemberModalVisible] = useState(false);
  const [isEditMemberModalVisible, setIsEditMemberModalVisible] = useState(false);
  const [userModels, setUserModels] = useState<string[]>([]);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [teamToDelete, setTeamToDelete] = useState<string | null>(null);
  const [modelsToPick, setModelsToPick] = useState<string[]>([]);
  


  const [perTeamInfo, setPerTeamInfo] = useState<Record<string, any>>({});

  // Add this state near the other useState declarations
  const [guardrailsList, setGuardrailsList] = useState<string[]>([]);

  useEffect(() => {
    console.log(`currentOrgForCreateTeam: ${currentOrgForCreateTeam}`);
    const models = getOrganizationModels(currentOrgForCreateTeam, userModels);
    console.log(`models: ${models}`);
    setModelsToPick(models);
    form.setFieldValue('models', []);
  }, [currentOrgForCreateTeam, userModels]);

  // Add this useEffect to fetch guardrails
  useEffect(() => {
    const fetchGuardrails = async () => {
      try {
        if (accessToken == null) {
          return;
        }

        const response = await getGuardrailsList(accessToken);
        const guardrailNames = response.guardrails.map(
          (g: { guardrail_name: string }) => g.guardrail_name
        );
        setGuardrailsList(guardrailNames);
      } catch (error) {
        console.error("Failed to fetch guardrails:", error);
      }
    };

    fetchGuardrails();
  }, [accessToken]);


  const handleOk = () => {
    setIsTeamModalVisible(false);
    form.resetFields();
  };

  const handleMemberOk = () => {
    setIsAddMemberModalVisible(false);
    setIsEditMemberModalVisible(false);
    memberForm.resetFields();
  };

  const handleCancel = () => {
    setIsTeamModalVisible(false);

    form.resetFields();
  };

  const handleMemberCancel = () => {
    setIsAddMemberModalVisible(false);
    setIsEditMemberModalVisible(false);
    memberForm.resetFields();
  };

  const handleDelete = async (team_id: string) => {
    // Set the team to delete and open the confirmation modal
    setTeamToDelete(team_id);
    setIsDeleteModalOpen(true);
  };

  const confirmDelete = async () => {
    if (teamToDelete == null || teams == null || accessToken == null) {
      return;
    }

    try {
      await teamDeleteCall(accessToken, teamToDelete);
      // Successfully completed the deletion. Update the state to trigger a rerender.
      fetchTeams(accessToken, userID, userRole, currentOrg, setTeams)
    } catch (error) {
      console.error("Error deleting the team:", error);
      // Handle any error situations, such as displaying an error message to the user.
    }

    // Close the confirmation modal and reset the teamToDelete
    setIsDeleteModalOpen(false);
    setTeamToDelete(null);
  };

  const cancelDelete = () => {
    // Close the confirmation modal and reset the teamToDelete
    setIsDeleteModalOpen(false);
    setTeamToDelete(null);
  };

  useEffect(() => {
    const fetchUserModels = async () => {
      try {
        if (userID === null || userRole === null || accessToken === null) {
          return;
        }
        const models = await fetchAvailableModelsForTeamOrKey(userID, userRole, accessToken);
        if (models) {
          setUserModels(models);
        }
      } catch (error) {
        console.error("Error fetching user models:", error);
      }
    };

    fetchUserModels();
  }, [accessToken, userID, userRole, teams]);

  const handleCreate = async (formValues: Record<string, any>) => {
    try {
      console.log(`formValues: ${JSON.stringify(formValues)}`);
      if (accessToken != null) {
        const newTeamAlias = formValues?.team_alias;
        const existingTeamAliases = teams?.map((t) => t.team_alias) ?? [];
        let organizationId = formValues?.organization_id || currentOrg?.organization_id;
        if (organizationId === "" || typeof organizationId !== 'string') {
          formValues.organization_id = null;
        } else {
          formValues.organization_id = organizationId.trim();
        }

        
        // Remove guardrails from top level since it's now in metadata
        if (existingTeamAliases.includes(newTeamAlias)) {
          throw new Error(
            `Team alias ${newTeamAlias} already exists, please pick another alias`
          );
        }

        message.info("Creating Team");
        const response: any = await teamCreateCall(accessToken, formValues);
        if (teams !== null) {
          setTeams([...teams, response]);
        } else {
          setTeams([response]);
        }
        console.log(`response for team create call: ${response}`);
        message.success("Team created");
        form.resetFields();
        setIsTeamModalVisible(false);
      }
    } catch (error) {
      console.error("Error creating the team:", error);
      message.error("Error creating the team: " + error, 20);
    }
  };

  const is_team_admin = (team: any) => {
    if (team == null || team.members_with_roles == null) {
      return false;
    }
    for (let i = 0; i < team.members_with_roles.length; i++) {
      let member = team.members_with_roles[i];
      if (member.user_id == userID && member.role == "admin") {
        return true;
      }
    }
    return false;
  }



  const handleRefreshClick = () => {
    // Update the 'lastRefreshed' state to the current date and time
    const currentDate = new Date();
    setLastRefreshed(currentDate.toLocaleString());
  };

  const handleFilterChange = (key: keyof FilterState, value: string) => {
    const newFilters = { ...filters, [key]: value };
    setFilters(newFilters);
    // Call teamListCall with the new filters
    if (accessToken) {
      v2TeamListCall(
        accessToken,
        newFilters.organization_id || null,
        null,
        newFilters.team_id || null,
        newFilters.team_alias || null
      ).then((response) => {
        if (response && response.teams) {
          setTeams(response.teams);
        }
      }).catch((error) => {
        console.error("Error fetching teams:", error);
      });
    }
  };

  const handleSortChange = (sortBy: string, sortOrder: 'asc' | 'desc') => {
    const newFilters = {
      ...filters,
      sort_by: sortBy,
      sort_order: sortOrder
    };
    setFilters(newFilters);
    // Call teamListCall with the new sort parameters
    if (accessToken) {
      v2TeamListCall(
        accessToken,
        filters.organization_id || null,
        null,
        filters.team_id || null,
        filters.team_alias || null
      ).then((response) => {
        if (response && response.teams) {
          setTeams(response.teams);
        }
      }).catch((error) => {
        console.error("Error fetching teams:", error);
      });
    }
  };

  const handleFilterReset = () => {
    setFilters({
      team_id: "",
      team_alias: "",
      organization_id: "",
      sort_by: "created_at",
      sort_order: "desc"
    });
    // Reset teams list
    if (accessToken) {
      v2TeamListCall(accessToken, null, userID || null, null, null).then((response) => {
        if (response && response.teams) {
          setTeams(response.teams);
        }
      }).catch((error) => {
        console.error("Error fetching teams:", error);
      });
    }
  };

  return (
    <div className="w-full mx-4 h-[75vh]">
      {selectedTeamId ? (
        <TeamInfoView 
        teamId={selectedTeamId} 
        onUpdate={(data) => {
            setTeams(teams => {
              if (teams == null) {
                return teams;
              }
            
              return teams.map(team => {
                if (data.team_id === team.team_id) {
                  return updateExistingKeys(team, data)
                }
                
                return team
              })
            })

        }}
        onClose={() => {
          setSelectedTeamId(null);
          setEditTeam(false);
        }} 
        accessToken={accessToken}
        is_team_admin={is_team_admin(teams?.find((team) => team.team_id === selectedTeamId))}
        is_proxy_admin={userRole == "Admin"}
        userModels={userModels}
        editTeam={editTeam}
      />
    ) : (
      <TabGroup className="gap-2 p-8 h-[75vh] w-full mt-2">
      <TabList className="flex justify-between mt-2 w-full items-center">
        <div className="flex">
          <Tab>Your Teams</Tab>
          <Tab>Available Teams</Tab>
          {isAdminRole(userRole || "") && <Tab>Default Team Settings</Tab>}
          </div>
          <div className="flex items-center space-x-2">
            {lastRefreshed && <Text>Last Refreshed: {lastRefreshed}</Text>}
            <Icon
              icon={RefreshIcon} // Modify as necessary for correct icon name
              variant="shadow"
              size="xs"
              className="self-center"
              onClick={handleRefreshClick}
            />
          </div>
      </TabList>
      <TabPanels>
      <TabPanel>
      <Text>
        Click on &ldquo;Team ID&rdquo; to view team details <b>and</b> manage team members.
      </Text>
      <Grid numItems={1} className="gap-2 pt-2 pb-2 h-[75vh] w-full mt-2">
        <Col numColSpan={1}>
          <Card className="w-full mx-auto flex-auto overflow-hidden overflow-y-auto max-h-[50vh]">
            <div className="border-b px-6 py-4">
              <div className="flex flex-col space-y-4">
                {/* Search and Filter Controls */}
                <div className="flex flex-wrap items-center gap-3">
                  {/* Team Alias Search */}
                  <div className="relative w-64">
                    <input
                      type="text"
                      placeholder="Search by Team Name..."
                      className="w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                      value={filters.team_alias}
                      onChange={(e) => handleFilterChange('team_alias', e.target.value)}
                    />
                    <svg
                      className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-500"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                      />
                    </svg>
                  </div>

                  {/* Filter Button */}
                  <button
                    className={`px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2 ${showFilters ? 'bg-gray-100' : ''}`}
                    onClick={() => setShowFilters(!showFilters)}
                  >
                    <svg
                      className="w-4 h-4"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"
                      />
                    </svg>
                    Filters
                    {(filters.team_id || filters.team_alias || filters.organization_id) && (
                      <span className="w-2 h-2 rounded-full bg-blue-500"></span>
                    )}
                  </button>

                  {/* Reset Filters Button */}
                  <button
                    className="px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2"
                    onClick={handleFilterReset}
                  >
                    <svg
                      className="w-4 h-4"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
                      />
                    </svg>
                    Reset Filters
                  </button>
                </div>

                {/* Additional Filters */}
                {showFilters && (
                  <div className="flex flex-wrap items-center gap-3 mt-3">
                    {/* Team ID Search */}
                    <div className="relative w-64">
                      <input
                        type="text"
                        placeholder="Enter Team ID"
                        className="w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                        value={filters.team_id}
                        onChange={(e) => handleFilterChange('team_id', e.target.value)}
                      />
                      <svg
                        className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-500"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0zm6 2a9 9 0 11-18 0 9 9 0 0118 0z"
                        />
                      </svg>
                    </div>

                    {/* Organization Dropdown */}
                    <div className="w-64">
                      <Select
                        value={filters.organization_id || ""}
                        onValueChange={(value) => handleFilterChange('organization_id', value)}
                        placeholder="Select Organization"
                      >
                        {organizations?.map((org) => (
                          <SelectItem key={org.organization_id} value={org.organization_id || ""}>
                            {org.organization_alias || org.organization_id}
                          </SelectItem>
                        ))}
                      </Select>
                    </div>
                  </div>
                )}
              </div>
            </div>
            <Table>
              <TableHead>
                <TableRow>
                  <TableHeaderCell>Team Name</TableHeaderCell>
                  <TableHeaderCell>Team ID</TableHeaderCell>
                  <TableHeaderCell>Created</TableHeaderCell>
                  <TableHeaderCell>Spend (USD)</TableHeaderCell>
                  <TableHeaderCell>Budget (USD)</TableHeaderCell>
                  <TableHeaderCell>Models</TableHeaderCell>
                  <TableHeaderCell>Organization</TableHeaderCell>
                  <TableHeaderCell>Info</TableHeaderCell>
                </TableRow>
              </TableHead>

              <TableBody>
                {teams && teams.length > 0
                  ? teams
                    .filter((team) => {
                      if (!currentOrg) return true;
                      return team.organization_id === currentOrg.organization_id;
                    })            
                      .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
                      .map((team: any) => (
                      <TableRow key={team.team_id}>
                        <TableCell
                          style={{
                            maxWidth: "4px",
                            whiteSpace: "pre-wrap",
                            overflow: "hidden",
                          }}
                        >
                          {team["team_alias"]}
                        </TableCell>
                        <TableCell>
                          <div className="overflow-hidden">
                            <Tooltip title={team.team_id}>
                              <Button 
                                size="xs"
                                variant="light"
                                className="font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]"

                                onClick={() => {
                                  // Add click handler
                                  setSelectedTeamId(team.team_id);
                                }}
                              >
                                {team.team_id.slice(0, 7)}...
                              </Button>
                            </Tooltip>
                          </div>
                        </TableCell>
                        <TableCell
                          style={{
                            maxWidth: "4px",
                            whiteSpace: "pre-wrap",
                            overflow: "hidden",
                          }}
                        >
                          {team.created_at ? new Date(team.created_at).toLocaleDateString() : "N/A"}
                        </TableCell>
                        <TableCell
                          style={{
                            maxWidth: "4px",
                            whiteSpace: "pre-wrap",
                            overflow: "hidden",
                          }}
                        >
                          {team["spend"]}
                        </TableCell>
                        <TableCell
                          style={{
                            maxWidth: "4px",
                            whiteSpace: "pre-wrap",
                            overflow: "hidden",
                          }}
                        >
                          {team["max_budget"] !== null && team["max_budget"] !== undefined ? team["max_budget"] : "No limit"}
                        </TableCell>
                        <TableCell
                          style={{
                            maxWidth: "8-x",
                            whiteSpace: "pre-wrap",
                            overflow: "hidden",
                          }}
                        >
                          {Array.isArray(team.models) ? (
                            <div
                              style={{
                                display: "flex",
                                flexDirection: "column",
                              }}
                            >
                              {team.models.length === 0 ? (
                                <Badge size={"xs"} className="mb-1" color="red">
                                  <Text>All Proxy Models</Text>
                                </Badge>
                              ) : (
                                team.models.map(
                                  (model: string, index: number) =>
                                    model === "all-proxy-models" ? (
                                      <Badge
                                        key={index}
                                        size={"xs"}
                                        className="mb-1"
                                        color="red"
                                      >
                                        <Text>All Proxy Models</Text>
                                      </Badge>
                                    ) : (
                                      <Badge
                                        key={index}
                                        size={"xs"}
                                        className="mb-1"
                                        color="blue"
                                      >
                                        <Text>
                                          {model.length > 30
                                            ? `${getModelDisplayName(model).slice(0, 30)}...`
                                            : getModelDisplayName(model)}
                                        </Text>
                                      </Badge>
                                    )
                                )
                              )}
                            </div>
                          ) : null}
                        </TableCell>

                        <TableCell>
                          {team.organization_id}
                        </TableCell>
                        <TableCell>
                          <Text>
                            {perTeamInfo &&
                              team.team_id &&
                              perTeamInfo[team.team_id] &&
                              perTeamInfo[team.team_id].keys &&
                              perTeamInfo[team.team_id].keys.length}{" "}
                            Keys
                          </Text>
                          <Text>
                            {perTeamInfo &&
                              team.team_id &&
                              perTeamInfo[team.team_id] &&
                              perTeamInfo[team.team_id].members_with_roles &&
                              perTeamInfo[team.team_id].members_with_roles.length}{" "}
                            Members
                          </Text>
                        </TableCell>
                        <TableCell>
                          {userRole == "Admin" ? (
                            <>
                            <Icon
                              icon={PencilAltIcon}
                              size="sm"
                              onClick={() => {
                                setSelectedTeamId(team.team_id);
                                setEditTeam(true);
                              }}
                            />
                            <Icon
                              onClick={() => handleDelete(team.team_id)}
                              icon={TrashIcon}
                              size="sm"
                            />
                            </>
                          ) : null}
                        </TableCell>
                      </TableRow>
                    ))
                  : null}
              </TableBody>
            </Table>
            {isDeleteModalOpen && (
              <div className="fixed z-10 inset-0 overflow-y-auto">
                <div className="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
                  <div
                    className="fixed inset-0 transition-opacity"
                    aria-hidden="true"
                  >
                    <div className="absolute inset-0 bg-gray-500 opacity-75"></div>
                  </div>

                  {/* Modal Panel */}
                  <span
                    className="hidden sm:inline-block sm:align-middle sm:h-screen"
                    aria-hidden="true"
                  >
                    &#8203;
                  </span>

                  {/* Confirmation Modal Content */}
                  <div className="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                    <div className="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                      <div className="sm:flex sm:items-start">
                        <div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
                          <h3 className="text-lg leading-6 font-medium text-gray-900">
                            Delete Team
                          </h3>
                          <div className="mt-2">
                            <p className="text-sm text-gray-500">
                              Are you sure you want to delete this team ?
                            </p>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div className="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                      <Button
                        onClick={confirmDelete}
                        color="red"
                        className="ml-2"
                      >
                        Delete
                      </Button>
                      <Button onClick={cancelDelete}>Cancel</Button>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </Card>
        </Col>
        {userRole == "Admin" || userRole == "Org Admin"? (
          <Col numColSpan={1}>
            <Button
              className="mx-auto"
              onClick={() => setIsTeamModalVisible(true)}
            >
            + Create New Team
          </Button>
          <Modal
            title="Create Team"
            visible={isTeamModalVisible}
            width={800}
            footer={null}
            onOk={handleOk}
            onCancel={handleCancel}
          >
            <Form
              form={form}
              onFinish={handleCreate}
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 16 }}
              labelAlign="left"
            >
              <>
                <Form.Item
                  label="Team Name"
                  name="team_alias"
                  rules={[
                    { required: true, message: "Please input a team name" },
                  ]}
                >
                  <TextInput placeholder="" />
                </Form.Item>
                <Form.Item
                  label={
                    <span>
                      Organization{' '}
                      <Tooltip title={
                        <span>
                          Organizations can have multiple teams. Learn more about{' '}
                          <a 
                            href="https://docs.litellm.ai/docs/proxy/user_management_heirarchy"
                            target="_blank"
                            rel="noopener noreferrer"
                            style={{ color: '#1890ff', textDecoration: 'underline' }}
                            onClick={(e) => e.stopPropagation()}
                          >
                            user management hierarchy
                          </a>
                        </span>
                      }>
                        <InfoCircleOutlined style={{ marginLeft: '4px' }} />
                      </Tooltip>
                    </span>
                  }
                  name="organization_id"
                  initialValue={currentOrg ? currentOrg.organization_id : null}
                  className="mt-8"
                >
                  <Select2
                    showSearch
                    allowClear
                    placeholder="Search or select an Organization"
                    onChange={(value) => {
                      form.setFieldValue('organization_id', value);
                      setCurrentOrgForCreateTeam(organizations?.find((org) => org.organization_id === value) || null);
                    }}
                    filterOption={(input, option) => {
                      if (!option) return false;
                      const optionValue = option.children?.toString() || '';
                      return optionValue.toLowerCase().includes(input.toLowerCase());
                    }}
                    optionFilterProp="children"
                  >
                    {organizations?.map((org) => (
                      <Select2.Option key={org.organization_id} value={org.organization_id}>
                        <span className="font-medium">{org.organization_alias}</span>{" "}
                        <span className="text-gray-500">({org.organization_id})</span>
                      </Select2.Option>
                    ))}
                  </Select2>
                </Form.Item>
                <Form.Item label={
                    <span>
                      Models{' '}
                      <Tooltip title="These are the models that your selected team has access to">
                        <InfoCircleOutlined style={{ marginLeft: '4px' }} />
                      </Tooltip>
                    </span>
                  } name="models">
                  <Select2
                    mode="multiple"
                    placeholder="Select models"
                    style={{ width: "100%" }}
                  >
                    <Select2.Option
                      key="all-proxy-models"
                      value="all-proxy-models"
                    >
                      All Proxy Models
                    </Select2.Option>
                    {modelsToPick.map((model) => (
                      <Select2.Option key={model} value={model}>
                        {getModelDisplayName(model)}
                      </Select2.Option>
                    ))}
                  </Select2>
                </Form.Item>

                <Form.Item label="Max Budget (USD)" name="max_budget">
                  <NumericalInput step={0.01} precision={2} width={200} />
                </Form.Item>
                <Form.Item
                  className="mt-8"
                  label="Reset Budget"
                  name="budget_duration"
                >
                  <Select2 defaultValue={null} placeholder="n/a">
                    <Select2.Option value="24h">daily</Select2.Option>
                    <Select2.Option value="7d">weekly</Select2.Option>
                    <Select2.Option value="30d">monthly</Select2.Option>
                  </Select2>
                </Form.Item>
                <Form.Item
                  label="Tokens per minute Limit (TPM)"
                  name="tpm_limit"
                >
                  <NumericalInput step={1} width={400} />
                </Form.Item>
                <Form.Item
                  label="Requests per minute Limit (RPM)"
                  name="rpm_limit"
                >
                  <NumericalInput step={1} width={400} />
                </Form.Item>

                <Accordion className="mt-20 mb-8">
                  <AccordionHeader>
                    <b>Additional Settings</b>
                  </AccordionHeader>
                  <AccordionBody>
                    <Form.Item
                      label="Team ID"
                      name="team_id"
                      help="ID of the team you want to create. If not provided, it will be generated automatically."
                    >
                      <TextInput 
                        onChange={(e) => {
                          e.target.value = e.target.value.trim();
                        }} 
                      />
                    </Form.Item>
                    <Form.Item label="Metadata" name="metadata" help="Additional team metadata. Enter metadata as JSON object.">
                      <Input.TextArea rows={4} />
                    </Form.Item>
                    <Form.Item 
                      label={
                        <span>
                          Guardrails{' '}
                          <Tooltip title="Setup your first guardrail">
                            <a 
                              href="https://docs.litellm.ai/docs/proxy/guardrails/quick_start" 
                              target="_blank" 
                              rel="noopener noreferrer"
                              onClick={(e) => e.stopPropagation()}
                            >
                              <InfoCircleOutlined style={{ marginLeft: '4px' }} />
                            </a>
                          </Tooltip>
                        </span>
                      }
                      name="guardrails" 
                      className="mt-8"
                      help="Select existing guardrails or enter new ones"
                    >
                      <Select2
                        mode="tags"
                        style={{ width: '100%' }}
                        placeholder="Select or enter guardrails"
                        options={guardrailsList.map(name => ({ value: name, label: name }))}
                      />
                    </Form.Item>
                  </AccordionBody>
                </Accordion>
              </>
              <div style={{ textAlign: "right", marginTop: "10px" }}>
                <Button2 htmlType="submit">Create Team</Button2>
              </div>
            </Form>
          </Modal>
          </Col>
        ) : null}
      </Grid>
      </TabPanel>
      <TabPanel>  
        <AvailableTeamsPanel
          accessToken={accessToken}
          userID={userID}
        />
      </TabPanel>
      {isAdminRole(userRole || "") && (
        <TabPanel>
          <TeamSSOSettings
            accessToken={accessToken}
            userID={userID || ""}
            userRole={userRole || ""}
          />
        </TabPanel>
      )}
      </TabPanels>

      </TabGroup>)}
    </div>
  );
};

export default Teams;