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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
"use client"

import * as React from "react"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Textarea } from "@/components/ui/textarea"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { SettingsIcon, EraserIcon, ShieldCheckIcon } from "lucide-react"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { toast } from "sonner"
import { useAppDispatch, useAppSelector } from "@/common/hooks"
import { ECozeBaseUrl } from "@/common/constant"
import {
  setAgentSettings,
  setCozeSettings,
  resetCozeSettings,
  resetDifySettings,
  setGlobalSettingsDialog,
  setDifySettings,
} from "@/store/reducers/global"

const TABS_OPTIONS = [
  {
    label: "Agent",
    value: "agent",
  },
  {
    label: "Coze",
    value: "coze",
  },
  {
    label: "Dify",
    value: "dify",
  },
]

export const useSettingsTabs = () => {
  const [tabs, setTabs] = React.useState(TABS_OPTIONS)

  const graphName = useAppSelector((state) => state.global.graphName)

  const enableCozeSettingsMemo = React.useMemo(() => {
    return isCozeGraph(graphName)
  }, [graphName])

  const enableDifySettingsMemo = React.useMemo(() => {
    return isDifyGraph(graphName)
  }, [graphName])

  const enableGreetingsOrPromptMemo: { greeting: boolean, prompt: boolean } = React.useMemo(() => {
    if (graphName === "va_gemini_v2v") {
      return {
        greeting: false,
        prompt: true,
      }
    } else if (graphName === "va_dify_azure") {
      return {
        greeting: true,
        prompt: false,
      }
    } else if (graphName === "story_teller_stt_integrated") {
      return {
        greeting: true,
        prompt: false,
      }
    }

    return {
      greeting: true,
      prompt: true,
    }
  }, [graphName])



  React.useEffect(() => {
    if (enableCozeSettingsMemo) {
      setTabs((prev) =>
        [
          { label: "Agent", value: "agent" },
          { label: "Coze", value: "coze" },
        ]
      )
    } else if (enableDifySettingsMemo) {
      setTabs((prev) =>
        [
          { label: "Agent", value: "agent" },
          { label: "Dify", value: "dify" },
        ]
      )
    } else {
      setTabs((prev) => prev.filter((tab) => tab.value !== "coze" && tab.value !== "dify"))
    }
  }, [enableCozeSettingsMemo, enableDifySettingsMemo])

  return {
    tabs,
    enableGreetingsOrPromptMemo,
  }
}

export default function SettingsDialog() {
  const dispatch = useAppDispatch()
  const globalSettingsDialog = useAppSelector(
    (state) => state.global.globalSettingsDialog,
  )

  const { tabs, enableGreetingsOrPromptMemo } = useSettingsTabs()

  const handleClose = () => {
    dispatch(setGlobalSettingsDialog({ open: false, tab: undefined }))
  }

  return (
    <Dialog
      open={globalSettingsDialog.open}
      onOpenChange={(open) =>
        dispatch(setGlobalSettingsDialog({ open, tab: undefined }))
      }
    >
      <DialogTrigger asChild>
        <Button variant="ghost" size="sm" className="w-9">
          <SettingsIcon />
        </Button>
      </DialogTrigger>
      <DialogContent className="w-fit">
        <DialogHeader>
          <DialogTitle>Settings</DialogTitle>
        </DialogHeader>
        <Tabs
          defaultValue={globalSettingsDialog.tab || TABS_OPTIONS[0].value}
          className="w-full min-w-96 max-w-screen-sm"
        >
          {tabs.length > 1 && (
            <TabsList className="w-full">
              {tabs.map((tab) => (
                <TabsTrigger
                  key={tab.value}
                  className="w-full"
                  value={tab.value}
                >
                  {tab.label}
                </TabsTrigger>
              ))}
            </TabsList>
          )}
          <TabsContent value="agent">
            <CommonAgentSettingsTab
              enableGreeting={enableGreetingsOrPromptMemo.greeting}
              enablePrompt={enableGreetingsOrPromptMemo.prompt}
              handleClose={handleClose}
              handleSubmit={handleClose}
            />
          </TabsContent>
          <TabsContent value="coze">
            <CozeSettingsTab
              handleClose={handleClose}
              handleSubmit={handleClose}
            />
          </TabsContent>
          <TabsContent value="dify">
            <DifySettingsTab
              handleClose={handleClose}
              handleSubmit={handleClose}
            />
          </TabsContent>
        </Tabs>
      </DialogContent>
    </Dialog>
  )
}

const formSchema = z.object({
  greeting: z.string().optional(),
  prompt: z.string().optional(),
})

export function CommonAgentSettingsTab(props: {
  enableGreeting?: boolean
  enablePrompt?: boolean
  handleClose?: () => void
  handleSubmit?: (values: z.infer<typeof formSchema>) => void
}) {
  const { handleSubmit, enableGreeting, enablePrompt } = props

  const dispatch = useAppDispatch()
  const agentSettings = useAppSelector((state) => state.global.agentSettings)

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      greeting: agentSettings.greeting,
      prompt: agentSettings.prompt,
    },
  })

  function onSubmit(values: z.infer<typeof formSchema>) {
    console.log("Form Values:", values)
    dispatch(setAgentSettings(values))
    handleSubmit?.(values)
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
        {enableGreeting && <FormField
          control={form.control}
          name="greeting"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Greeting</FormLabel>
              <FormControl>
                <Textarea
                  placeholder="Enter the greeting, leave it blank if you want to use default one."
                  className="resize-none"
                  {...field}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />}
        {enablePrompt && <FormField
          control={form.control}
          name="prompt"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Prompt</FormLabel>
              <FormControl>
                <Textarea
                  placeholder="Enter the prompt, leave it blank if you want to use default one."
                  className="resize-none"
                  rows={4}
                  {...field}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />}
        <DialogFooter>
          <Button type="submit" disabled={!form.formState.isValid}>
            Save Agent Settings
          </Button>
        </DialogFooter>
      </form>
    </Form>
  )
}

