import React, { useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { CancelRequestSchema } from "@/zod/order.validation";

interface ClientCancelConfirmDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  submitting: boolean;
  onConfirm: (reason: string) => void;
}

export function ClientCancelConfirmDialog({
  open,
  onOpenChange,
  submitting,
  onConfirm,
}: ClientCancelConfirmDialogProps) {
  const reasonRef = useRef<HTMLTextAreaElement>(null);
  const [error, setError] = useState<string | undefined>(undefined);

  if (!open) return null;

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setError(undefined);

    const reasonVal = reasonRef.current?.value || "";
    const result = CancelRequestSchema.safeParse({ reason: reasonVal });
    if (!result.success) {
      const fieldErrors = result.error.flatten().fieldErrors;
      setError(fieldErrors.reason?.[0]);
      return;
    }

    onConfirm(result.data.reason);
  };

  return (
    <div className="fixed inset-0 bg-black/70 z-[60] flex items-center justify-center p-4">
      <div className="bg-white border border-zinc-200 rounded-2xl w-full max-w-md shadow-2xl p-6 space-y-4 relative">
        <h3 className="text-lg font-bold text-red-655 tracking-tight">
          Request Order Cancellation
        </h3>

        <div className="bg-red-50 border border-red-200 text-red-800 rounded-xl p-3.5 text-xs font-semibold leading-relaxed">
          Warning: Cancellation requests are permanent. Once approved by the administrator, items are returned to stock and the order status is updated to cancelled.
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-1.5">
            <label className="text-[10px] font-bold text-zinc-500 uppercase tracking-wider">
              Reason for Cancellation
            </label>
            <textarea
              ref={reasonRef}
              placeholder="Please provide a reason for cancelling this order..."
              rows={3}
              className={`w-full text-xs p-3 border rounded-xl focus:outline-none focus:ring-1 bg-white ${
                error ? "border-red-500 focus:ring-red-400" : "border-zinc-200 focus:ring-red-400"
              }`}
            />
            {error && (
              <p className="text-red-500 text-xs mt-1 font-semibold">{error}</p>
            )}
          </div>

          <div className="flex justify-end gap-2 pt-2">
            <Button
              type="button"
              variant="ghost"
              onClick={() => {
                onOpenChange(false);
                setError(undefined);
              }}
              disabled={submitting}
              className="text-xs h-9 px-4 rounded-lg cursor-pointer uppercase border"
            >
              Keep Order
            </Button>
            <Button
              type="submit"
              disabled={submitting}
              className="bg-red-600 hover:bg-red-700 text-white text-xs h-9 px-4 rounded-lg cursor-pointer uppercase"
            >
              {submitting ? "Submitting..." : "Yes, Request Cancel"}
            </Button>
          </div>
        </form>
      </div>
    </div>
  );
}
