"use client";

import { useState, use, useEffect } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { motion, AnimatePresence } from "framer-motion";
import {
  ChevronRight,
  ChevronLeft,
  Upload,
  CheckCircle2,
  Briefcase,
  FileText,
  User,
  MessageSquare,
  Save,
  ArrowLeft,
  Loader2,
} from "lucide-react";

import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { Progress } from "@/components/ui/progress";
import { Separator } from "@/components/ui/separator";
import { Navbar } from "@/components/navbar";
import { Footer } from "@/components/footer";
import { useNotify } from "@/contexts/notification-context";
import { jobsApi, applicationsApi, storageApi, type ApiJob } from "@/lib/api";
import { formatPhone } from "@/lib/utils";
import { useTranslation } from "@/lib/i18n";
import { getCurrentUser } from "@/lib/auth";





export const runtime = 'edge';

export default function JobApplicationPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { t } = useTranslation();

  const steps = [
    { id: 1, title: t("application.steps.personal"), icon: User },
    { id: 2, title: t("application.steps.documents"), icon: FileText },
    { id: 3, title: t("application.steps.experience"), icon: Briefcase },
    { id: 4, title: t("application.steps.additional"), icon: MessageSquare },
  ];

  const { id } = use(params);
  const router = useRouter();
  const notify = useNotify();
  const [currentStep, setCurrentStep] = useState(1);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const [job, setJob] = useState<ApiJob | null>(null);
  const [loading, setLoading] = useState(true);

  // Form state
  const [formData, setFormData] = useState({
    // Step 1
    fullName: "",
    email: "",
    phone: "",
    linkedin: "",
    privacyAccepted: false,

    // Step 2
    resumeUrl: "",
    resumeName: "",
    coverLetter: "",
    portfolioUrl: "",
    // Step 3
    salaryExpectation: "",
    hasExperience: "",
    // Step 4
    whyUs: "",
    availability: [] as string[],
  });

  const handleInputChange = (field: string, value: any) => {
    if (field === "phone") {
      value = formatPhone(value);
    }
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  const handleResumeUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (file.size > 5 * 1024 * 1024) {
      notify.error(t("application.toasts.fileTooLarge.title"), t("application.toasts.fileTooLarge.desc"));
      return;
    }

    try {
      setIsUploading(true);
      const { publicUrl } = await storageApi.uploadFile(file, "resumes");
      setFormData(prev => ({
        ...prev,
        resumeUrl: publicUrl,
        resumeName: file.name
      }));
      notify.success(t("application.toasts.uploadComplete.title"), t("application.toasts.uploadComplete.desc"));
    } catch (error) {
      console.error("Upload error:", error);
      notify.error(t("application.toasts.uploadFailed.title"), t("application.toasts.uploadFailed.desc"));
    } finally {
      setIsUploading(false);
    }
  };

  const validateStep = (step: number) => {
    switch (step) {
      case 1:
        if (!formData.fullName || !formData.email || !formData.phone) {
          notify.error(t("application.toasts.requiredFields.title"), t("application.toasts.requiredFields.desc"));
          return false;
        }
        if (!formData.email.includes("@")) {
          notify.error(t("application.toasts.invalidEmail.title"), t("application.toasts.invalidEmail.desc"));
          return false;
        }
        if (formData.phone.length < 14) { // (11) 91234-5678 is 15 chars, (11) 1234-5678 is 14 chars
          notify.error(t("application.toasts.invalidPhone.title"), t("application.toasts.invalidPhone.desc"));
          return false;
        }
        if (!formData.privacyAccepted) {
          notify.error(t("application.toasts.privacyPolicy.title"), t("application.toasts.privacyPolicy.desc"));
          return false;
        }
        return true;
      case 2:
        if (!formData.resumeUrl) {
          notify.error(t("application.toasts.resumeRequired.title"), t("application.toasts.resumeRequired.desc"));
          return false;
        }
        return true;
      case 3:
        if (!formData.salaryExpectation || !formData.hasExperience) {
          notify.error(
            t("application.toasts.questionsRequired.title"),
            t("application.toasts.questionsRequired.desc")
          );
          return false;
        }
        return true;
      case 4:
        if (!formData.whyUs || formData.availability.length === 0) {
          notify.error(
            t("application.toasts.reasonRequired.title"),
            t("application.toasts.reasonRequired.desc")
          );
          return false;
        }
        return true;
      default:
        return true;
    }
  };

  const handleNext = () => {
    if (validateStep(currentStep)) {
      if (currentStep < steps.length) {
        setCurrentStep((prev) => prev + 1);
        window.scrollTo(0, 0);
      } else {
        handleSubmit();
      }
    }
  };

  const handleBack = () => {
    if (currentStep > 1) {
      setCurrentStep((prev) => prev - 1);
      window.scrollTo(0, 0);
    }
  };

  useEffect(() => {
    async function fetchJob() {
      try {
        setLoading(true);
        const response = await jobsApi.getById(id);
        if (response) {
          setJob(response);
        }
      } catch (err) {
        console.error("Error fetching job:", err);
        notify.error(t("application.toasts.loadError.title"), t("application.toasts.loadError.desc"));
      } finally {
        setLoading(false);
      }
    }
    fetchJob();
  }, [id, notify]);

  // Auto-fill for logged in users
  useEffect(() => {
    const user = getCurrentUser();
    if (user) {
      setFormData(prev => ({
        ...prev,
        fullName: user.name || prev.fullName,
        email: user.email || prev.email,
      }));
    }
  }, []);

  const handleSubmit = async () => {
    setIsSubmitting(true);
    try {
      await applicationsApi.create({
        jobId: id,
        name: formData.fullName,
        email: formData.email,
        phone: formData.phone,
        linkedin: formData.linkedin,
        resumeUrl: formData.resumeUrl,
        coverLetter: formData.coverLetter || undefined,
        portfolioUrl: formData.portfolioUrl || undefined,
        message: formData.whyUs, // Mapping Why Us to Message/Notes
        documents: {}, // TODO: Extra docs
        // salaryExpectation: formData.salaryExpectation, // These fields might need to go into Notes or structured JSON if backend doesn't support them specifically?
        // hasExperience: formData.hasExperience,
        // Backend seems to map "documents" as JSONMap. We can put extra info there?
        // Or put in "message" concatenated.
        // Let's assume the backend 'message' field is good for "whyUs"
      });

      notify.success(
        t("application.toasts.submitted.title"),
        t("application.toasts.submitted.desc", { jobTitle: job?.title || 'this position' })
      );

      setIsSubmitted(true);
      window.scrollTo(0, 0);
    } catch (error: any) {
      console.error("Submit error:", error);
      notify.error(
        t("application.toasts.submitError.title"),
        error.message || t("application.toasts.submitError.default")
      );
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleSaveDraft = () => {
    notify.info(
      t("application.toasts.draftSaved.title"),
      t("application.toasts.draftSaved.desc")
    );
  };

  const progress = (currentStep / steps.length) * 100;

  if (!job) return null;

  if (isSubmitted) {
    const user = getCurrentUser();

    return (
      <div className="min-h-screen flex flex-col bg-muted/30">
        <Navbar />
        <main className="flex-1 py-12 sm:py-24">
          <div className="container mx-auto px-4 max-w-lg">
            <Card className="border-t-4 border-t-green-500 shadow-lg">
              <CardContent className="pt-10 pb-8 text-center space-y-6">
                <div className="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto text-green-600 mb-6">
                  <CheckCircle2 className="h-10 w-10" />
                </div>

                <div className="space-y-2">
                  <h2 className="text-2xl font-bold">{t("application.success.title")}</h2>
                  <p className="text-muted-foreground">
                    {t("application.success.message")} <span className="font-semibold text-foreground">{job.title}</span>.
                  </p>
                </div>

                <div className="py-4">
                  {user ? (
                    <div className="bg-primary/5 p-4 rounded-lg border border-primary/20 text-left">
                      <h3 className="font-semibold text-primary mb-1 flex items-center">
                        <Briefcase className="w-4 h-4 mr-2" />
                        {t("candidate.dashboard.applications.title")}
                      </h3>
                      <p className="text-sm text-muted-foreground mb-3">
                        Acompanhe o status desta e de outras candidaturas no seu painel.
                      </p>
                      <Button className="w-full" asChild>
                        <Link href="/dashboard/my-applications">
                          Ver Minhas Candidaturas
                        </Link>
                      </Button>
                    </div>
                  ) : (
                    <div className="bg-primary/5 p-4 rounded-lg border border-primary/20 text-left">
                      <h3 className="font-semibold text-primary mb-1 flex items-center">
                        <User className="w-4 h-4 mr-2" />
                        {t("application.success.ctaTitle")}
                      </h3>
                      <p className="text-sm text-muted-foreground mb-3">
                        {t("application.success.ctaDesc")}
                      </p>
                      <Button className="w-full" asChild>
                        <Link
                          href={`/register/candidate?email=${encodeURIComponent(formData.email)}&name=${encodeURIComponent(formData.fullName)}&phone=${encodeURIComponent(formData.phone)}`}
                        >
                          {t("application.success.ctaButton")}
                        </Link>
                      </Button>
                    </div>
                  )}
                </div>

                <div className="flex flex-col gap-3">
                  <Button variant="outline" asChild>
                    <Link href="/jobs">
                      {t("application.success.backJobs")}
                    </Link>
                  </Button>
                </div>
              </CardContent>
            </Card>
          </div>
        </main>
        <Footer />
      </div>
    );
  }

  return (
    <div className="min-h-screen flex flex-col bg-muted/30">
      <Navbar />

      <main className="flex-1 py-4 sm:py-8">
        <div className="container mx-auto px-4 sm:px-6 lg:px-8 max-w-4xl">
          {/* Header */}
          <div className="mb-4 sm:mb-8">
            <Link
              href={`/jobs/${id}`}
              className="inline-flex items-center text-sm text-muted-foreground hover:text-primary mb-4 transition-colors"
            >
              <ArrowLeft className="mr-2 h-4 w-4" />
              {t("application.back")}
            </Link>
            <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
              <div>
                <h1 className="text-2xl md:text-3xl font-bold text-foreground">
                  {t("application.title", { jobTitle: job.title })}
                </h1>
                <p className="text-muted-foreground mt-1">
                  {job.companyName || 'Company'} • {job.location || 'Remote'}
                </p>
              </div>
              <div className="text-sm font-medium bg-primary/10 text-primary px-3 py-1 rounded-full self-start md:self-center">
                {t("application.estimatedTime")}
              </div>
            </div>
          </div>

          {/* Step progress */}
          <div className="mb-4 sm:mb-8">
            <div className="flex justify-between mb-2">
              <span className="text-sm font-medium text-muted-foreground">
                {t("application.progress.step", { current: currentStep, total: steps.length })}{" "}
                <span className="text-foreground">
                  {steps[currentStep - 1].title}
                </span>
              </span>
              <span className="text-sm font-medium text-primary">
                {Math.round(progress)}%
              </span>
            </div>
            <Progress value={progress} className="h-2" />

            {/* Step indicator - Mobile */}
            <div className="flex md:hidden justify-between mt-3 gap-1">
              {steps.map((step) => {
                const isActive = step.id === currentStep;
                const isCompleted = step.id < currentStep;
                return (
                  <div
                    key={step.id}
                    className={`flex-1 h-1.5 rounded-full transition-colors ${isCompleted
                      ? "bg-primary"
                      : isActive
                        ? "bg-primary/60"
                        : "bg-muted"
                      }`}
                  />
                );
              })}
            </div>

            {/* Step indicator (desktop) */}
            <div className="hidden md:flex justify-between mt-4 px-2">
              {steps.map((step) => {
                const Icon = step.icon;
                const isActive = step.id === currentStep;
                const isCompleted = step.id < currentStep;

                return (
                  <div
                    key={step.id}
                    className={`flex flex-col items-center gap-2 ${isActive
                      ? "text-primary"
                      : isCompleted
                        ? "text-primary/60"
                        : "text-muted-foreground"
                      }`}
                  >
                    <div
                      className={`
                      w-8 h-8 rounded-full flex items-center justify-center border-2 transition-colors
                      ${isActive
                          ? "border-primary bg-primary text-primary-foreground"
                          : isCompleted
                            ? "border-primary bg-primary/10 text-primary"
                            : "border-muted-foreground/30 bg-background"
                        }
                    `}
                    >
                      {isCompleted ? (
                        <CheckCircle2 className="h-5 w-5" />
                      ) : (
                        <Icon className="h-4 w-4" />
                      )}
                    </div>
                    <span className="text-xs font-medium">{step.title}</span>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Form content */}
          <div className="grid gap-6">
            <AnimatePresence mode="wait">
              <motion.div
                key={currentStep}
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -20 }}
                transition={{ duration: 0.3 }}
              >
                <Card className="border-t-4 border-t-primary">
                  <CardHeader>
                    <CardTitle>{steps[currentStep - 1].title}</CardTitle>
                    <CardDescription>
                      {t("application.form.description")}
                    </CardDescription>
                  </CardHeader>

                  <CardContent className="space-y-6">
                    {/* Step 1: Personal Details */}
                    {currentStep === 1 && (
                      <div className="space-y-4">
                        <div className="grid md:grid-cols-2 gap-4">
                          <div className="space-y-2">
                            <Label htmlFor="fullName">{t("application.form.fullName")}</Label>
                            <Input
                              id="fullName"
                              placeholder={t("application.form.placeholders.fullName")}
                              value={formData.fullName}
                              onChange={(e) =>
                                handleInputChange("fullName", e.target.value)
                              }
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="email">{t("application.form.email")}</Label>
                            <Input
                              id="email"
                              type="email"
                              placeholder={t("application.form.placeholders.email")}
                              value={formData.email}
                              onChange={(e) =>
                                handleInputChange("email", e.target.value)
                              }
                            />
                          </div>
                        </div>

                        <div className="grid md:grid-cols-2 gap-4">
                          <div className="space-y-2">
                            <Label htmlFor="phone">{t("application.form.phone")}</Label>
                            <Input
                              id="phone"
                              placeholder={t("application.form.placeholders.phone")}
                              value={formData.phone}
                              onChange={(e) =>
                                handleInputChange("phone", e.target.value)
                              }
                            />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="linkedin">{t("application.form.linkedin")}</Label>
                            <Input
                              id="linkedin"
                              placeholder={t("application.form.placeholders.linkedin")}
                              value={formData.linkedin}
                              onChange={(e) =>
                                handleInputChange("linkedin", e.target.value)
                              }
                            />
                          </div>
                        </div>

                        <div className="flex items-center space-x-2 pt-4">
                          <Checkbox
                            id="privacy"
                            checked={formData.privacyAccepted}
                            onCheckedChange={(checked) =>
                              handleInputChange("privacyAccepted", checked)
                            }
                          />
                          <Label
                            htmlFor="privacy"
                            className="text-sm font-normal text-muted-foreground"
                          >
                            {t("application.form.privacy.agree")}{" "}
                            <Link href="/privacy" className="text-primary underline">
                              {t("application.form.privacy.policy")}
                            </Link>{" "}
                            {t("application.form.privacy.authorize")}
                          </Label>
                        </div>
                      </div>
                    )}

                    {/* Step 2: Documents */}
                    {currentStep === 2 && (
                      <div className="space-y-6">
                        <div className="space-y-3">
                          <Label>{t("application.form.resume")}</Label>
                          <div className="border-2 border-dashed border-muted-foreground/25 rounded-lg p-8 text-center hover:bg-muted/50 transition-colors relative">
                            <input
                              type="file"
                              accept=".pdf,.doc,.docx,.txt"
                              className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                              onChange={handleResumeUpload}
                              disabled={isUploading}
                            />
                            <div className="flex flex-col items-center gap-2">
                              <div className="p-3 bg-primary/10 rounded-full text-primary">
                                {isUploading ? <Loader2 className="h-6 w-6 animate-spin" /> : <Upload className="h-6 w-6" />}
                              </div>
                              <div className="space-y-1">
                                <p className="text-sm font-medium">
                                  {formData.resumeName || t("application.form.upload.click")}
                                </p>
                                <p className="text-xs text-muted-foreground">
                                  {formData.resumeName ? t("application.form.upload.change") : t("application.form.upload.formats")}
                                </p>
                              </div>
                            </div>
                          </div>
                        </div>

                        <div className="space-y-2">
                          <Label htmlFor="portfolio">
                            {t("application.form.portfolio")}
                          </Label>
                          <Input
                            id="portfolio"
                            placeholder={t("application.form.placeholders.portfolio")}
                            value={formData.portfolioUrl}
                            onChange={(e) =>
                              handleInputChange("portfolioUrl", e.target.value)
                            }
                          />
                        </div>

                        <div className="space-y-2">
                          <Label htmlFor="coverLetter">
                            {t("application.form.coverLetter")}
                          </Label>
                          <Textarea
                            id="coverLetter"
                            placeholder={t("application.form.placeholders.whyUs")}
                            className="min-h-[150px]"
                            value={formData.coverLetter}
                            onChange={(e) =>
                              handleInputChange("coverLetter", e.target.value)
                            }
                          />
                        </div>
                      </div>
                    )}

                    {/* Step 3: Experience */}
                    {currentStep === 3 && (
                      <div className="space-y-6">
                        <div className="space-y-2">
                          <Label htmlFor="salary">{t("application.form.salary")}</Label>
                          <Select
                            value={formData.salaryExpectation}
                            onValueChange={(val) =>
                              handleInputChange("salaryExpectation", val)
                            }
                          >
                            <SelectTrigger>
                              <SelectValue placeholder={t("application.form.placeholders.select")} />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="up-to-3k">
                                {t("application.form.salaryRanges.upTo3k")}
                              </SelectItem>
                              <SelectItem value="3k-5k">
                                {t("application.form.salaryRanges.3k-5k")}
                              </SelectItem>
                              <SelectItem value="5k-8k">
                                {t("application.form.salaryRanges.5k-8k")}
                              </SelectItem>
                              <SelectItem value="8k-12k">
                                {t("application.form.salaryRanges.8k-12k")}
                              </SelectItem>
                              <SelectItem value="12k-plus">
                                {t("application.form.salaryRanges.12k-plus")}
                              </SelectItem>
                            </SelectContent>
                          </Select>
                        </div>

                        <div className="space-y-3">
                          <Label>
                            {t("application.form.hasExperience")}
                          </Label>
                          <div className="flex gap-4">
                            <div className="flex items-center space-x-2 border p-3 rounded-md flex-1 hover:bg-muted/50 cursor-pointer">
                              <input
                                type="radio"
                                name="experience"
                                id="exp-yes"
                                className="accent-primary h-4 w-4"
                                checked={formData.hasExperience === "yes"}
                                onChange={() =>
                                  handleInputChange("hasExperience", "yes")
                                }
                              />
                              <Label
                                htmlFor="exp-yes"
                                className="cursor-pointer flex-1"
                              >
                                {t("application.form.experience.yes")}
                              </Label>
                            </div>
                            <div className="flex items-center space-x-2 border p-3 rounded-md flex-1 hover:bg-muted/50 cursor-pointer">
                              <input
                                type="radio"
                                name="experience"
                                id="exp-no"
                                className="accent-primary h-4 w-4"
                                checked={formData.hasExperience === "no"}
                                onChange={() =>
                                  handleInputChange("hasExperience", "no")
                                }
                              />
                              <Label
                                htmlFor="exp-no"
                                className="cursor-pointer flex-1"
                              >
                                {t("application.form.experience.no")}
                              </Label>
                            </div>
                          </div>
                        </div>
                      </div>
                    )}

                    {/* Step 4: Additional */}
                    {currentStep === 4 && (
                      <div className="space-y-6">
                        <div className="space-y-2">
                          <Label htmlFor="whyUs">
                            {t("application.form.whyUs", { company: job.companyName || 'this company' })}
                          </Label>
                          <Textarea
                            id="whyUs"
                            placeholder={t("application.form.placeholders.whyUs")}
                            className="min-h-[150px]"
                            maxLength={1000}
                            value={formData.whyUs}
                            onChange={(e) =>
                              handleInputChange("whyUs", e.target.value)
                            }
                          />
                          <div className="text-xs text-right text-muted-foreground">
                            {formData.whyUs.length}/1000 characters
                          </div>
                        </div>

                        <div className="space-y-3">
                          <Label>{t("application.form.availability")}</Label>
                          <div className="grid gap-2">
                            {[
                              "onsite",
                              "remote",
                              "travel",
                              "immediate",
                            ].map((item) => (
                              <div
                                key={item}
                                className="flex items-center space-x-2"
                              >
                                <Checkbox
                                  id={`avail-${item}`}
                                  checked={formData.availability.includes(item)}
                                  onCheckedChange={(checked) => {
                                    if (checked) {
                                      handleInputChange("availability", [
                                        ...formData.availability,
                                        item,
                                      ]);
                                    } else {
                                      handleInputChange(
                                        "availability",
                                        formData.availability.filter(
                                          (i) => i !== item
                                        )
                                      );
                                    }
                                  }}
                                />
                                <Label htmlFor={`avail-${item}`}>{t(`application.form.availabilityOptions.${item}`)}</Label>
                              </div>
                            ))}
                          </div>
                        </div>
                      </div>
                    )}
                  </CardContent>

                  <CardFooter className="flex flex-col sm:flex-row gap-3 sm:justify-between border-t pt-4 sm:pt-6">
                    <Button
                      variant="outline"
                      onClick={handleBack}
                      disabled={currentStep === 1 || isSubmitting}
                      className="w-full sm:w-auto order-2 sm:order-1"
                    >
                      <ChevronLeft className="mr-2 h-4 w-4" />
                      {t("application.buttons.back")}
                    </Button>

                    <div className="flex gap-2 w-full sm:w-auto order-1 sm:order-2">
                      <Button
                        variant="ghost"
                        onClick={handleSaveDraft}
                        disabled={isSubmitting}
                        className="hidden sm:flex"
                      >
                        <Save className="mr-2 h-4 w-4" />
                        {t("application.buttons.draft")}
                      </Button>

                      <Button
                        onClick={handleNext}
                        disabled={isSubmitting}
                        className="flex-1 sm:flex-none sm:min-w-[120px]"
                      >
                        {isSubmitting ? (
                          t("application.buttons.submitting")
                        ) : currentStep === steps.length ? (
                          <>
                            {t("application.buttons.submit")}{" "}
                            <CheckCircle2 className="ml-2 h-4 w-4" />
                          </>
                        ) : (
                          <>
                            {t("application.buttons.next")}{" "}
                            <ChevronRight className="ml-2 h-4 w-4" />
                          </>
                        )}
                      </Button>
                    </div>
                  </CardFooter>
                </Card>
              </motion.div>
            </AnimatePresence>
          </div>
        </div>
      </main>

      <Footer />
    </div>
  );
}
