"use client";
import React, { useState, useEffect } from "react";
import Navbar from "../components/Navbar";
import Footer from "../components/Footer";
import FormField from "../components/FormField";
import OperationList from "../components/OparationList";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { useAuthState } from "react-firebase-hooks/auth";
import { auth } from "@/app/firebase/config";

const Review = ({ id }: { id: string | null }) => {
  const [operations, setOperations] = useState<any[]>([]);
  const [formData, setFormData] = useState<any>({});
  const [loading, setLoading] = useState(false);

  const [user] = useAuthState(auth);
  const router = useRouter();

  useEffect(() => {
    if (typeof window !== "undefined") {
      const userSession = sessionStorage.getItem("user");

      console.log(user);

      if (!user && !userSession) {
        router.push("/login");
      }
    }
  }, [user, router]);

  useEffect(() => {
    console.log({ id });
    const fetchFormData = async () => {
      try {
        const response = await fetch(
          `${process.env.NEXT_PUBLIC_RENDER_LINK}/get-custom-data?id=${id}`
        ); // Fetch data based on id
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();

        // Ensure the data contains all necessary fields
        const operations = Object.keys(data)
          .filter(
            (key) =>
              key.startsWith("B") &&
              !isNaN(Number(key.slice(1))) &&
              Number(key.slice(1)) >= 16
          )
          .map((key, index) => ({
            id: index + 1,
            key,
            description: data[key],
            explanation: data[`H${index + 16}`] || "", // Adjust as needed
            checkbox: data[`D${index + 16}`] || "", // Adjust as needed
          }));

        setFormData(data);
        setOperations(operations);
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    };

    if (id) {
      fetchFormData();
    }
  }, [id]);

  const handleDownload = async () => {
    setLoading(true);
    try {
      const response = await fetch(
        `${process.env.NEXT_PUBLIC_RENDER_LINK}/fill-excel?id=${id}`
      );
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`Excel indirme hatası: ${errorText}`);
      }

      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = `${formData.I6}.xlsx`;
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);
      setLoading(false);
    } catch (error) {
      setLoading(false);
      console.error("Excel indirme hatası:", error);
    }
  };

  const handleRemoveOperation = (id: number) => {
    setOperations((prevOperations) =>
      prevOperations.filter((operation) => operation.id !== id)
    );
  };

  return (
    <div>
      <Navbar isShow={false} toggleRightSidePage={() => {}}/>
      <div className="max-w-3xl mx-auto bg-slate-200 p-8 rounded-lg shadow-md mt-10 mb-10">
        <h1 className="text-3xl text-neutral mb-6 text-center">
          {formData.C1}
        </h1>
        <form id="excelForm">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            {/* Render FormField components with formData values */}
            <FormField
              id="baslik"
              label="Başlık:"
              name="C1"
              placeholder="Başlık girin"
              required={false}
              readOnly={true}
              defaultValue={formData.C1 ?? ""}
            />
            <FormField
              id="yayınlanmaTarihi"
              label="Yayınlanma Tarihi:"
              name="J1"
              placeholder="Yayınlanma tarihi girin"
              required={false}
              readOnly={true}
              defaultValue={formData.J1 ?? ""}
            />
            <FormField
              id="dokumanKodu"
              label="Döküman Kodu:"
              name="J2"
              placeholder="Döküman kodu girin"
              required={false}
              readOnly={true}
              defaultValue={formData.J2 ?? ""}
            />
            <FormField
              id="versionNoTarih"
              label="Version No/Tarih:"
              name="J3"
              placeholder="Version No/Tarih girin"
              required={false}
              readOnly={true}
              defaultValue={formData.J3 ?? ""}
            />
            <FormField
              id="sayfaNo"
              label="Sayfa No:"
              name="J4"
              placeholder="Sayfa No girin"
              required={false}
              readOnly={true}
              defaultValue={formData.J4 ?? ""}
            />
            <FormField
              id="proje"
              label="Proje:"
              name="C5"
              placeholder="Proje girin"
              required={false}
              readOnly={true}
              defaultValue={formData.C5 ?? ""}
            />
            <FormField
              id="adres"
              label="Adres:"
              name="C6"
              placeholder="Adres girin"
              required={false}
              readOnly={true}
              defaultValue={formData.C6 ?? ""}
            />
            <FormField
              id="bakimTarihi"
              label="Bakım Tarihi:"
              name="I5"
              placeholder="Bakım tarihi girin"
              required={false}
              readOnly={true}
              defaultValue={formData.I5 ?? ""}
            />
            <FormField
              id="isEmriNo"
              label="İş Emri No:"
              name="I6"
              placeholder="Otomatik Olarak Atanacak"
              required={false}
              readOnly={true}
              defaultValue={formData.I6 ?? ""}
            />
            <FormField
              id="marka"
              label="Markası:"
              name="C8"
              placeholder="Marka girin"
              required={false}
              readOnly={true}
              defaultValue={formData.C8 ?? ""}
            />
            <FormField
              id="tipModel"
              label="Tipi/Modeli:"
              name="C9"
              placeholder="Tipi/Modeli girin"
              required={false}
              readOnly={true}
              defaultValue={formData.C9 ?? ""}
            />
            <FormField
              id="seriNo"
              label="Seri No:"
              name="C10"
              placeholder="Seri No girin"
              required={false}
              readOnly={true}
              defaultValue={formData.C10 ?? ""}
            />
            <FormField
              id="imalatYili"
              label="İmalat Yılı:"
              name="C11"
              placeholder="İmalat yılı girin"
              required={false}
              readOnly={true}
              defaultValue={formData.C11 ?? ""}
            />
            <div>
              <label
                htmlFor="bakimPeriyodu"
                className="block text-gray-700 mb-2"
              >
                Bakım Periyodu:
              </label>
              <div className="flex items-center space-x-4">
                <div className="flex items-center">
                  <input
                    type="radio"
                    id="bakimPeriyodu6"
                    name="C12"
                    value="6 Ay"
                    className="checkbox mr-2"
                    disabled
                    checked={formData.C12 === "6 Ay"}
                  />
                  <label htmlFor="bakimPeriyodu6" className="text-gray-700">
                    6 Ay
                  </label>
                </div>
                <div className="flex items-center">
                  <input
                    type="radio"
                    id="bakimPeriyodu12"
                    name="C12"
                    value="12 Ay"
                    className="checkbox mr-2"
                    disabled
                    checked={formData.C12 === "12 Ay"}
                  />
                  <label htmlFor="bakimPeriyodu12" className="text-gray-700">
                    12 Ay
                  </label>
                </div>
              </div>
            </div>
            <FormField
              id="bulunduguYer"
              label="Bulunduğu Yer:"
              name="I8"
              placeholder="Bulunduğu yer girin"
              required={false}
              readOnly={true}
              defaultValue={formData.I8 ?? ""}
            />
            <FormField
              id="kapasitesi"
              label="Kapasitesi:"
              name="I9"
              placeholder="Kapasite girin"
              required={false}
              readOnly={true}
              defaultValue={formData.I9 ?? ""}
            />
            <FormField
              id="kullananBirim"
              label="Kullanan Birim:"
              name="I10"
              placeholder="Kullanan birim girin"
              required={false}
              readOnly={true}
              defaultValue={formData.I10 ?? ""}
            />
            <FormField
              id="sonrakiBakimTarihi"
              label="Bir Sonraki Bakım Tarihi:"
              name="I11"
              placeholder="Bir sonraki bakım tarihi girin"
              required={false}
              readOnly={true}
              defaultValue={formData.I11 ?? ""}
            />
          </div>

          <OperationList
            deleteBtn={false}
            operations={operations}
            onRemove={handleRemoveOperation}
            disabled={true}
            readOnlyAva={true}
            readOnlyDes={true}
            requiredCheck={false}
            requiredText={false}
          />

          <label htmlFor="bakimPeriyodu" className="block text-gray-700 mb-2">
            Tespit edilen uygunsuzluklar ve öneriler:
          </label>
          <textarea
            className="textarea textarea-bordered w-full mb-2 bg-gray-200 cursor-not-allowed"
            placeholder="Uygunsuzluk ve öneri girin"
            name="A1"
            readOnly
            defaultValue={formData.A1 ?? ""}
          ></textarea>

          <label htmlFor="bakimPeriyodu" className="block text-gray-700 mb-2">
            Sonuç:
          </label>
          <textarea
            className="textarea textarea-bordered w-full mb-2 bg-gray-200 cursor-not-allowed"
            placeholder="Sonuç girin"
            name="A2"
            readOnly
            defaultValue={formData.A2 ?? ""}
          ></textarea>

          <div className="mb-6 flex justify-between">
            <button
              type="button"
              className="btn btn-info text-lg"
              onClick={handleDownload}
              disabled={loading} // Buton yükleme süresince devre dışı bırakılır
            >
              {loading ? "Yükleniyor..." : "İndir"}
            </button>

            <Link href="/search">
              <button type="button" className="btn btn-error text-lg">
                Geri
              </button>
            </Link>
          </div>
        </form>
      </div>
      <Footer />
    </div>
  );
};

export default Review;
