'use client';

import React, { useEffect, useState } from 'react';
import DashboardLayout from '@/app/dashboard/layout';
import {
  Dialog,
  DialogTrigger,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogClose
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Eye, Loader2, Pencil } from 'lucide-react';
import apis, { BUCKET_ROOT } from '@/utils/apis';
import { useGlobalContext } from '@/context/Provider';
import { useRouter } from 'next/navigation';
import moment from 'moment';

type DocumentType = {
  _id: string;
  requirement_id: string;
  restaurant_id: string;
  document_value: string | null;
  document_value_back: string | null;
  expiry_date: number | string | null;
  createdAt: string;
  document_name: string;
  requirement_is_expiry: boolean;
  is_required: boolean;
  response_type: 'image' | 'both_side_image' | 'number';
  frontFile?: File;
  backFile?: File;
};

const formatDate = (date: number | string | null | undefined, formatStr = 'DD/MM/YYYY') => {
  if (!date) return null;
  const num = typeof date === 'number' ? date : Number(date);
  const m = !isNaN(num) && num > 1000000000 ? moment(num) : moment(date);
  return m.isValid() ? m.format(formatStr) : null;
};

const Documents = () => {
  const { Toast, userInfo } = useGlobalContext();
  const router = useRouter();

  const [documents, setDocuments] = useState<DocumentType[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedDoc, setSelectedDoc] = useState<DocumentType | null>(null);
  const [editModalOpen, setEditModalOpen] = useState(false);
  const [viewModalOpen, setViewModalOpen] = useState(false);
  const [restaurantId, setRestaurantId] = useState<string>('');

  useEffect(() => {
    const fetchDocs = async () => {
      try {
        if (!userInfo?.restaurant_id) return;
        const resId = userInfo.restaurant_id._id;
        setRestaurantId(resId);
        const params = new URLSearchParams({
          restaurant_id: resId,
          page: '1',
          limit: '10'
        });

        const res = await apis.Documents.getUploadedDocumets(params.toString());
        if (res) {
          setDocuments(res.data);
        } else {
          console.error('Fetch failed:', res.message);
        }
      } catch (err) {
        console.error('Error fetching documents', err);
      } finally {
        setLoading(false);
      }
    };

    fetchDocs();
  }, [userInfo]);

  const renderDocumentValue = (doc: any) => {
    switch (doc.response_type) {
      case "number":
        return <span>{doc.document_value}</span>;

      case "image":
        return (
          <img
            src={`/uploads/${doc.document_value}`}
            alt={doc.document_name}
            className="w-32 h-auto object-cover rounded border"
          />
        );

      case "both_side_image":
        return (
          <div className="flex gap-4">
            <img
              src={`/uploads/${doc.document_value}`}
              alt="Front Side"
              className="w-32 h-auto object-cover rounded border"
            />
            {doc.document_value_back && (
              <img
                src={`/uploads/${doc.document_value_back}`}
                alt="Back Side"
                className="w-32 h-auto object-cover rounded border"
              />
            )}
          </div>
        );

      default:
        return <span className="text-gray-400">Unknown Type</span>;
    }
  };


  const openEdit = (doc: DocumentType) => {
    const found = documents.find((d) => d._id === doc._id);
    setSelectedDoc(found || doc);
    setEditModalOpen(true);
  };

  const openView = (doc: DocumentType) => {
    setSelectedDoc(doc);
    setViewModalOpen(true);
  };

  useEffect(() => {
    if (selectedDoc) {
      setDocuments((prevDocs) =>
        prevDocs.map((doc) =>
          doc._id === selectedDoc._id ? selectedDoc : doc
        )
      );
    }
  }, [selectedDoc]);

  const handleFileChange = async (
    requirementId: string,
    event: React.ChangeEvent<HTMLInputElement>,
    side: 'front' | 'back' = 'front'
  ) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const maxFileSize = 5 * 1024 * 1024;
    const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg'];

    if (!allowedTypes.includes(file.type)) {
      Toast.error('Only JPG and PNG images are allowed.');
      return;
    }

    if (file.size > maxFileSize) {
      Toast.error('Image size cannot be more than 5MB.');
      return;
    }

    try {
      const uploadRes = await apis.Common.uploadFile('file', file);

      setDocuments((prev) => {
        const updated = prev.map((doc) =>
          doc.requirement_id === requirementId
            ? {
              ...doc,
              [side === 'front' ? 'document_value' : 'document_value_back']:
                uploadRes?.key || '',
              [side === 'front' ? 'frontFile' : 'backFile']: file
            }
            : doc
        );

        // Update selectedDoc if it matches
        const updatedSelected = updated.find(
          (doc) => doc.requirement_id === requirementId
        );
        setSelectedDoc(updatedSelected || null);

        return updated;
      });

      Toast.success('Document uploaded successfully!');
    } catch (err) {
      Toast.error('Failed to upload document.');
    }
  };

  const handleSubmit = async () => {
    const requiredDocs = documents.filter((doc) => doc.is_required);

    const allRequiredUploaded = requiredDocs.every((doc) => {
      if (doc.response_type === "both_side_image") {
        return doc.document_value && doc.document_value_back;
      } else {
        return !!doc.document_value;
      }
    });

    if (!allRequiredUploaded) {
      Toast.error("Please upload all required documents.");
      return;
    }

    try {
      setLoading(true);

      const payload = {
        documents: documents.map((doc) => ({
          _id: doc._id,
          requirement_id: doc.requirement_id,
          restaurant_id: restaurantId,
          response_type: doc.response_type,
          document_value: doc.document_value || "",
          document_value_back: doc.document_value_back || null,
          expiry_date: doc.requirement_is_expiry
            ? doc.expiry_date
            : null,
        })),
      };

      const res = await apis.Documents.uploadDocument(payload);

      if (res) {
        Toast.success("Documents saved successfully!");
        sessionStorage.setItem("documents", "complete");
        router.push("/auth/login");
      }
    } catch (err: any) {
      Toast.error(err.message || "Failed to save documents.");
    } finally {
      setLoading(false);
    }
  };


  return (
    <div className="h-full w-full overflow-y-scroll bg-white p-6">
      {loading ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="h-8 w-8 animate-spin text-gray-500" />
        </div>
      ) : (
        <div className="grid gap-4 sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-3">
          {documents.map((doc) => {
            const formattedExpiry = formatDate(doc.expiry_date);
            return (
              <div
                key={doc._id}
                className="flex items-center justify-between rounded-lg border p-4"
              >
                <div>
                  <p className="font-semibold">{doc.document_name}</p>
                  {formattedExpiry ? (
                    <p className="mt-1 text-xs text-gray-500">
                      Expiry Date: {formattedExpiry}
                    </p>
                  ) : doc.requirement_is_expiry ? (
                    <p className="mt-1 text-xs text-amber-600">
                      Expiry Date: Not set
                    </p>
                  ) : null}
                </div>
                <div className="flex gap-2">
                  <button
                    onClick={() => openView(doc)}
                    className="rounded-md p-2 text-[var(--primary-brand)] transition-colors hover:bg-[var(--primary-brand)]/10"
                  >
                    <Eye className="h-5 w-5" />
                  </button>
                  <button
                    onClick={() => openEdit(doc)}
                    className="rounded-md p-2 text-green-500 transition-colors hover:bg-green-100"
                  >
                    <Pencil className="h-5 w-5" />
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Edit Modal */}
      <Dialog open={editModalOpen} onOpenChange={setEditModalOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>Edit Document</DialogTitle>
          </DialogHeader>

          {selectedDoc && (
            <div className="space-y-4">
              {/* Expiry Date Input */}
              {selectedDoc.requirement_is_expiry && (
                <div>
                  <label className="text-sm font-semibold text-gray-700">
                    Expiry Date
                  </label>
                  <input
                    type="date"
                    className="mt-2 w-full rounded-md border p-2 text-gray-700"
                    value={formatDate(selectedDoc.expiry_date, 'YYYY-MM-DD') || ''}
                    onChange={(e) => {
                      const val = e.target.value;
                      setSelectedDoc((prev) =>
                        prev
                          ? {
                              ...prev,
                              expiry_date: val ? new Date(val).getTime() : null,
                            }
                          : prev
                      );
                    }}
                  />
                </div>
              )}

              {/* Number Type */}
              {selectedDoc.response_type === "number" && (
                <div>
                  <label className="text-sm font-semibold text-gray-700">
                    Enter {selectedDoc.document_name} Number
                  </label>
                  <input
                    type="text"
                    className="mt-2 w-full rounded-md border p-2 text-gray-700"
                    defaultValue={selectedDoc.document_value || ""}
                    onChange={(e) =>
                      setSelectedDoc((prev) =>
                        prev ? { ...prev, document_value: e.target.value } : prev
                      )
                    }
                    placeholder={`Enter ${selectedDoc.document_name}`}
                  />
                </div>
              )}

              {/* Image Type */}
              {selectedDoc.response_type === "image" && (
                <>
                  <div className="text-lg font-semibold text-gray-700">
                    Upload Image
                  </div>
                  <div className="flex w-full flex-col items-center">
                    <label className="w-full cursor-pointer">
                      <div className="mb-2 w-full">
                        {selectedDoc.frontFile ? (
                          <img
                            src={URL.createObjectURL(selectedDoc.frontFile)}
                            alt="front"
                            className="max-h-40 w-full border object-cover"
                          />
                        ) : selectedDoc.document_value ? (
                          <img
                            src={`${BUCKET_ROOT}${selectedDoc.document_value}`}
                            alt="front"
                            className="max-h-40 w-full border object-cover"
                          />
                        ) : (
                          <div className="flex h-24 w-full items-center justify-center bg-gray-100 text-gray-400">
                            Image Not Uploaded
                          </div>
                        )}
                      </div>
                      <span className="cursor-pointer text-[var(--primary-brand)]">
                        + Upload Image
                      </span>
                      <input
                        type="file"
                        className="hidden"
                        accept=".jpg,.jpeg,.png"
                        onChange={(e) =>
                          selectedDoc?.requirement_id &&
                          handleFileChange(selectedDoc.requirement_id, e, "front")
                        }
                      />
                    </label>
                  </div>
                </>
              )}

              {/* Both Side Image Type */}
              {selectedDoc.response_type === "both_side_image" && (
                <>
                  {/* Front */}
                  <div className="text-lg font-semibold text-gray-700">Front Image</div>
                  <div className="flex w-full flex-col items-center">
                    <label className="w-full cursor-pointer">
                      <div className="mb-2 w-full">
                        {selectedDoc.frontFile ? (
                          <img
                            src={URL.createObjectURL(selectedDoc.frontFile)}
                            alt="front"
                            className="max-h-40 w-full border object-cover"
                          />
                        ) : selectedDoc.document_value ? (
                          <img
                            src={`${BUCKET_ROOT}${selectedDoc.document_value}`}
                            alt="front"
                            className="max-h-40 w-full border object-cover"
                          />
                        ) : (
                          <div className="flex h-24 w-full items-center justify-center bg-gray-100 text-gray-400">
                            Front
                          </div>
                        )}
                      </div>
                      <span className="cursor-pointer text-[var(--primary-brand)] hover:text-[var(--primary-brand)]/90 hover:underline">
                        + Upload Front
                      </span>
                      <input
                        type="file"
                        className="hidden"
                        accept=".jpg,.jpeg,.png"
                        onChange={(e) =>
                          selectedDoc?.requirement_id &&
                          handleFileChange(selectedDoc.requirement_id, e, "front")
                        }
                      />
                    </label>
                  </div>

                  {/* Back */}
                  <div className="text-lg font-semibold text-gray-700">Back Image</div>
                  <div className="flex w-full flex-col items-center">
                    <label className="w-full cursor-pointer">
                      <div className="mb-2 w-full">
                        {selectedDoc.backFile ? (
                          <img
                            src={URL.createObjectURL(selectedDoc.backFile)}
                            alt="back"
                            className="max-h-40 w-full border object-cover"
                          />
                        ) : selectedDoc.document_value_back ? (
                          <img
                            src={`${BUCKET_ROOT}${selectedDoc.document_value_back}`}
                            alt="back"
                            className="max-h-40 w-full border object-cover"
                          />
                        ) : (
                          <div className="flex h-24 w-full items-center justify-center bg-gray-100 text-gray-400">
                            Back
                          </div>
                        )}
                      </div>
                      <span className="cursor-pointer text-[var(--primary-brand)] hover:text-[var(--primary-brand)]/90 hover:underline">
                        + Upload Back
                      </span>
                      <input
                        type="file"
                        className="hidden"
                        accept=".jpg,.jpeg,.png"
                        onChange={(e) =>
                          selectedDoc?.requirement_id &&
                          handleFileChange(selectedDoc.requirement_id, e, "back")
                        }
                      />
                    </label>
                  </div>
                </>
              )}
            </div>
          )}

          <DialogFooter className="flex justify-end gap-2 pt-4">
            <DialogClose asChild>
              <Button variant="secondary" className="bg-gray-200 text-gray-700 hover:bg-gray-300">
                Cancel
              </Button>
            </DialogClose>
            <Button
              onClick={handleSubmit}
              className="h-11"
              variant={'theme'}
            >
              Save
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>


      {/* View Modal */}
      <Dialog open={viewModalOpen} onOpenChange={setViewModalOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>View Document</DialogTitle>
          </DialogHeader>

          {selectedDoc && (
            <div className="space-y-4">
              {(selectedDoc.expiry_date || selectedDoc.requirement_is_expiry) && (
                <div className="rounded border bg-gray-50 p-3 text-sm text-gray-800">
                  <span className="font-semibold text-gray-700">Expiry Date: </span>
                  {formatDate(selectedDoc.expiry_date) || "Not Set"}
                </div>
              )}
              {/* Number Type */}
              {selectedDoc.response_type === "number" && (
                <div>
                  <p className="text-lg font-semibold text-gray-700">
                    {selectedDoc.document_name}
                  </p>
                  <div className="mt-2 rounded border bg-gray-50 p-3 text-gray-800">
                    {selectedDoc.document_value || "Not Available"}
                  </div>
                </div>
              )}

              {/* Image Type */}
              {selectedDoc.response_type === "image" && (
                <div className="w-full">
                  <p className="text-lg font-semibold text-gray-700 mb-2">
                    {selectedDoc.document_name}
                  </p>
                  {selectedDoc.document_value ? (
                    <img
                      src={`${BUCKET_ROOT}${selectedDoc.document_value}`}
                      alt="Image"
                      className="max-h-60 w-full border object-cover"
                    />
                  ) : (
                    <div className="flex h-24 w-full items-center justify-center border bg-gray-100 text-gray-400">
                      Image Not Available
                    </div>
                  )}
                </div>
              )}

              {/* Both Side Image Type */}
              {selectedDoc.response_type === "both_side_image" && (
                <>
                  <div>
                    <p className="text-lg font-semibold text-gray-700">Front Image</p>
                    {selectedDoc.document_value ? (
                      <img
                        src={`${BUCKET_ROOT}${selectedDoc.document_value}`}
                        alt="Front"
                        className="max-h-60 w-full border object-cover"
                      />
                    ) : (
                      <div className="flex h-24 w-full items-center justify-center border bg-gray-100 text-gray-400">
                        Front Image Not Available
                      </div>
                    )}
                  </div>

                  <div>
                    <p className="text-lg font-semibold text-gray-700">Back Image</p>
                    {selectedDoc.document_value_back ? (
                      <img
                        src={`${BUCKET_ROOT}${selectedDoc.document_value_back}`}
                        alt="Back"
                        className="max-h-60 w-full border object-cover"
                      />
                    ) : (
                      <div className="flex h-24 w-full items-center justify-center border bg-gray-100 text-gray-400">
                        Back Image Not Available
                      </div>
                    )}
                  </div>
                </>
              )}
            </div>
          )}

          <DialogFooter>
            <DialogClose asChild>
              <Button variant="secondary" className="bg-gray-200 text-gray-700 hover:bg-gray-300">
                Close
              </Button>
            </DialogClose>
          </DialogFooter>
        </DialogContent>
      </Dialog>

    </div>
  );
};

// Wrap with layout
export default function JobAutomationPage() {
  return (
    <DashboardLayout>
      <Documents />
    </DashboardLayout>
  );
}
