"use client";
import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { Modal } from "@/src/components/admin/ui/modal";
import { useModal } from "@/src/hooks/admin/useModal";
import DatePicker from "@/src/components/admin/form/date-picker";
import Input from "@/src/components/admin/form/input/InputField";
import TextArea from "@/src/components/admin/form/input/TextArea";
import Label from "@/src/components/admin/form/Label";
import FormGroup from "@/src/components/admin/form/FormGroup";
import { createSiteVisit } from "@/src/services/admin/services";
import { toast } from "react-hot-toast";

const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
const MAX_FILES = 10;
const ALLOWED_FILE_TYPES = ['image/jpeg', 'image/jpg', 'image/png', 'application/pdf'];

const siteVisitSchema = z.object({
  visit_date: z.string().min(1, "Visit date is required"),
  remark: z.string().optional(),
  photos: z
    .custom<FileList>()
    .refine((files) => files && files.length > 0, "At least one file is required")
    .refine((files) => files && files.length <= MAX_FILES, `Maximum ${MAX_FILES} files allowed`)
    .refine(
      (files) => files && Array.from(files).every((file) => file.size <= MAX_FILE_SIZE),
      "Each file must be less than 10MB"
    )
    .refine(
      (files) => files && Array.from(files).every((file) => ALLOWED_FILE_TYPES.includes(file.type)),
      "Only JPEG, JPG, PNG, and PDF files are allowed"
    ),
});

type SiteVisitFormData = z.infer<typeof siteVisitSchema>;

interface SiteVisitUploadModalProps {
  applicationId: string;
  onSuccess?: () => void;
}

