"use client";

import { useEffect, useRef, useState } from "react";

import axios from "axios";

import Cookies from "js-cookie";

import { z } from "zod";

import { zodResolver } from "@hookform/resolvers/zod";

import { Controller, useForm } from "react-hook-form";

import toast, { Toaster } from "react-hot-toast";

import { Button } from "@/components/shadcnui/button";

import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/shadcnui/card";

import {
  Field,
  FieldError,
  FieldGroup,
  FieldLabel,
} from "@/components/shadcnui/field";

import { Input } from "@/components/shadcnui/input";

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/shadcnui/select";

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/shadcnui/table";

const ROLE_OPTIONS = ["PLUMBER", "MASON", "DEALER", "DISTRIBUTOR"];

const TYPE_OPTIONS = ["QUARTERLY", "ANNUAL"];

const schema = z.object({
  title: z.string().min(2, "Title required"),

  description: z.string().min(5, "Description required"),

  type: z.string().min(1, "Type required"),

  validTill: z.string().min(1, "Valid till required"),

  applicableRoles: z.array(z.string()).min(1, "Select at least one role"),

  pdf: z.any().optional(),
});

type FormType = z.infer<typeof schema>;

interface SchemeType {
  _id: string;

  title: string;

  description: string;

  type: string;

  applicableRoles: string[];

  pdfUrl: string;

  validTill: string;

  isActive: boolean;
}

