"use client";

import { displayValue } from "@/lib/display-format";
import { useId, useState } from "react";
import { X, Send, Truck } from "lucide-react";
import { Button } from "@/components/ui/button";

// ============================================
// Dispatch Modal
// Required fields before marking order as dispatched:
// courier name, tracking URL, tracking ID
// ============================================

interface DispatchModalProps {
  isOpen: boolean;
  onClose: () => void;
  onConfirm: (data: {
    courierName: string;
    trackingUrl: string;
    trackingId: string;
  }) => void;
  orderNumber: string;
}

export function DispatchModal({
  isOpen,
  onClose,
  onConfirm,
  orderNumber,
}: DispatchModalProps) {
  const [courierName, setCourierName] = useState("");
  const [trackingUrl, setTrackingUrl] = useState("");
  const [trackingId, setTrackingId] = useState("");
  const [errors, setErrors] = useState<Record<string, string>>({});
  const formId = useId();

  if (!isOpen) return null;

  const validate = (): boolean => {
    const newErrors: Record<string, string> = {};
    if (!courierName.trim()) newErrors.courierName = "Courier name is required";
    if (!trackingUrl.trim()) newErrors.trackingUrl = "Tracking URL is required";
    if (!trackingId.trim()) newErrors.trackingId = "Tracking ID is required";
    if (courierName.trim().length > 255) newErrors.courierName = "Courier name must be 255 characters or fewer";
    if (trackingId.trim().length > 255) newErrors.trackingId = "Tracking ID must be 255 characters or fewer";
    if (trackingUrl.trim()) {
      try {
        const url = new URL(trackingUrl.trim());
        if (!/^https?:\/\//i.test(trackingUrl.trim()) || !["http:", "https:"].includes(url.protocol) || !url.hostname || /\s/.test(trackingUrl.trim())) {
          newErrors.trackingUrl = "Enter a valid tracking URL starting with http:// or https://";
        } else if (trackingUrl.trim().length > 2048) {
          newErrors.trackingUrl = "Tracking URL must be 2048 characters or fewer";
        }
      } catch {
        newErrors.trackingUrl = "Enter a valid tracking URL starting with http:// or https://";
      }
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = () => {
    if (validate()) {
      onConfirm({
        courierName: courierName.trim(),
        trackingUrl: trackingUrl.trim(),
        trackingId: trackingId.trim(),
      });
      // Reset form
      setCourierName("");
      setTrackingUrl("");
      setTrackingId("");
      setErrors({});
    }
  };

  const handleClose = () => {
    setCourierName("");
    setTrackingUrl("");
    setTrackingId("");
    setErrors({});
    onClose();
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/50 backdrop-blur-sm"
        onClick={handleClose}
      />

      {/* Modal */}
      <div className="relative z-10 mx-4 w-full max-w-md overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-2xl">
        {/* Header */}
        <div className="flex items-center justify-between border-b border-gray-200 px-6 py-4">
          <div className="flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-purple-50">
              <Truck className="h-5 w-5 text-purple-600" />
            </div>
            <div>
              <h2 className="text-lg font-semibold text-gray-900">
                Mark as Shipped
              </h2>
              <p className="text-xs text-gray-500">
                {orderNumber} — Enter shipping details
              </p>
            </div>
          </div>
          <button
            type="button"
            aria-label="Close dispatch form"
            onClick={handleClose}
            className="rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Form */}
        <form id={formId} noValidate onSubmit={(event) => { event.preventDefault(); handleSubmit(); }} className="space-y-4 px-6 py-5">
          {/* Courier Name */}
          <div className="space-y-1.5">
            <label htmlFor={`${formId}-courier`} className="block text-sm font-medium text-gray-700">
              Courier Name <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              id={`${formId}-courier`}
              required
              maxLength={255}
              aria-invalid={Boolean(errors.courierName)}
              aria-describedby={errors.courierName ? `${formId}-courier-error` : undefined}
              value={courierName}
              onChange={(e) => {
                setCourierName(e.target.value);
                if (errors.courierName) setErrors((prev) => ({ ...prev, courierName: "" }));
              }}
              placeholder="e.g. FedEx, UPS, DHL"
              className={`block w-full rounded-lg border bg-gray-50 px-3 py-2.5 text-sm text-gray-900 shadow-sm transition-colors placeholder:text-gray-400 focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500 ${
                errors.courierName ? "border-red-500" : "border-gray-200"
              }`}
            />
            {errors.courierName && (
              <p id={`${formId}-courier-error`} role="alert" className="text-xs text-red-500">{displayValue(errors.courierName)}</p>
            )}
          </div>

          {/* Tracking ID */}
          <div className="space-y-1.5">
            <label htmlFor={`${formId}-tracking-id`} className="block text-sm font-medium text-gray-700">
              Tracking ID <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              id={`${formId}-tracking-id`}
              required
              maxLength={255}
              aria-invalid={Boolean(errors.trackingId)}
              aria-describedby={errors.trackingId ? `${formId}-tracking-id-error` : undefined}
              value={trackingId}
              onChange={(e) => {
                setTrackingId(e.target.value);
                if (errors.trackingId) setErrors((prev) => ({ ...prev, trackingId: "" }));
              }}
              placeholder="e.g. 1Z999AA10123456784"
              className={`block w-full rounded-lg border bg-gray-50 px-3 py-2.5 text-sm text-gray-900 shadow-sm transition-colors placeholder:text-gray-400 focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500 ${
                errors.trackingId ? "border-red-500" : "border-gray-200"
              }`}
            />
            {errors.trackingId && (
              <p id={`${formId}-tracking-id-error`} role="alert" className="text-xs text-red-500">{displayValue(errors.trackingId)}</p>
            )}
          </div>

          {/* Tracking URL */}
          <div className="space-y-1.5">
            <label htmlFor={`${formId}-tracking-url`} className="block text-sm font-medium text-gray-700">
              Tracking URL <span className="text-red-500">*</span>
            </label>
            <input
              type="url"
              id={`${formId}-tracking-url`}
              required
              maxLength={2048}
              aria-invalid={Boolean(errors.trackingUrl)}
              aria-describedby={errors.trackingUrl ? `${formId}-tracking-url-error` : undefined}
              value={trackingUrl}
              onChange={(e) => {
                setTrackingUrl(e.target.value);
                if (errors.trackingUrl) setErrors((prev) => ({ ...prev, trackingUrl: "" }));
              }}
              placeholder="https://tracking.courier.com/..."
              className={`block w-full rounded-lg border bg-gray-50 px-3 py-2.5 text-sm text-gray-900 shadow-sm transition-colors placeholder:text-gray-400 focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500 ${
                errors.trackingUrl ? "border-red-500" : "border-gray-200"
              }`}
            />
            {errors.trackingUrl && (
              <p id={`${formId}-tracking-url-error`} role="alert" className="text-xs text-red-500">{displayValue(errors.trackingUrl)}</p>
            )}
          </div>
        </form>

        {/* Footer */}
        <div className="flex items-center justify-end gap-3 border-t border-gray-200 px-6 py-4">
          <Button type="button" variant="ghost" onClick={handleClose}>
            Cancel
          </Button>
          <Button type="submit" form={formId} className="gap-1.5">
            <Send className="h-4 w-4" />
            Dispatch Order
          </Button>
        </div>
      </div>
    </div>
  );
}
