import { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useQueryClient } from "@tanstack/react-query";
import {
  useCreateServiceOrder,
  getListMyServiceOrdersQueryKey,
} from "@workspace/api-client-react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { ImageIcon } from "lucide-react";
import { useToast } from "@/hooks/use-toast";

const NOTES_MAX = 500;

type Props = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  service: {
    id: number;
    nameAr: string;
    nameEn: string;
    imageUrl?: string | null;
  } | null;
  resolveImage: (url: string | null | undefined) => string | null;
  initialNotes?: string | null;
};

export function OrderServiceModal({
  open,
  onOpenChange,
  service,
  resolveImage,
  initialNotes,
}: Props) {
  const { t, i18n } = useTranslation();
  const lang = i18n.language;
  const queryClient = useQueryClient();
  const { toast } = useToast();
  const [notes, setNotes] = useState("");
  const [imgErrored, setImgErrored] = useState(false);

  const createOrder = useCreateServiceOrder();

  useEffect(() => {
    if (open) {
      setNotes((initialNotes ?? "").slice(0, NOTES_MAX));
      setImgErrored(false);
    }
  }, [open, service?.id, initialNotes]);

  if (!service) return null;
  const name = lang === "ar" ? service.nameAr : service.nameEn;
  const img = resolveImage(service.imageUrl);

  const handleSubmit = () => {
    const trimmed = notes.trim();
    createOrder.mutate(
      {
        data: {
          serviceId: service.id,
          notes: trimmed.length > 0 ? trimmed.slice(0, NOTES_MAX) : null,
        },
      },
      {
        onSuccess: () => {
          queryClient.invalidateQueries({
            queryKey: getListMyServiceOrdersQueryKey(),
          });
          toast({ title: t("services.orderPlaced") });
          onOpenChange(false);
        },
        onError: () => {
          toast({
            title: t("services.orderFailed"),
            variant: "destructive",
          });
        },
      },
    );
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent
        className="max-w-md"
        dir={lang === "ar" ? "rtl" : "ltr"}
      >
        <DialogHeader>
          <DialogTitle>
            {t("services.orderModalTitle", { name })}
          </DialogTitle>
        </DialogHeader>

        <div className="flex items-center gap-3">
          <div className="w-16 h-16 rounded-lg bg-slate-100 overflow-hidden flex items-center justify-center shrink-0">
            {img && !imgErrored ? (
              <img
                src={img}
                alt={name}
                className="w-full h-full object-cover"
                onError={() => setImgErrored(true)}
              />
            ) : (
              <ImageIcon size={20} className="text-slate-300" />
            )}
          </div>
          <div className="text-base font-medium text-foreground">{name}</div>
        </div>

        <div className="space-y-1.5">
          <Label htmlFor="order-notes">{t("services.orderNotes")}</Label>
          <Textarea
            id="order-notes"
            value={notes}
            onChange={(e) => setNotes(e.target.value.slice(0, NOTES_MAX))}
            placeholder={t("services.orderNotesPlaceholder")}
            maxLength={NOTES_MAX}
            rows={3}
          />
          <div className="text-[11px] text-muted-foreground text-end">
            {t("services.orderNotesCounter", { count: notes.length })}
          </div>
        </div>

        <DialogFooter className="gap-2 sm:gap-2">
          <Button
            variant="ghost"
            onClick={() => onOpenChange(false)}
            disabled={createOrder.isPending}
          >
            {t("common.cancel")}
          </Button>
          <Button onClick={handleSubmit} disabled={createOrder.isPending}>
            {createOrder.isPending
              ? t("services.placing")
              : t("services.placeOrder")}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