export default function SiteVisitUploadModal({ 
  applicationId, 
  onSuccess 
}: SiteVisitUploadModalProps) {
  const { isOpen, openModal, closeModal } = useModal();
  const [files, setFiles] = useState<File[]>([]);
  const [deleteIndex, setDeleteIndex] = useState<number | null>(null);

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
    setError,
    setValue,
    watch,
    reset,
  } = useForm<SiteVisitFormData>({
    resolver: zodResolver(siteVisitSchema),
    defaultValues: {
      visit_date: "",
      remark: "",
    },
  });

  const visitDate = watch("visit_date");

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      const newFiles = Array.from(e.target.files);
      const updatedFiles = [...files, ...newFiles];
      
      if (updatedFiles.length > MAX_FILES) {
        toast.error(`Maximum ${MAX_FILES} files allowed`);
        setError("photos", {
          type: "custom",
          message: `Maximum ${MAX_FILES} files allowed`,
        })
        return;
      }

      setFiles(updatedFiles);
      
      const dataTransfer = new DataTransfer();
      updatedFiles.forEach(file => dataTransfer.items.add(file));
      setValue("photos", dataTransfer.files, { shouldValidate: true });
    }
  };

  const onSubmit = async (data: SiteVisitFormData) => {
    try {
      const formData = new FormData();
      formData.append("visit_date", data.visit_date);
      formData.append("remark", data.remark || "");

      files.forEach((file) => {
        formData.append("photos", file);
      });

      await createSiteVisit(Number(applicationId), formData);

      toast.success("Site visit uploaded successfully!");
      
      reset();
      setFiles([]);
      closeModal();
      
      if (onSuccess) {
        onSuccess();
      }
    } catch (error) {
      console.error("Error uploading site visit:", error);
      toast.error(error instanceof Error ? error.message : "Failed to upload site visit");
    }
  };

  const openDeleteConfirm = (index: number) => {
    setDeleteIndex(index);
  };

  const closeDeleteConfirm = () => {
    setDeleteIndex(null);
  };

  const confirmDelete = () => {
    if (deleteIndex === null) return;
    const updatedFiles = files.filter((_, i) => i !== deleteIndex);
    setFiles(updatedFiles);
    
    const dataTransfer = new DataTransfer();
    updatedFiles.forEach(file => dataTransfer.items.add(file));
    setValue("photos", dataTransfer.files, { shouldValidate: true });
    
    closeDeleteConfirm();
    toast.success("File removed");
  };

  const handleClose = () => {
    if (!isSubmitting) {
      reset();
      setFiles([]);
      closeModal();
    }
  };

  return (
    <div>
      <button
        onClick={openModal}
        className="bg-teal-600 hover:bg-teal-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition cursor-pointer flex items-center gap-2 shadow-sm"
      >
        Upload Site Visit
      </button>

      {/* Delete Confirmation Modal */}
      <Modal
        isOpen={deleteIndex !== null}
        onClose={closeDeleteConfirm}
        className="max-w-xl w-full overflow-hidden rounded-2xl shadow-2xl"
      >
        <div className="bg-white px-6 py-6">
          <h4 className="text-lg font-bold text-gray-900">Remove File?</h4>
          <p className="mt-2 text-sm text-gray-600">
            Are you sure you want to remove this file?
          </p>

          {deleteIndex !== null && (
            <p className="mt-2 text-xs text-gray-500 truncate">
              {files[deleteIndex]?.name}
            </p>
          )}

          <div className="mt-6 flex justify-end gap-3">
            <button
              onClick={closeDeleteConfirm}
              className="px-4 py-2 rounded-lg text-sm text-gray-600 hover:bg-gray-100"
            >
              Cancel
            </button>
            <button
              onClick={confirmDelete}
              className="px-4 py-2 rounded-lg bg-red-600 text-white hover:bg-red-700"
            >
              Delete
            </button>
          </div>
        </div>
      </Modal>

      {/* Upload Modal */}
      <Modal
        isOpen={isOpen}
        onClose={handleClose}
        className="max-w-xl w-full overflow-hidden rounded-2xl shadow-2xl transition-all"
      >
        <div className="bg-white px-6 py-7 sm:p-8">
          <div className="mb-6">
            <h4 className="text-2xl font-extrabold text-gray-900 tracking-tight">
              Upload Site Visit
            </h4>
            <p className="mt-1 text-sm text-gray-500">
              Add site visit date, upload documents, and remarks.
            </p>
          </div>

          <form onSubmit={handleSubmit(onSubmit)} className="space-y-5">
            {/* Date */}
            <FormGroup>
              <DatePicker
                id="siteVisitDate"
                label="Site Visit Date"
                placeholder="Select site visit date"
                value={visitDate}
                onChange={(val) => setValue("visit_date", val, { shouldValidate: true })}
                required
              />
              {errors.visit_date && (
                <p className="text-xs text-error-500 mt-1.5">{errors.visit_date.message}</p>
              )}
            </FormGroup>

            {/* File Upload */}
            <FormGroup>
              <Label htmlFor="photos">
                Upload Documents (Max {MAX_FILES}) <span className="text-red-500">*</span>
              </Label>
              <input
                id="photos"
                type="file"
                multiple
                accept="image/jpeg,image/jpg,image/png,application/pdf"
                onChange={handleFileChange}
                disabled={files.length >= MAX_FILES}
                className="w-full border border-dashed border-gray-300 rounded-xl px-4 py-3 text-gray-600 cursor-pointer file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:bg-teal-600 file:text-white hover:file:bg-teal-900 transition disabled:opacity-50 disabled:cursor-not-allowed"
              />
              <p className="text-xs text-gray-500 mt-1.5">
                Allowed: JPEG, JPG, PNG, PDF (Max 10MB each) • {files.length}/{MAX_FILES} files
              </p>
              {errors.photos && (
                <p className="text-xs text-error-500 mt-1.5">{errors.photos.message as string}</p>
              )}

              {files.length > 0 && (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-3">
                  {files.map((file, index) => (
                    <div
                      key={index}
                      className="relative group border border-gray-200 rounded-xl p-4 bg-gray-50 hover:bg-white hover:border-teal-500 hover:shadow-md transition-all"
                    >
                      <button
                        onClick={() => openDeleteConfirm(index)}
                        className="absolute -top-2 -right-2 bg-red-500 hover:bg-red-600 text-white rounded-full p-1.5 opacity-0 group-hover:opacity-100 transition-opacity shadow-lg z-10"
                        type="button"
                      >
                        <svg
                          width="12"
                          height="12"
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="4"
                        >
                          <path d="M18 6L6 18M6 6l12 12" />
                        </svg>
                      </button>

                      <div className="flex items-start gap-3">
                        <div className="bg-teal-100 p-3 rounded-lg text-teal-700">
                          <svg
                            width="24"
                            height="24"
                            fill="currentColor"
                            viewBox="0 0 20 20"
                          >
                            <path d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z" />
                          </svg>
                        </div>

                        <div className="flex-1 min-w-0">
                          <p
                            className="text-sm font-bold text-gray-800 truncate"
                            title={file.name}
                          >
                            {file.name}
                          </p>
                          <p className="text-xs text-gray-500 mt-1">
                            {(file.size / 1024).toFixed(1)} KB
                          </p>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </FormGroup>

            {/* Remark */}
            <FormGroup>
              <Label htmlFor="remark">Remark</Label>
              <TextArea
                id="remark"
                placeholder="Add site visit notes..."
                rows={5}
                error={!!errors.remark}
                errorMessage={errors.remark?.message}
                {...register("remark")}
              />
            </FormGroup>

            {/* Actions */}
            <div className="mt-8 flex items-center justify-end gap-3">
              <button
                type="button"
                onClick={handleClose}
                disabled={isSubmitting}
                className="px-5 py-2.5 rounded-xl text-sm font-medium text-gray-600 hover:bg-gray-100 transition-colors active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={isSubmitting}
                className="bg-teal-600 hover:bg-teal-700 active:bg-teal-800 text-white font-semibold px-7 py-2.5 rounded-xl shadow-md shadow-teal-500/20 transition-all active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
              >
                {isSubmitting ? (
                  <>
                    <svg
                      className="animate-spin h-4 w-4"
                      xmlns="http://www.w3.org/2000/svg"
                      fill="none"
                      viewBox="0 0 24 24"
                    >
                      <circle
                        className="opacity-25"
                        cx="12"
                        cy="12"
                        r="10"
                        stroke="currentColor"
                        strokeWidth="4"
                      ></circle>
                      <path
                        className="opacity-75"
                        fill="currentColor"
                        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                      ></path>
                    </svg>
                    Uploading...
                  </>
                ) : (
                  "Submit"
                )}
              </button>
            </div>
          </form>
        </div>
      </Modal>
    </div>
  );
}

   