import type { ServiceUserUserInfoData } from '@/client';
import { useForm } from '@tanstack/react-form';
import { useState } from 'react';
import { toast } from 'sonner';
import z from 'zod';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import {
  Field,
  FieldError,
  FieldLabel,
} from '@/components/ui/field';
import {
  Input,
} from '@/components/ui/input';
import { useUpdateUser } from '@/hooks/data/useUpdateUser';
import { Switch } from '../ui/switch';

const formSchema = z.object({
  username: z.string().min(5),
  nickname: z.string(),
  subtitle: z.string(),
  avatar: z.url().or(z.literal('')),
  allow_public: z.boolean(),
});
export function EditProfileDialog({ user }: { user: ServiceUserUserInfoData }) {
  const { mutateAsync } = useUpdateUser();

  const form = useForm({
    defaultValues: {
      avatar: user.avatar,
      username: user.username,
      nickname: user.nickname,
      subtitle: user.subtitle,
      allow_public: user.allow_public,
    },
    validators: {
      onBlur: formSchema,
    },
    onSubmit: async ({
      value,
    }) => {
      try {
        await mutateAsync({ body: value });
        toast.success('个人资料更新成功');
      }
      catch (error) {
        console.error('Form submission error', error);
        toast.error('更新个人资料失败，请重试');
      }
    },
  });

  const [open, setOpen] = useState(false);

  if (!open) {
    setTimeout(() => {
      form.reset();
    }, 200);
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="outline" className="w-full" size="lg">编辑个人资料</Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[425px]">
        <form
          onSubmit={(e) => {
            e.preventDefault();
            e.stopPropagation();
            void form.handleSubmit().then(() => setOpen(false));
          }}
          className="grid gap-4"
        >
          <DialogHeader>
            <DialogTitle>编辑个人资料</DialogTitle>
          </DialogHeader>
          <form.Field name="username">
            {field => (
              <Field>
                <FieldLabel htmlFor="username">用户名</FieldLabel>
                <Input
                  id="username"
                  name="username"
                  placeholder={user.username}
                  value={field.state.value}
                  onBlur={field.handleBlur}
                  onChange={e => field.handleChange(e.target.value)}
                />
                <FieldError errors={field.state.meta.errors} />
              </Field>
            )}
          </form.Field>
          <form.Field name="nickname">
            {field => (
              <Field>
                <FieldLabel htmlFor="nickname">昵称</FieldLabel>
                <Input
                  id="nickname"
                  name="nickname"
                  placeholder={user.nickname}
                  value={field.state.value}
                  onBlur={field.handleBlur}
                  onChange={e => field.handleChange(e.target.value)}
                />
                <FieldError errors={field.state.meta.errors} />
              </Field>
            )}
          </form.Field>
          <form.Field name="subtitle">
            {field => (
              <Field>
                <FieldLabel htmlFor="subtitle">副标题</FieldLabel>
                <Input
                  id="subtitle"
                  name="subtitle"
                  placeholder={user.subtitle}
                  value={field.state.value}
                  onBlur={field.handleBlur}
                  onChange={e => field.handleChange(e.target.value)}
                />
                <FieldError errors={field.state.meta.errors} />
              </Field>
            )}
          </form.Field>
          <form.Field name="avatar">
            {field => (
              <Field>
                <FieldLabel htmlFor="avatar">头像链接</FieldLabel>
                <Input
                  id="avatar"
                  name="avatar"
                  placeholder={user.avatar}
                  value={field.state.value}
                  onBlur={field.handleBlur}
                  onChange={e => field.handleChange(e.target.value)}
                />
                <FieldError errors={field.state.meta.errors} />
              </Field>
            )}
          </form.Field>
          <form.Field name="allow_public">
            {field => (
              <Field orientation="horizontal" className="my-2">
                <FieldLabel htmlFor="allow_public">公开个人资料</FieldLabel>
                <Switch id="allow_public" onCheckedChange={e => field.handleChange(e)} defaultChecked={user.allow_public} />
              </Field>
            )}
          </form.Field>
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="outline">取消</Button>
            </DialogClose>
            <form.Subscribe
              selector={state => [state.canSubmit]}
              children={([canSubmit]) => (
                <Button type="submit" disabled={!canSubmit}>保存</Button>
              )}
            />
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
