"use client";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { toast } from "@/components/ui/toaster";
import { useOrganization } from "@clerk/nextjs";
import { UploadCloud } from "lucide-react";
import Link from "next/link";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import React, { ChangeEvent, useCallback, useEffect, useState } from "react";

import { z } from "zod";

const formSchema = z.object({
  name: z
    .string()
    .min(3)
    .regex(/^[a-zA-Z0-9_\-\.\*]+$/, {
      message:
        "Must be at least 3 characters long and only contain alphanumeric, periods, dashes and underscores",
    }),

  // id: z.string().optional(),
  dataURL: z.string().optional(),

  description: z.string().optional(),
  permissionOptions: z
    .array(
      z.object({
        label: z.string(),
        value: z.string(),
      }),
    )
    .optional(),
});



export const UpdateWorkspace: React.FC = () => {
  // const { organization } = useOrganization();

  const [dragActive, setDragActive] = useState(false);

  const [image, setImage] = useState<string | null>(null);

  const form = useForm<z.infer<typeof formSchema>>({
    // resolver: zodResolver(formSchema),
    reValidateMode: "onBlur",
  });

  const onChangePicture = useCallback(
    (e: ChangeEvent<HTMLInputElement>) => {
      toast("Uploading image...");
      const file = e.target.files?.[0];

      if (!file) {
        toast.error("No image selected");
        return;
      }
      if (file.size / 1024 / 1024 > 2) {
        toast.error("File size too big (max 2MB)");
        return;
      }
      if (file.type !== "image/png" && file.type !== "image/jpeg") {
        toast.error("File type not supported (.png or .jpg only)");
        return;
      }

      console.log("-------------------", file)

      const reader = new FileReader();
      reader.onload = (e) => {
        setImage(e.target?.result as string);
      };
      reader.readAsDataURL(file);

      // if (!organization) {
      //   toast.error("Only allowed for orgs");
      //   return;
      // }
      // organization
      //   .setLogo({ file })
      //   .then(() => {
      //     toast.success("Image uploaded");
      //   })
      //   .catch(() => {
      //     toast.error("Error uploading image");
      //   });
    },
    [setImage],
  );

  // if (!organization) {
  //   return (
  //     <Card>
  //       <CardHeader>
  //         <CardTitle>Workspace Avatar</CardTitle>
  //       </CardHeader>
  //       <CardContent>
  //         <p className="text-sm text-content-subtle">
  //           This is a personal workspace. Change your personal avatar{" "}
  //           <Link href="/app/settings/user" className="underline hover:text-content">
  //             here
  //           </Link>
  //           .
  //         </p>
  //       </CardContent>
  //     </Card>
  //   );
  // }

  async function onSubmit(values: z.infer<typeof formSchema>) {

    console.log("----onSubmit----", values)
    // createRole.mutate({
    //   name: values.name,
    //   description: values.description,
    //   permissionIds: values.permissionOptions?.map((o) => o.value),
    // });
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-8">

        <FormField
          control={form.control}
          name="name"
          render={({ field }) => (
            <Card className="w-full ">
              <CardHeader>
                <CardTitle>请选择或新建知识库</CardTitle>
                <CardDescription>xxxxx</CardDescription>
              </CardHeader>
              <CardContent>
                <Input placeholder="domain.manager"  {...field} />
              </CardContent>
            </Card>
          )}
        />

        {/* <FormField
          control={form.control}
          name="name"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Name</FormLabel>
              <FormControl>
                <Input placeholder="domain.manager" {...field} />
              </FormControl>
              <FormDescription>
                A unique name for your role. You will use this when managing roles through the
                API. These are not customer facing.
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        /> */}
        {/* <FormField
          control={form.control}
          name="description"
          render={({ field }) => (
            <FormItem>
              <FormLabel>
                Description{" "}
            
              </FormLabel>
              <FormControl>
                <Textarea
                  rows={form.getValues().description?.split("\n").length ?? 3}
                  placeholder="Manage domains and DNS records "
                  {...field}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        /> */}


        <Card className="flex items-start justify-between ">
          <CardHeader>
            <CardTitle>上传培训资料</CardTitle>
            <CardDescription>
              Limit 200MB per file • HTML, HTM, MHTML, MD, JSON, JSONL, CSV, PDF, DOCX, DOC, PPT, PPTX, PNG, JPG, JPEG, BMP, EML, MSG, RST, RTF, TXT, XML, EPUB, ODT, TSV, EML, MSG, EPUB, XLSX, XLS, XLSD, IPYNB, ODT, PY, RST, RTF, SRT, TOML, TSV, DOCX, DOC, XML, PPT, PPTX, ENEX
            </CardDescription>
          </CardHeader>
          <CardContent>
            <label
              htmlFor="image"
              className="relative flex flex-col items-center justify-center w-24 h-24 mt-1 transition-all border rounded-full shadow-sm cursor-pointer  border-border group text-background  hover:bg-background-subtle"
            >
              <div
                className="absolute z-[5] h-full w-full rounded-full"
                onDragOver={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  setDragActive(true);
                }}
                onDragEnter={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  setDragActive(true);
                }}
                onDragLeave={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  setDragActive(false);
                }}
                onDrop={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  setDragActive(false);
                  const file = e.dataTransfer.files?.[0];
                  if (file) {
                    if (file.size / 1024 / 1024 > 2) {
                      toast.error("File size too big (max 2MB)");
                    } else if (file.type !== "image/png" && file.type !== "image/jpeg") {
                      toast.error("File type not supported (.png or .jpg only)");
                    } else {
                      const reader = new FileReader();
                      reader.onload = (e) => {
                        setImage(e.target?.result as string);
                      };
                      reader.readAsDataURL(file);
                    }
                  }
                }}
              />
              <div
                className={`${dragActive ? "cursor-copy border-2 border-black bg-gray-50 opacity-100" : ""
                  } absolute z-[3] flex h-full w-full flex-col items-center justify-center rounded-full bg-white transition-all ${false ? "opacity-0 group-hover:opacity-100" : "group-hover:bg-gray-50"
                  }`}
              >
                <UploadCloud
                  className={`${dragActive ? "scale-110" : "scale-100"
                    } h-5 w-5 text-gray-500 transition-all duration-75 group-hover:scale-110 group-active:scale-95`}
                />
              </div>

            </label>
            <div className="flex mt-1 rounded-full shadow-sm">
              <input
                id="image"
                name="image"
                type="file"
                accept="image/*"
                className="sr-only"
                onChange={onChangePicture}
              />
            </div>


          </CardContent>
        </Card>


        <FormField
          control={form.control}
          name="description"
          render={({ field }) => (
            <Card className="w-full ">
              <CardHeader>
                <CardTitle>请输入培训资料库介绍</CardTitle>
                <CardDescription>xxxxx</CardDescription>
              </CardHeader>
              <CardContent>
                <Textarea
                  rows={3}
                  placeholder="关于本项目issue的解答 "
                  {...field}
                />
              </CardContent>
            </Card>
          )}
        />


        <Button type="submit" size={"default"} className="w-1/5">
          {/* {createRole.isLoading ? <Loading className="w-4 h-4" /> : "添加文件到知识库"} */}
          添加文件到知识库
        </Button>
      </form>
    </Form>
  )

  return (
    <form
      onSubmit={async (e) => {
        e.preventDefault();
        // if (!image) {
        //   toast.error("No image selected");
        //   return;
        // }

        console.log("------------", e)

        // await organization?.setLogo({ file: image });
        // await organization?.reload();
        toast.success("Image uploaded");
      }}
      className="flex flex-col items-start justify-between gap-[1.5rem]"
    >

      <Card className="w-full ">
        <CardHeader>
          <CardTitle>请选择或新建知识库</CardTitle>
          <CardDescription>xxxxx</CardDescription>
        </CardHeader>
        <CardContent>
          <Input placeholder="domain.manager" />
        </CardContent>
      </Card>
      <Card className="flex items-start justify-between ">
        <CardHeader>
          <CardTitle>上传培训资料</CardTitle>
          <CardDescription>
            Limit 200MB per file • HTML, HTM, MHTML, MD, JSON, JSONL, CSV, PDF, DOCX, DOC, PPT, PPTX, PNG, JPG, JPEG, BMP, EML, MSG, RST, RTF, TXT, XML, EPUB, ODT, TSV, EML, MSG, EPUB, XLSX, XLS, XLSD, IPYNB, ODT, PY, RST, RTF, SRT, TOML, TSV, DOCX, DOC, XML, PPT, PPTX, ENEX
          </CardDescription>
        </CardHeader>
        <CardContent>
          <label
            htmlFor="image"
            className="relative flex flex-col items-center justify-center w-24 h-24 mt-1 transition-all border rounded-full shadow-sm cursor-pointer  border-border group text-background  hover:bg-background-subtle"
          >
            <div
              className="absolute z-[5] h-full w-full rounded-full"
              onDragOver={(e) => {
                e.preventDefault();
                e.stopPropagation();
                setDragActive(true);
              }}
              onDragEnter={(e) => {
                e.preventDefault();
                e.stopPropagation();
                setDragActive(true);
              }}
              onDragLeave={(e) => {
                e.preventDefault();
                e.stopPropagation();
                setDragActive(false);
              }}
              onDrop={(e) => {
                e.preventDefault();
                e.stopPropagation();
                setDragActive(false);
                const file = e.dataTransfer.files?.[0];
                if (file) {
                  if (file.size / 1024 / 1024 > 2) {
                    toast.error("File size too big (max 2MB)");
                  } else if (file.type !== "image/png" && file.type !== "image/jpeg") {
                    toast.error("File type not supported (.png or .jpg only)");
                  } else {
                    const reader = new FileReader();
                    // reader.onload = (e) => {
                    //   setImage(e.target?.result as string);
                    // };
                    reader.readAsDataURL(file);
                  }
                }
              }}
            />
            <div
              className={`${dragActive ? "cursor-copy border-2 border-black bg-gray-50 opacity-100" : ""
                } absolute z-[3] flex h-full w-full flex-col items-center justify-center rounded-full bg-white transition-all ${false ? "opacity-0 group-hover:opacity-100" : "group-hover:bg-gray-50"
                }`}
            >
              <UploadCloud
                className={`${dragActive ? "scale-110" : "scale-100"
                  } h-5 w-5 text-gray-500 transition-all duration-75 group-hover:scale-110 group-active:scale-95`}
              />
            </div>

          </label>
          <div className="flex mt-1 rounded-full shadow-sm">
            <input
              id="image"
              name="image"
              type="file"
              accept="image/*"
              className="sr-only"
              onChange={onChangePicture}
            />
          </div>


        </CardContent>
      </Card>

      <Card className="w-full ">
        <CardHeader>
          <CardTitle>请输入培训资料库介绍</CardTitle>
          <CardDescription>xxxxx</CardDescription>
        </CardHeader>
        <CardContent>
          <Textarea
            rows={3}
            placeholder="关于本项目issue的解答 "
          // {...field}
          />
        </CardContent>
      </Card>

      <Button type="submit" size={"default"} className="w-1/5">
        {/* {createRole.isLoading ? <Loading className="w-4 h-4" /> : "添加文件到知识库"} */}
        添加文件到知识库
      </Button>
    </form>
  );
};
