"use client";

import { useState, useEffect } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectTrigger,
  SelectValue,
  SelectContent,
  SelectItem,
} from "@/components/ui/select";
import { fetchJobForm, submitJobFormData } from "@/services/job-form.service";

interface OptionField {
  label: string;
  value: string;
}

interface FormField {
  name: string;
  label: string;
  type: "text" | "email" | "tel" | "number" | "textarea" | "select";
  required: boolean;
  options?: {
    optionFields: OptionField[];
  };
}

interface ApplyModalProps {
  jobTitle: string;
  open: boolean;
  onClose: () => void;
}

export default function ApplyModal({
  jobTitle,
  open,
  onClose,
}: ApplyModalProps) {
  const [fields, setFields] = useState<FormField[]>([]);
  const [formValues, setFormValues] = useState<Record<string, string>>({});
  const [loading, setLoading] = useState<boolean>(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const normalizedJobTitle = jobTitle.replace(/^Job Title\s*:\s*/i, "").trim();

  useEffect(() => {
    if (!open) return;

    const loadForm = async () => {
      setLoading(true);
      try {
        const response = await fetchJobForm(
          "09a98858-b00d-475c-bb4f-68b953dc1887"
        );

        if (response?.fields) {
          setFields(response.fields);

          const defaults: Record<string, string> = {};
          response.fields.forEach((f: FormField) => {
            if (
              f.label?.toLowerCase().includes("post applying for") &&
              normalizedJobTitle !== ""
            ) {
              defaults[f.name] = normalizedJobTitle;
            } else if (f.type === "select" && f.options?.optionFields?.length) {
              defaults[f.name] = f.options.optionFields[0].value;
            } else {
              defaults[f.name] = "";
            }
          });

          setFormValues(defaults);
        }
      } catch (err) {
        console.error("Failed to load form:", err);
      } finally {
        setLoading(false);
        setErrors({});
      }
    };

    loadForm();
  }, [open, normalizedJobTitle]);

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    setFormValues((prev) => ({ ...prev, [e.target.id]: e.target.value }));
    setErrors((prev) => ({ ...prev, [e.target.id]: "" }));
  };

  const handleSelectChange = (name: string, value: string) => {
    setFormValues((prev) => ({ ...prev, [name]: value }));
    setErrors((prev) => ({ ...prev, [name]: "" }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setErrors({});
    try {
      const phoneField = fields.find((f) => f.type === "tel");
      if (phoneField) {
        const phoneValue = formValues[phoneField.name];
        const phoneRegex = /^[0-9]{10}$/;
        if (!phoneRegex.test(phoneValue)) {
          setErrors({ [phoneField.name]: "Please enter a valid 10-digit phone number." });
          setLoading(false);
          return;
        }
      }

      const res = await submitJobFormData(
        "09a98858-b00d-475c-bb4f-68b953dc1887",
        formValues
      );

      if (res) {
        alert("Application submitted successfully!");

        // Reset form values
        const defaults: Record<string, string> = {};
        fields.forEach((f: FormField) => {
          if (
            f.label?.toLowerCase().includes("post applying for") &&
            normalizedJobTitle !== ""
          ) {
            defaults[f.name] = normalizedJobTitle;
          } else if (f.type === "select" && f.options?.optionFields?.length) {
            defaults[f.name] = f.options.optionFields[0].value;
          } else {
            defaults[f.name] = "";
          }
        });
        setFormValues(defaults);
        setErrors({});
        onClose();
      }
    } catch (err) {
      // console.error(err);
      const isAxiosError = (
  error: unknown
): error is {
  response?: {
    data?: {
      errors?: string[];
    };
  };
} => {
  return (
    typeof error === "object" &&
    error !== null &&
    "response" in error &&
    typeof (error as { response?: unknown }).response === "object"
  );
};

      if (
        isAxiosError(err) &&
        err.response?.data?.errors?.[0]?.includes("Invalid email format")
      ) {
        const emailField = fields.find((f) => f.type === "email");
        if (emailField) {
          setErrors({ [emailField.name]: "Invalid email" });
        }
      } else {
        alert("Submission failed!");
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-lg max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Apply for Job</DialogTitle>
        </DialogHeader>

        {fields.length > 0 && (
          <form onSubmit={handleSubmit} className="grid gap-4">
            {fields.map((field, idx) => {
              const isPostApplyingForField = field.label
                ?.toLowerCase()
                .includes("post applying for");
              const shouldDisable =
                isPostApplyingForField && normalizedJobTitle !== "";

              return (
                <div key={idx} className="space-y-1">
                  <label
                    htmlFor={field.name}
                    className="block text-sm font-medium"
                  >
                    {field.label}{" "}
                    {field.required && <span className="text-red-500">*</span>}
                  </label>

                  {(() => {
                    switch (field.type) {
                      case "select":
                        const matchedOption =
                          field.options?.optionFields?.find(
                            (opt) =>
                              opt.label.trim().toLowerCase() ===
                              normalizedJobTitle.toLowerCase() ||
                              opt.value.trim().toLowerCase() ===
                              normalizedJobTitle.toLowerCase()
                          );

                        return (
                          <Select
                            onValueChange={(val) =>
                              handleSelectChange(field.name, val)
                            }
                            value={
                              shouldDisable
                                ? matchedOption?.value || ""
                                : formValues[field.name] || ""
                            }
                            disabled={shouldDisable}
                          >
                            <SelectTrigger>
                              <SelectValue
                                placeholder={`Select ${field.label}`}
                              />
                            </SelectTrigger>
                            <SelectContent>
                              {field.options?.optionFields?.map((opt, i) => (
                                <SelectItem key={i} value={opt.value}>
                                  {opt.label}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        );

                      case "textarea":
                        return (
                          <Textarea
                            id={field.name}
                            value={
                              shouldDisable
                                ? normalizedJobTitle
                                : formValues[field.name] || ""
                            }
                            onChange={handleChange}
                            required={field.required}
                            disabled={shouldDisable}
                          />
                        );

                      default:
                        return (
                          <Input
                            id={field.name}
                            type={field.type}
                            value={
                              shouldDisable
                                ? normalizedJobTitle
                                : formValues[field.name] || ""
                            }
                            onChange={handleChange}
                            required={field.required}
                            disabled={shouldDisable}
                            className={
                              errors[field.name]
                                ? "border-red-500"
                                : ""
                            }
                          />
                        );
                    }
                  })()}

                  {errors[field.name] && (
                    <p className="text-red-600 text-sm">
                      {errors[field.name]}
                    </p>
                  )}
                </div>
              );
            })}

            <Button
              type="submit"
              className="bg-orange-500 hover:bg-orange-600 text-white"
              disabled={loading}
            >
              {loading ? "Submitting..." : "Submit"}
            </Button>
          </form>
        )}
      </DialogContent>
    </Dialog>
  );
}
