"use client";

import React, { useMemo, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useNavigate } from "react-router-dom";
import { Input } from "@/shared/common/ui/input";
import { Button } from "@/shared/common/ui/button";
import { Mail, User, Phone, Text, Building } from "lucide-react";
import { useToast } from "@/shared/common/ui/use-toast";

import { userSchema, UserFormValues } from "./outgoing/formSchema";
import { useRegisterExternalPortalUser } from "../hooks/useRegisterExternalPortalUser";

import { useTenantConfig } from "@/layout/components/TenantConfig";
import { useDocumentRequirement } from "@/shared/hooks/useOrganizationReport";
import { useMyUploads } from "@/external-portal/hooks/useMyUpload";
import { useQueries } from "@tanstack/react-query";
import {
  getMyUploadById,
  submitApplication,
} from "@/external-portal/services/portalOutgoingService";
import { FilterEnum } from "@/shared/services/organizationsService";
import { UploadFileModal } from "./Registration/UploadFileModal";



type LocalizedText = { am: string; en: string };
interface Document {
  id: string;
  title: LocalizedText;
  description: LocalizedText;
  key: string;
  type: string;
  order: number;
  isActive: boolean;
  isOptional: boolean;
}

export default function SignupWithUploads() {
  const { toast } = useToast();
  const navigate = useNavigate();
  const { config: tenantConfig } = useTenantConfig();
  const { registerExternalPortalUser, isRegistering } =
    useRegisterExternalPortalUser();

  const form = useForm<UserFormValues>({
    resolver: zodResolver(userSchema),
    defaultValues: {
      email: "",
      username: "",
      phoneNumber: "",
      userType: "external_organization",
      name: { am: "", en: "" },
    },
    mode: "onChange",
  });

  // watch userType so we can load document requirements for that type
  const watchedUserType = form.watch("userType") || "external_organization";

  // Map userType to FilterEnum values (same logic you used elsewhere)
  const mappedType =
    watchedUserType === "external_organization"
      ? "organization"
      : watchedUserType;

  const filterData: FilterEnum | undefined =
    mappedType && Object.values(FilterEnum).includes(mappedType as FilterEnum)
      ? (mappedType as FilterEnum)
      : undefined;

  // fetch requirement doc for the watched user type
  const { requirementDoc } = useDocumentRequirement(filterData);

  // fetch user's previous uploads (if any) and prefill the upload list
  const { data: myUploads } = useMyUploads();

  // build latest upload ids per requirement doc (like your UploadSteps logic)
const latestUploadIds = (requirementDoc.items ?? []).map((doc) => {
  const uploadsForDoc = (myUploads ?? []).filter(
    (u) => u.documentId === doc.id
  );

  if (uploadsForDoc.length) {
    const latestUpload = uploadsForDoc.reduce((prev, current) =>
      new Date(prev.createdAt) > new Date(current.createdAt) ? prev : current
    );

    return {
      docId: doc.id,
      uploadId: latestUpload.id,
      fileInfo: latestUpload.fileInfo,
    };
  }

  return { docId: doc.id, uploadId: null, fileInfo: null };
});

  // query presigned urls for each latest upload
  const uploadQueries = useQueries({
    queries:
      latestUploadIds.map(({ uploadId }:any) => ({
        queryKey: ["myUpload", uploadId],
        queryFn: () => getMyUploadById(uploadId as string),
        enabled: !!uploadId,
      })) || [],
  });

  // build filesRecord map: docId -> presignedURL | fileName | null
  const filesRecord = latestUploadIds.reduce(
    (acc: Record<string, File | string | null>, { docId, fileInfo }: any, idx:any) => {
      const uploadData = uploadQueries[idx]?.data as
        | { data?: { presigned?: string } }
        | undefined;
      const presigned = uploadData?.data?.presigned;
      acc[docId] = presigned || fileInfo?.fileName || null;
      return acc;
    },
    {} as Record<string, File | string | null>
  );

  // local state to track uploaded files while user interacts on this page
  const [uploadedFiles, setUploadedFiles] =
    useState<Record<string, File | string | null>>(filesRecord);

  // modal state for UploadFileModal
  const [selectedDoc, setSelectedDoc] = useState<Document | null>(null);
  const [modalOpen, setModalOpen] = useState(false);

  const openUploadModal = (doc: Document) => {
    setSelectedDoc(doc);
    setModalOpen(true);
  };

  const handleUploadComplete = (file: File | null | string) => {
    if (!selectedDoc) return;
    const newFiles = { ...uploadedFiles, [selectedDoc.id]: file };
    setUploadedFiles(newFiles);
    setSelectedDoc(null);
    setModalOpen(false);

    if (file) {
      toast({
        title: "Success",
        description:
          "File uploaded successfully. You will be notified of your status via SMS shortly.",
        variant: "default",
      });
    }
  };

  // Signup submit: registers the user then triggers submitApplication (if desired)
  const onSubmit = async (values: UserFormValues) => {
    try {
      // 1) Register user (existing hook)
      await registerExternalPortalUser(values);

      // 2) After registration, optionally submit an application.
      // Your uploadDocuments hook (used in UploadFileModal) already uploads
      // files during the modal upload action. submitApplication() finalizes/sends the application.
      try {
        await submitApplication();
      } catch (err) {
        // non-blocking: show toast but continue to navigate to verify OTP
        console.error("submitApplication error", err);
        toast({
          title: "Warning",
          description:
            "Account created but application submission failed. You can retry later.",
          variant: "destructive",
        });
      }

      // 3) Navigate to verify-otp with query params (same behavior you had)
      const params = new URLSearchParams();
      if (values.email) params.set("email", values.email.trim());
      if (values.phoneNumber) {
        const normalizedPhone = values.phoneNumber.trim().replace(/^0/, "+251");
        params.set("phone", normalizedPhone);
      }
      navigate(`/external-portal/verify-otp?${params.toString()}`);
    } catch (error) {
      console.error("Signup error:", error);
      toast({
        title: "Error",
        description: "Failed to create account. Please check your details.",
        variant: "destructive",
      });
    }
  };

  // helper localizer — re-use your localized name hook if needed (not provided here).
  const localized = (t: LocalizedText) => t?.en || t?.am || "";

  // count uploaded files
  const attachedCount = useMemo(
    () => Object.values(uploadedFiles).filter((f) => f !== null).length,
    [uploadedFiles]
  );

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 flex items-center justify-center p-4">
      <div className="w-full max-w-6xl bg-white rounded-2xl shadow-xl overflow-hidden flex flex-col md:flex-row h-full max-h-[900px]">
        {/* Left: Signup form */}
        <div className="md:w-1/2 w-full p-8 md:p-12 flex flex-col gap-4">
          <div className="flex items-center mb-4">
            <img
              src={tenantConfig.logo || "/assets/smart-office-logo.svg"}
              alt={tenantConfig.appName}
              className="h-10 object-contain"
            />
            <span className="ml-2 text-xl font-semibold text-gray-800">
              {tenantConfig.appName}
            </span>
          </div>

          <div>
            <h1 className="text-2xl font-bold mb-1">Create Account</h1>
            <p className="text-sm text-gray-500">
              Create your account and upload required documents on the right.
            </p>
          </div>

          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="mt-4 flex-1 flex flex-col">
            <div className="space-y-4">
              <div className="relative">
                <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <Input
                  {...form.register("email")}
                  type="email"
                  placeholder="Email"
                  className="pl-10 h-12"
                />
              </div>

              <div className="relative">
                <User className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <Input
                  {...form.register("username")}
                  type="text"
                  placeholder="Username"
                  className="pl-10 h-12"
                />
              </div>

              <div className="relative">
                <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <Input
                  {...form.register("phoneNumber")}
                  type="tel"
                  placeholder="Phone Number"
                  className="pl-10 h-12"
                />
              </div>

              <div className="relative">
                <Text className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <Input
                  {...form.register("name.en")}
                  type="text"
                  placeholder="Name (English)"
                  className="pl-10 h-12"
                />
              </div>

              <div className="relative">
                <Text className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <Input
                  {...form.register("name.am")}
                  type="text"
                  placeholder="Name (Amharic)"
                  className="pl-10 h-12"
                />
              </div>

              {/* userType control — you may already have this as a select / radio; using plain input for brevity */}
              <div>
                <label className="text-sm text-gray-600">Account type</label>
                <div className="mt-2 flex gap-2">
                  <label
                    className={`px-3 py-2 rounded-md border ${
                      form.getValues("userType") === "external_organization"
                        ? "bg-primary-50 border-primary"
                        : ""
                    }`}>
                    <input
                      type="radio"
                      {...form.register("userType")}
                      value="external_organization"
                      className="mr-2"
                    />
                    Organization
                  </label>
                  <label
                    className={`px-3 py-2 rounded-md border ${
                      form.getValues("userType") === "individual"
                        ? "bg-primary-50 border-primary"
                        : ""
                    }`}>
                    <input
                      type="radio"
                      {...form.register("userType")}
                      value="individual"
                      className="mr-2"
                    />
                    Individual
                  </label>
                </div>
              </div>
            </div>

            <div className="mt-auto pt-4">
              <Button
                type="submit"
                className="w-full h-12 bg-primary hover:bg-primary-700 text-white"
                disabled={isRegistering}>
                {isRegistering
                  ? "Creating Account..."
                  : "Create account & submit"}
              </Button>

              <p className="text-center text-sm text-gray-500 mt-3">
                Already have an account?{" "}
                <a href="/login" className="text-primary">
                  Sign in
                </a>
              </p>
            </div>
          </form>
        </div>

        {/* Vertical divider */}
        <div className="hidden md:block w-px bg-gray-200" />

        {/* Right: Upload document area (changes by userType) */}
        <div className="md:w-1/2 w-full p-6 md:p-10">
          <div className="flex items-center justify-between mb-4">
            <div>
              <h3 className="text-lg font-semibold">
                Upload Required Documents
              </h3>
              <p className="text-sm text-gray-500">
                Required documents for:{" "}
                <span className="font-medium">{mappedType}</span>
              </p>
            </div>
            <div className="text-sm text-gray-600">
              {attachedCount} attached
            </div>
          </div>

          <div className="space-y-3 max-h-[62vh] overflow-auto">
            {requirementDoc?.items?.length === 0 && (
              <div className="text-sm text-gray-500">
                No document requirements for this account type.
              </div>
            )}

            {requirementDoc?.items?.map((doc: Document) => (
              <div
                key={doc.id}
                className="flex items-center justify-between p-3 border rounded-md">
                <div className="flex flex-col">
                  <span className="font-medium">{localized(doc.title)}</span>
                  {doc.description && (
                    <span className="text-sm text-muted-foreground">
                      {localized(doc.description)}
                    </span>
                  )}
                </div>

                <div className="flex gap-2 items-center">
                  {uploadedFiles[doc.id] && (
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => {
                        const file = uploadedFiles[doc.id];
                        if (!file) return;
                        if (typeof file === "string") {
                          window.open(file, "_blank");
                        } else if (file instanceof File) {
                          const url = URL.createObjectURL(file);
                          window.open(url, "_blank");
                        }
                      }}>
                      View
                    </Button>
                  )}

                  <Button
                    size="sm"
                    className="bg-primary-600"
                    onClick={() => openUploadModal(doc)}>
                    {uploadedFiles[doc.id] ? "Replace" : "Upload"}
                  </Button>
                </div>
              </div>
            ))}
          </div>

          <div className="mt-4 text-sm text-gray-500">
            Tip: You can upload files now or complete your account and upload
            later.
          </div>
        </div>
      </div>

      {/* Upload modal */}
      {modalOpen && selectedDoc && (
        <UploadFileModal
          value={uploadedFiles[selectedDoc.id] || null}
          multiple={false}
          accept={[
            ".png",
            ".jpg",
            ".jpeg",
            ".pdf",
            ".dwg",
            ".dxf",
            ".dwt",
            ".bak",
            ".sv$",
            ".dws",
            ".mxd",
            ".aprx",
            ".rar",
            ".zip",
          ]}
          onChange={(file) => {
            if (file === null) handleUploadComplete(null);
            else if (file instanceof File) handleUploadComplete(file);
            else if (Array.isArray(file) && file[0])
              handleUploadComplete(file[0]);
          }}
          fileUploadFields={{
            requiredDocumentId: selectedDoc.id,
            // optionally: photoConfiguration etc.
          }}
        />
      )}
    </div>
  );
}