export const cozeSettingsFormSchema = z.object({
  token: z
    .string({
      message: "Token is required",
    })
    .min(1),
  bot_id: z
    .string({
      message: "Bot ID is required",
    })
    .min(1),
  base_url: z.nativeEnum(ECozeBaseUrl).default(ECozeBaseUrl.GLOBAL),
})

export const isCozeGraph = (graphName: string) => {
  return graphName.toLowerCase().includes("coze")
}

export function CozeSettingsTab(props: {
  handleClose?: () => void
  handleSubmit?: (values: z.infer<typeof cozeSettingsFormSchema>) => void
}) {
  const { handleSubmit } = props

  const dispatch = useAppDispatch()
  const cozeSettings = useAppSelector((state) => state.global.cozeSettings)

  const form = useForm<z.infer<typeof cozeSettingsFormSchema>>({
    resolver: zodResolver(cozeSettingsFormSchema),
    defaultValues: {
      token: cozeSettings.token,
      bot_id: cozeSettings.bot_id,
      base_url: cozeSettings.base_url as z.infer<
        typeof cozeSettingsFormSchema
      >["base_url"],
    },
  })

  function onSubmit(values: z.infer<typeof cozeSettingsFormSchema>) {
    console.log("Coze Form Values:", values)
    dispatch(setCozeSettings(values))
    handleSubmit?.(values)
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
        <FormField
          control={form.control}
          name="bot_id"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Bot ID*</FormLabel>
              <FormControl>
                <Input placeholder="Enter your Coze bot ID" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="token"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Token*</FormLabel>
              <FormControl>
                <Input placeholder="Enter your Coze API token" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="base_url"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Base URL*</FormLabel>
              <FormControl>
                <Select {...field} onValueChange={field.onChange}>
                  <SelectTrigger>
                    <SelectValue placeholder="Select base URL" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value={ECozeBaseUrl.GLOBAL}>
                      {ECozeBaseUrl.GLOBAL}
                    </SelectItem>
                    <SelectItem value={ECozeBaseUrl.CN}>
                      {ECozeBaseUrl.CN}
                    </SelectItem>
                    {/* <SelectItem value={ECozeBaseUrl.CN}>
                      {ECozeBaseUrl.CN}
                    </SelectItem> */}
                  </SelectContent>
                </Select>
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <div className="flex flex-col items-end">
          <div className="flex items-center gap-2">
            <Button
              variant="destructive"
              size="icon"
              onClick={(e) => {
                e.preventDefault()
                e.stopPropagation()
                form.reset({
                  token: "",
                  bot_id: "",
                  base_url: ECozeBaseUrl.GLOBAL,
                })
                dispatch(resetCozeSettings())
                toast.success("Coze settings reset")
              }}
            >
              <EraserIcon />
            </Button>
            <Button type="submit" disabled={!form.formState.isValid}>
              Save Coze Settings
            </Button>
          </div>
          <Label className="flex select-none items-center gap-1 pt-2 text-right text-xs text-muted-foreground">
            <ShieldCheckIcon className="me-1 size-3" />
            Settings are saved in your browser only
          </Label>
        </div>
      </form>
    </Form>
  )
}

export const difySettingsFormSchema = z.object({
  api_key: z
    .string({
      message: "API Key is required",
    })
    .min(1),
})

export const isDifyGraph = (graphName: string) => {
  return graphName.toLowerCase().includes("dify")
}

export function DifySettingsTab(props: {
  handleClose?: () => void
  handleSubmit?: (values: z.infer<typeof difySettingsFormSchema>) => void
}) {
  const { handleSubmit } = props

  const dispatch = useAppDispatch()
  const difySettings = useAppSelector((state) => state.global.difySettings)

  const form = useForm<z.infer<typeof difySettingsFormSchema>>({
    resolver: zodResolver(difySettingsFormSchema),
    defaultValues: {
      api_key: difySettings.api_key,
    },
  })

  function onSubmit(values: z.infer<typeof difySettingsFormSchema>) {
    console.log("Dify Form Values:", values)
    dispatch(setDifySettings(values))
    handleSubmit?.(values)
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
        <FormField
          control={form.control}
          name="api_key"
          render={({ field }) => (
            <FormItem>
              <FormLabel>API Key*</FormLabel>
              <FormControl>
                <Input placeholder="Enter your Dify API Key" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <div className="flex flex-col items-end">
          <div className="flex items-center gap-2">
            <Button
              variant="destructive"
              size="icon"
              onClick={(e) => {
                e.preventDefault()
                e.stopPropagation()
                form.reset({
                  api_key: "",
                })
                dispatch(resetDifySettings())
                toast.success("Dify settings reset")
              }}
            >
              <EraserIcon />
            </Button>
            <Button type="submit" disabled={!form.formState.isValid}>
              Save Dify Settings
            </Button>
          </div>
          <Label className="flex select-none items-center gap-1 pt-2 text-right text-xs text-muted-foreground">
            <ShieldCheckIcon className="me-1 size-3" />
            Settings are saved in your browser only
          </Label>
        </div>
      </form>
    </Form>
  )
}