"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 {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/shadcnui/table";
import { Label } from "@/components/shadcnui/label";

const tilesSchema = z.object({
  category: z.string().min(1, "Category required"),

  designName: z.string().min(2, "Design name required"),

  size: z.string().min(2, "Size required"),

  sizeInch: z.string().min(2, "Size inch required"),

  pcsPerBox: z.string().min(1, "PCS per box required"),

  sqFtPerBox: z.string().min(1, "SQ FT per box required"),

  pricePerBox: z.string().min(1, "Price per box required"),
});

type TilesFormType = z.infer<typeof tilesSchema>;

interface TileType {
  _id: string;

  category: string;

  designName: string;

  size: string;

  sizeInch: string;

  pcsPerBox: number;

  sqFtPerBox: number;

  pricePerBox: number;

  isActive: boolean;
}

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

  const [tiles, setTiles] = useState<TileType[]>([]);

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

  const [editId, setEditId] = useState<string | null>(null);

  const [catalogueTitle, setCatalogueTitle] = useState("");

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

  const [catalogueLoading, setCatalogueLoading] = useState(false);

  const [catalogueData, setCatalogueData] = useState<any>(null);
  const fileInputRef = useRef<HTMLInputElement | null>(null);

  const form = useForm<TilesFormType>({
    resolver: zodResolver(tilesSchema),

    defaultValues: {
      category: "Tiles",

      designName: "",

      size: "",

      sizeInch: "",

      pcsPerBox: "",

      sqFtPerBox: "",

      pricePerBox: "",
    },
  });

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

      if (response.data.success) {
        const activeTiles = response.data.tiles.filter(
          (item: TileType) => item.isActive,
        );

        setTiles(activeTiles);
      }
    } catch (error) {
      console.log(error);
    }
  };

  // PDF upload

  const getCatalogue = async () => {
    try {
      const response = await axios.get(
        `${process.env.NEXT_PUBLIC_API_BASE_URL}/tiles/catalogue`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      );

      if (response.data.success) {
        setCatalogueData(response.data.catalogue);
      }
    } catch (error) {
      console.log(error);
    }
  };

  const uploadCatalogue = async () => {
    try {
      if (!catalogueTitle || !pdfFile) {
        toast.error("Title and PDF required");

        return;
      }

      setCatalogueLoading(true);

      const formData = new FormData();

      formData.append("title", catalogueTitle);

      formData.append("pdf", pdfFile);

      await axios.post(
        `${process.env.NEXT_PUBLIC_API_BASE_URL}/tiles/catalogue/upload`,
        formData,
        {
          headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "multipart/form-data",
          },
        },
      );

      toast.success("Catalogue uploaded");
      setCatalogueTitle("");

      setPdfFile(null);

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

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

      toast.error("Upload failed");
    } finally {
      setCatalogueLoading(false);
    }
  };

  const deleteCatalogue = async () => {
    try {
      if (!catalogueData?._id) return;

      await axios.delete(
        `${process.env.NEXT_PUBLIC_API_BASE_URL}/tiles/catalogue/${catalogueData._id}`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      );

      toast.success("Catalogue deleted");

      setCatalogueData(null);

      setCatalogueTitle("");

      setPdfFile(null);

      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
    } catch (error) {
      console.log(error);

      toast.error("Delete failed");
    }
  };

  useEffect(() => {
    getAllTiles();

    getCatalogue();
  }, []);

  const onSubmit = async (values: TilesFormType) => {
    try {
      setLoading(true);

      const payload = {
        category: values.category,

        designName: values.designName,

        size: values.size,

        sizeInch: values.sizeInch,

        pcsPerBox: Number(values.pcsPerBox),

        sqFtPerBox: Number(values.sqFtPerBox),

        pricePerBox: Number(values.pricePerBox),
      };

      if (editId) {
        await axios.put(
          `${process.env.NEXT_PUBLIC_API_BASE_URL}/tiles/${editId}`,
          payload,
          {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          },
        );

        toast.success("Tile updated successfully!");
      } else {
        await axios.post(
          `${process.env.NEXT_PUBLIC_API_BASE_URL}/tiles/create`,
          payload,
          {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          },
        );

        toast.success("Tile created successfully!");
      }

      form.reset();

      setEditId(null);

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

      if (axios.isAxiosError(error)) {
        const message =
          error.response?.data?.message || error.response?.data?.error || "";

        if (
          message.toLowerCase().includes("duplicate") ||
          message.toLowerCase().includes("exists") ||
          message.toLowerCase().includes("already")
        ) {
          toast.error("Tile product already exists");
        } else {
          toast.error(message || "Something went wrong");
        }
      } else {
        toast.error("Something went wrong");
      }
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = (item: TileType) => {
    setEditId(item._id);

    form.setValue("category", item.category);

    form.setValue("designName", item.designName);

    form.setValue("size", item.size);

    form.setValue("sizeInch", item.sizeInch);

    form.setValue("pcsPerBox", String(item.pcsPerBox));

    form.setValue("sqFtPerBox", String(item.sqFtPerBox));

    form.setValue("pricePerBox", String(item.pricePerBox));
  };

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

      toast.success("Tile deleted successfully!");

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

      toast.error("Failed to delete tile");
    }
  };

  return (
    <div className="mt-6 space-y-8">
      <Toaster
        position="top-center"
        reverseOrder={false}
      />

      {/* All PDF  */}
      <Card>
        <CardHeader>
          <CardTitle>Tiles Catalogue PDF</CardTitle>
        </CardHeader>

        <CardContent className="space-y-5">
          <div className="space-y-2">
            <Label>Catalogue Title</Label>

            <Input
              value={catalogueTitle}
              onChange={(e) => setCatalogueTitle(e.target.value)}
              placeholder="Enter title"
            />
          </div>

          <div className="space-y-2">
            <Label>Select PDF</Label>

            <Input
              ref={fileInputRef}
              type="file"
              accept=".pdf"
              onChange={(e) => setPdfFile(e.target.files?.[0] || null)}
            />
          </div>

          <Button
            onClick={uploadCatalogue}
            disabled={catalogueLoading}>
            {catalogueLoading ? "Uploading..." : "Upload Catalogue"}
          </Button>

          {catalogueData && (
            <div className="space-y-3 rounded-xl border p-4">
              <p className="font-medium">{catalogueData.title}</p>

              <div className="flex gap-3">
                <Button
                  type="button"
                  onClick={() =>
                    window.open(
                      `http://app.keroindia.com${catalogueData.pdfUrl}`,
                      "_blank",
                    )
                  }>
                  View PDF
                </Button>

                <Button
                  variant="destructive"
                  onClick={deleteCatalogue}>
                  Delete PDF
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>
            {editId ? "Edit Tile Product" : "Create Tile Product"}
          </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">
                <Field>
                  <FieldLabel>Category</FieldLabel>

                  <Input
                    value="Tiles"
                    disabled
                  />
                </Field>

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

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

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

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

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

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

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

                      <Input
                        {...field}
                        placeholder="Enter size inch"
                        // type="number"
                      />

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

                <Controller
                  name="pcsPerBox"
                  control={form.control}
                  render={({ field, fieldState }) => (
                    <Field data-invalid={fieldState.invalid}>
                      <FieldLabel>PCS Per Box</FieldLabel>

                      <Input
                        {...field}
                        placeholder="Enter pcs per box"
                        type="number"
                      />

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

                <Controller
                  name="sqFtPerBox"
                  control={form.control}
                  render={({ field, fieldState }) => (
                    <Field data-invalid={fieldState.invalid}>
                      <FieldLabel>SQ FT Per Box</FieldLabel>

                      <Input
                        {...field}
                        placeholder="Enter sq ft per box"
                      />

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

                <Controller
                  name="pricePerBox"
                  control={form.control}
                  render={({ field, fieldState }) => (
                    <Field data-invalid={fieldState.invalid}>
                      <FieldLabel>Price Per Box</FieldLabel>

                      <Input
                        {...field}
                        placeholder="Enter price per box"
                        type="number"
                      />

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

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

      <Card>
        <CardHeader>
          <CardTitle>All Tile Products</CardTitle>
        </CardHeader>

        <CardContent className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Category</TableHead>

                <TableHead>Design Name</TableHead>

                <TableHead>Size</TableHead>

                <TableHead>Size Inch</TableHead>

                <TableHead>PCS/Box</TableHead>

                <TableHead>SQ FT/Box</TableHead>

                <TableHead>Price/Box</TableHead>

                <TableHead>Status</TableHead>

                <TableHead>Actions</TableHead>
              </TableRow>
            </TableHeader>

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

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

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

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

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

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

                  <TableCell>₹ {item.pricePerBox}</TableCell>

                  <TableCell>{item.isActive ? "Active" : "Inactive"}</TableCell>

                  <TableCell>
                    <div className="flex gap-2">
                      <Button
                        type="button"
                        size="sm"
                        onClick={() => handleEdit(item)}>
                        Edit
                      </Button>

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

export default TilesProductPage;