const SchemaPDF = () => {
  const token = Cookies.get("kero_token");

  const [loading, setLoading] = useState(false);

  const [schemes, setSchemes] = useState<SchemeType[]>([]);

  const [pdfFile, setPdfFile] = useState<File | null>(null);

  const fileRef = useRef<HTMLInputElement | null>(null);

  const form = useForm<FormType>({
    resolver: zodResolver(schema),

    defaultValues: {
      title: "",

      description: "",

      type: "",

      validTill: "",

      applicableRoles: [],

      pdf: undefined,
    },
  });

  const getSchemes = async () => {
    try {
      const response = await axios.get(
        `${process.env.NEXT_PUBLIC_API_BASE_URL}/schemes/admin/all`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      );

      if (response.data.success) {
        const today = new Date();

        const activeSchemes = response.data.schemes.filter(
          (item: SchemeType) =>
            new Date(item.validTill) >= today && item.isActive,
        );

        setSchemes(activeSchemes);
      }
    } catch (error) {
      console.log(error);

      toast.error("Failed to fetch schemes");
    }
  };

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

  const onSubmit = async (values: FormType) => {
    try {
      if (!pdfFile) {
        toast.error("Please upload PDF");

        return;
      }

      if (pdfFile.type !== "application/pdf") {
        toast.error("Only PDF allowed");

        return;
      }

      setLoading(true);

      const formData = new FormData();

      formData.append("title", values.title);

      formData.append("description", values.description);

      formData.append("type", values.type);

      formData.append("validTill", values.validTill);

      formData.append(
        "applicableRoles",
        JSON.stringify(values.applicableRoles),
      );

      formData.append("pdf", pdfFile);

      const response = await axios.post(
        `${process.env.NEXT_PUBLIC_API_BASE_URL}/schemes/create`,
        formData,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      );

      console.log(response.data);

      toast.success("Scheme created successfully");

      form.reset();

      setPdfFile(null);

      if (fileRef.current) {
        fileRef.current.value = "";
      }

      getSchemes();
    } catch (error) {
      console.log(error);

      if (axios.isAxiosError(error)) {
        toast.error(error.response?.data?.message || "Something went wrong");
      }
    } finally {
      setLoading(false);
    }
  };

  const deleteScheme = async (id: string) => {
    try {
      await axios.delete(
        `${process.env.NEXT_PUBLIC_API_BASE_URL}/schemes/${id}`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      );

      toast.success("Scheme deleted successfully");

      getSchemes();
    } catch (error) {
      console.log(error);

      toast.error("Delete failed");
    }
  };
  return (
    <div className="mt-6 space-y-8">
      <Toaster
        position="top-center"
        reverseOrder={false}
      />

      <Card>
        <CardHeader>
          <CardTitle>Create Scheme</CardTitle>
        </CardHeader>

        <CardContent>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="space-y-5">
            <FieldGroup>
              <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                <Controller
                  name="title"
                  control={form.control}
                  render={({ field, fieldState }) => (
                    <Field data-invalid={fieldState.invalid}>
                      <FieldLabel>Title</FieldLabel>

                      <Input
                        {...field}
                        placeholder="Enter title"
                      />

                      {fieldState.invalid && (
                        <FieldError errors={[fieldState.error]} />
                      )}
                    </Field>
                  )}
                />

                <Controller
                  name="description"
                  control={form.control}
                  render={({ field, fieldState }) => (
                    <Field data-invalid={fieldState.invalid}>
                      <FieldLabel>Description</FieldLabel>

                      <Input
                        {...field}
                        placeholder="Enter description"
                      />

                      {fieldState.invalid && (
                        <FieldError errors={[fieldState.error]} />
                      )}
                    </Field>
                  )}
                />

                <Controller
                  name="type"
                  control={form.control}
                  render={({ field, fieldState }) => (
                    <Field data-invalid={fieldState.invalid}>
                      <FieldLabel>Type</FieldLabel>

                      <Select
                        value={field.value}
                        onValueChange={field.onChange}>
                        <SelectTrigger>
                          <SelectValue placeholder="Select Type" />
                        </SelectTrigger>

                        <SelectContent>
                          {TYPE_OPTIONS.map((item) => (
                            <SelectItem
                              key={item}
                              value={item}>
                              {item}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>

                      {fieldState.invalid && (
                        <FieldError errors={[fieldState.error]} />
                      )}
                    </Field>
                  )}
                />

                <Controller
                  name="validTill"
                  control={form.control}
                  render={({ field, fieldState }) => (
                    <Field data-invalid={fieldState.invalid}>
                      <FieldLabel>Valid Till</FieldLabel>

                      <Input
                        {...field}
                        type="date"
                      />

                      {fieldState.invalid && (
                        <FieldError errors={[fieldState.error]} />
                      )}
                    </Field>
                  )}
                />

                <Controller
                  name="applicableRoles"
                  control={form.control}
                  render={({ field, fieldState }) => (
                    <Field data-invalid={fieldState.invalid}>
                      <FieldLabel>Applicable Roles</FieldLabel>

                      <div className="grid grid-cols-2 gap-3 rounded-lg border p-4">
                        {ROLE_OPTIONS.map((role) => (
                          <label
                            key={role}
                            className="flex items-center gap-2">
                            <input
                              type="checkbox"
                              checked={field.value.includes(role)}
                              onChange={(e) => {
                                if (e.target.checked) {
                                  field.onChange([...field.value, role]);
                                } else {
                                  field.onChange(
                                    field.value.filter((item) => item !== role),
                                  );
                                }
                              }}
                            />

                            {role}
                          </label>
                        ))}
                      </div>

                      {fieldState.invalid && (
                        <FieldError errors={[fieldState.error]} />
                      )}
                    </Field>
                  )}
                />

                <Controller
                  name="pdf"
                  control={form.control}
                  render={({ field, fieldState }) => (
                    <Field data-invalid={fieldState.invalid}>
                      <FieldLabel>Upload PDF</FieldLabel>

                      <Input
                        ref={fileRef}
                        type="file"
                        accept=".pdf"
                        onChange={(e) => {
                          const file = e.target.files?.[0];

                          setPdfFile(file || null);

                          field.onChange(file);
                        }}
                      />

                      {fieldState.invalid && (
                        <FieldError errors={[fieldState.error]} />
                      )}
                    </Field>
                  )}
                />
              </div>
            </FieldGroup>

            <Button
              type="submit"
              disabled={loading}>
              {loading ? "Saving..." : "Create Scheme"}
            </Button>
          </form>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>All Schemes</CardTitle>
        </CardHeader>

        <CardContent className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Title</TableHead>
                <TableHead>Type</TableHead>
                <TableHead>Roles</TableHead>
                <TableHead>Expiry</TableHead>
                <TableHead>PDF</TableHead>
                <TableHead>Actions</TableHead>
              </TableRow>
            </TableHeader>

            <TableBody>
              {schemes.map((item) => (
                <TableRow key={item._id}>
                  <TableCell>{item.title}</TableCell>

                  <TableCell>{item.type}</TableCell>

                  <TableCell>{item.applicableRoles.join(", ")}</TableCell>

                  <TableCell>{item.validTill.split("T")[0]}</TableCell>

                  <TableCell>
                    <Button
                      size="sm"
                      onClick={() =>
                        window.open(
                          `http://app.keroindia.com${item.pdfUrl}`,
                          "_blank",
                        )
                      }>
                      View PDF
                    </Button>
                  </TableCell>

                  <TableCell>
                    <Button
                      size="sm"
                      variant="destructive"
                      onClick={() => deleteScheme(item._id)}>
                      Delete
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
};

export default SchemaPDF;
