"use client";
import { useState, useEffect } from "react";
import { format } from "date-fns";
import { CalendarIcon, ChevronLeft, ChevronRight, Check, Send, X } from "lucide-react";
import { cn } from "@/lib/utils";
import { useTranslations } from "next-intl";
import {
  Dialog,
  DialogContent,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Calendar } from "@/components/ui/calendar";
import { toast } from "sonner";
import { get } from "@/lib/api";
import { submitRequest } from "@/services/requests";

function ReviewField({ label, value }: { label: string; value?: string | null }) {
  return (
    <div>
      <p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">{label}</p>
      <p className="text-sm mt-0.5 break-words">{value || "—"}</p>
    </div>
  );
}

interface Props {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

const RequestManpowerModal = ({ open, onOpenChange }: Props) => {
  const t = useTranslations("manpower");
  const [currentStep, setCurrentStep] = useState(1);

  const steps = [
    { number: 1, label: t("steps.projectDetails") },
    { number: 2, label: t("steps.contactDetails") },
    { number: 3, label: t("steps.confirmation") },
  ];

  // Step fields
  const [projectLocation, setProjectLocation] = useState("");
  const [inspectionType, setInspectionType] = useState("");
  const [equipmentAvailable, setEquipmentAvailable] = useState("no");
  const [equipmentDetails, setEquipmentDetails] = useState("");
  const [numberPersonnel, setNumberPersonnel] = useState<string>("");
  const [startDate, setStartDate] = useState<Date | undefined>(undefined);

  const [companyName, setCompanyName] = useState("");
  const [contactPerson, setContactPerson] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");

  const [jobNotes, setJobNotes] = useState("");
  const [jobDuration, setJobDuration] = useState("");
  const [certificationRequired, setCertificationRequired] = useState("");

  const [serviceOptions, setServiceOptions] = useState<any[]>([]);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [isSubmitting, setIsSubmitting] = useState(false);

  useEffect(() => {
    get<{ data: { id: number; heading: string }[] }>("/api/service-sub-services/list")
      .then((res) => setServiceOptions(res.data))
      .catch(() => {});
  }, []);

  const updateField = (key: string, value: any) => {
    if (errors[key]) {
      setErrors((prev) => {
        const next = { ...prev };
        delete next[key];
        return next;
      });
    }
  };

  const validateStep = (step: number) => {
    const newErrors: Record<string, string> = {};
    if (step === 1) {
      if (!projectLocation.trim()) newErrors.projectLocation = t("validation.required");
      if (!inspectionType.trim()) newErrors.inspectionType = t("validation.required");
    }
    if (step === 2) {
      if (!companyName.trim()) newErrors.companyName = t("validation.required");
      if (!contactPerson.trim()) newErrors.contactPerson = t("validation.required");
      if (!email.trim()) newErrors.email = t("validation.required");
      else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) newErrors.email = t("validation.invalidEmail");
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleNext = () => {
    if (validateStep(currentStep)) setCurrentStep((s) => Math.min(s + 1, 3));
  };

  const handleBack = () => setCurrentStep((s) => Math.max(s - 1, 1));

  const handleSubmit = async () => {
    if (!validateStep(3)) return;
    setIsSubmitting(true);
    try {
      const res = await submitRequest({
        company_name: companyName.trim(),
        contact_person: contactPerson.trim(),
        email: email.trim(),
        phone: phone || undefined,
        location: projectLocation.trim(),
        inspection_type_id: serviceOptions.find((s: any) => s.heading === inspectionType)?.id ?? inspectionType,
        equipment_available: equipmentAvailable === "yes",
        equipment_details: equipmentDetails || null,
        number_of_personnel: numberPersonnel ? Number(numberPersonnel) : null,
        certification_required: certificationRequired.trim() ? certificationRequired.split(",").map((c) => c.trim()).filter(Boolean) : null,
        job_duration: jobDuration || null,
        start_date: startDate ? format(startDate, "yyyy-MM-dd") : null,
        additional_notes: jobNotes || null,
      });

      const trackUrl = `/requests/track/${res.tracking_token}`;
      toast.success(t("successToast"));
      try {
        await navigator.clipboard.writeText(window.location.origin + trackUrl);
      } catch {}
      // reset
      setCurrentStep(1);
      setProjectLocation("");
      setInspectionType("");
      setEquipmentAvailable("no");
      setEquipmentDetails("");
      setNumberPersonnel("");
      setStartDate(undefined);
      setCompanyName("");
      setContactPerson("");
      setEmail("");
      setPhone("");
      setJobNotes("");
      setJobDuration("");
      setCertificationRequired("");
      onOpenChange(false);
    } catch (err) {
      // handled by API interceptor
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleClose = (isOpen: boolean) => {
    if (!isOpen) {
      setCurrentStep(1);
      setErrors({});
    }
    onOpenChange(isOpen);
  };

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="w-[768px] sm:max-w-none p-0 gap-0 overflow-hidden rounded-sm border-none" showCloseButton={false}>
        <DialogTitle className="sr-only">{t("title")}</DialogTitle>
        <DialogDescription className="sr-only">{t("subtitle")}</DialogDescription>

        <div className="bg-primary px-6 pt-6 pb-5 relative">
          <button
            onClick={() => handleClose(false)}
            className="absolute top-3 right-4 text-primary-foreground/70 hover:text-primary-foreground transition-colors"
            aria-label="Close"
          >
            <X className="w-5 h-5" />
          </button>
          <h2 className="text-primary-foreground font-bold text-lg mb-4">{t("title")}</h2>
          <div className="flex items-center gap-2">
            {steps.map((step, i) => (
              <div key={step.number} className="flex items-center flex-1">
                <div className="flex items-center gap-2 flex-1">
                  <div
                    className={cn(
                      "w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold shrink-0 transition-all duration-300",
                      currentStep > step.number
                        ? "bg-accent text-accent-foreground"
                        : currentStep === step.number
                        ? "bg-accent text-accent-foreground"
                        : "bg-primary-foreground/20 text-primary-foreground/50"
                    )}
                  >
                    {currentStep > step.number ? <Check className="w-3.5 h-3.5" /> : step.number}
                  </div>
                  <span
                    className={cn(
                      "text-xs font-medium hidden sm:block transition-colors",
                      currentStep >= step.number ? "text-primary-foreground" : "text-primary-foreground/40"
                    )}
                  >
                    {step.label}
                  </span>
                </div>
                {i < steps.length - 1 && (
                  <div
                    className={cn(
                      "h-[2px] flex-1 mx-2 rounded transition-colors duration-300",
                      currentStep > step.number ? "bg-accent" : "bg-primary-foreground/20"
                    )}
                  />
                )}
              </div>
            ))}
          </div>
        </div>

        <div className="max-h-[60vh] overflow-y-auto px-6 py-5">
          {currentStep === 1 && (
            <div className="space-y-4">
              <div>
                <Label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">{t("fields.projectLocation")} <span className="text-destructive">*</span></Label>
                <Input placeholder={t("fields.projectLocationPlaceholder")} value={projectLocation} onChange={(e) => { setProjectLocation(e.target.value); updateField('projectLocation', e.target.value); }} className={errors.projectLocation ? 'border-destructive mt-1.5' : 'mt-1.5'} />
                {errors.projectLocation && <p className="text-destructive text-xs mt-1">{errors.projectLocation}</p>}
              </div>

              <div>
                <Label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">{t("fields.inspectionType")} <span className="text-destructive">*</span></Label>
                <Select value={inspectionType} onValueChange={(v) => { setInspectionType(v ?? ""); updateField('inspectionType', v ?? ""); }}>
                  <SelectTrigger className="mt-1.5 w-full"><SelectValue placeholder={t("fields.inspectionTypePlaceholder")} /></SelectTrigger>
                  <SelectContent alignItemWithTrigger={false}>
                    {serviceOptions.map((s: any) => (<SelectItem key={s.id} value={s.heading}>{s.heading}</SelectItem>))}
                  </SelectContent>
                </Select>
                {errors.inspectionType && <p className="text-destructive text-xs mt-1">{errors.inspectionType}</p>}
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <Label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">{t("fields.equipmentAvailable")}</Label>
                  <Select value={equipmentAvailable} onValueChange={(v) => setEquipmentAvailable(v ?? "no")}>
                    <SelectTrigger className="mt-1.5 w-full"><SelectValue /></SelectTrigger>
                    <SelectContent alignItemWithTrigger={false}>
                      <SelectItem value="yes">{t("options.yes")}</SelectItem>
                      <SelectItem value="no">{t("options.no")}</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">{t("fields.numberOfPersonnel")}</Label>
                  <Input type="number" min={1} value={numberPersonnel} onChange={(e) => setNumberPersonnel(e.target.value)} className="mt-1.5" />
                </div>
              </div>

              <div>
                <Label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">{t("fields.startDate")}</Label>
                <Popover>
                  <PopoverTrigger
                    render={
                      <Button
                        variant="outline"
                        className={cn(
                          "w-full mt-1.5 justify-start text-left font-normal",
                          !startDate && "text-muted-foreground"
                        )}
                      >
                        <CalendarIcon className="mr-2 h-4 w-4" />
                        {startDate ? format(startDate, "PPP") : t("fields.startDatePlaceholder")}
                      </Button>
                    }
                  />
                  <PopoverContent className="w-auto p-0" align="start">
                    <Calendar mode="single" selected={startDate} onSelect={(d) => setStartDate(d ?? undefined)} disabled={(d) => d < new Date()} initialFocus className="p-3 pointer-events-auto" />
                  </PopoverContent>
                </Popover>
              </div>

              <div>
                <Label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">{t("fields.certificationsRequired")}</Label>
                <Input
                  value={certificationRequired}
                  onChange={(e) => setCertificationRequired(e.target.value)}
                  placeholder={t("fields.certificationsPlaceholder")}
                  className="mt-1.5"
                />
                <p className="text-xs text-muted-foreground mt-1">{t("fields.certificationsHint")}</p>
              </div>

              <div>
                <Label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">{t("fields.equipmentDetails")}</Label>
                <Textarea value={equipmentDetails} onChange={(e) => setEquipmentDetails(e.target.value)} className="mt-1.5 min-h-[80px]" />
              </div>
            </div>
          )}

          {currentStep === 2 && (
            <div className="space-y-4">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <Label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">{t("fields.companyName")} <span className="text-destructive">*</span></Label>
                  <Input value={companyName} onChange={(e) => { setCompanyName(e.target.value); updateField('companyName', e.target.value); }} className={errors.companyName ? 'border-destructive mt-1.5' : 'mt-1.5'} />
                  {errors.companyName && <p className="text-destructive text-xs mt-1">{errors.companyName}</p>}
                </div>
                <div>
                  <Label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">{t("fields.contactPerson")} <span className="text-destructive">*</span></Label>
                  <Input value={contactPerson} onChange={(e) => { setContactPerson(e.target.value); updateField('contactPerson', e.target.value); }} className={errors.contactPerson ? 'border-destructive mt-1.5' : 'mt-1.5'} />
                  {errors.contactPerson && <p className="text-destructive text-xs mt-1">{errors.contactPerson}</p>}
                </div>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <Label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">{t("fields.email")} <span className="text-destructive">*</span></Label>
                  <Input type="email" value={email} onChange={(e) => { setEmail(e.target.value); updateField('email', e.target.value); }} className={errors.email ? 'border-destructive mt-1.5' : 'mt-1.5'} />
                  {errors.email && <p className="text-destructive text-xs mt-1">{errors.email}</p>}
                </div>
                <div>
                  <Label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">{t("fields.phone")}</Label>
                  <Input value={phone} onChange={(e) => setPhone(e.target.value)} className="mt-1.5" />
                </div>
              </div>

              <div>
                <Label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">{t("fields.jobDuration")}</Label>
                <Input placeholder={t("fields.jobDurationPlaceholder")} value={jobDuration} onChange={(e) => setJobDuration(e.target.value)} className="mt-1.5" />
              </div>

              <div>
                <Label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">{t("fields.additionalNotes")}</Label>
                <Textarea value={jobNotes} onChange={(e) => setJobNotes(e.target.value)} className="mt-1.5 min-h-[80px]" />
              </div>
            </div>
          )}

          {currentStep === 3 && (
            <div className="space-y-4">
              <div>
                <h3 className="font-semibold">{t("review.heading")}</h3>
                <p className="text-sm text-muted-foreground mt-2">{t("review.description")}</p>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-3">
                <ReviewField label={t("review.location")} value={projectLocation} />
                <ReviewField label={t("review.inspectionType")} value={inspectionType} />
                <ReviewField label={t("review.startDate")} value={startDate ? format(startDate, 'PPP') : null} />
                <ReviewField label={t("review.numberOfPersonnel")} value={numberPersonnel} />
                <ReviewField label={t("review.equipmentAvailable")} value={equipmentAvailable === 'yes' ? t("options.yes") : t("options.no")} />
                <ReviewField label={t("review.jobDuration")} value={jobDuration} />
                <ReviewField label={t("review.companyName")} value={companyName} />
                <ReviewField label={t("review.contactPerson")} value={contactPerson} />
                <ReviewField label={t("review.email")} value={email} />
                <ReviewField label={t("review.phone")} value={phone} />
              </div>
              {certificationRequired && (
                <ReviewField label={t("review.certificationsRequired")} value={certificationRequired} />
              )}
              {equipmentDetails && (
                <ReviewField label={t("review.equipmentDetails")} value={equipmentDetails} />
              )}
              {jobNotes && (
                <ReviewField label={t("review.additionalNotes")} value={jobNotes} />
              )}
            </div>
          )}
        </div>

        <div className="px-6 py-4 border-t border-border flex items-center justify-between bg-muted/30">
          <Button variant="ghost" onClick={handleBack} disabled={currentStep === 1} className="gap-1">
            <ChevronLeft className="w-4 h-4" /> {t("navigation.back")}
          </Button>

          <div className="flex items-center gap-2">
            <span className="text-xs text-muted-foreground">{t("navigation.stepOf", { current: currentStep, total: 3 })}</span>
            {currentStep < 3 ? (
              <Button onClick={handleNext} className="gap-1 bg-accent text-accent-foreground hover:bg-accent/90">{t("navigation.next")} <ChevronRight className="w-4 h-4" /></Button>
            ) : (
              <Button onClick={handleSubmit} disabled={isSubmitting} className="gap-1 bg-accent text-accent-foreground hover:bg-accent/90">{isSubmitting ? t("navigation.submitting") : (<><span>{t("navigation.submitRequest")}</span><Send className="w-4 h-4" /></>)}</Button>
            )}
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default RequestManpowerModal;
