import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/common/ui/dialog";
import { Button } from "@/shared/common/ui/button";
import { Input } from "@/shared/common/ui/input";
import { Label } from "@/shared/common/ui/label";
import { Spinner } from "@/shared/common/ui/sppiner";

interface ShareViaEmailProps {
  recordId: string;
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

const ShareViaEmail: React.FC<ShareViaEmailProps> = ({
  recordId,
  open,
  onClose,
  onSuccess,
}) => {
  const { t } = useTranslation();
  const [email, setEmail] = useState("");
  const [isSharing, setIsSharing] = useState(false);
  const [emailError, setEmailError] = useState("");

  const validateEmail = (email: string): boolean => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setEmail(value);

    if (emailError && value) {
      if (validateEmail(value)) {
        setEmailError("");
      }
    }
  };

  const handleShare = async () => {
    // Validate email
    if (!email.trim()) {
      setEmailError(t("shareViaEmail.emailRequired"));
      return;
    }

    if (!validateEmail(email)) {
      setEmailError(t("shareViaEmail.invalidEmailFormat"));
      return;
    }

    try {
      setIsSharing(true);
      // await shareRecordViaEmail(recordId, email.trim());
      toast.success(t("shareViaEmail.shareSuccess"));
      onSuccess();
      handleClose();
    } catch (error: any) {
      const errorMessage = error.message || t("shareViaEmail.shareFailed");
      toast.error(errorMessage);
      setEmailError(errorMessage);
    } finally {
      setIsSharing(false);
    }
  };

  const handleClose = () => {
    setEmail("");
    setEmailError("");
    onClose();
  };

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>{t("shareViaEmail.title")}</DialogTitle>
          <DialogDescription>
            {t("shareViaEmail.description")}
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="email">{t("shareViaEmail.emailLabel")}</Label>
            <Input
              id="email"
              type="email"
              placeholder={t("shareViaEmail.emailPlaceholder")}
              value={email}
              onChange={handleEmailChange}
              className={emailError ? "border-red-500" : ""}
              disabled={isSharing}
            />
            {emailError && <p className="text-sm text-red-500">{emailError}</p>}
          </div>
        </div>

        <DialogFooter className="flex-col sm:flex-row gap-2">
          <Button
            variant="outline"
            onClick={handleClose}
            disabled={isSharing}
            className="w-full sm:w-auto"
          >
            {t("common.Cancel")}
          </Button>
          <Button
            onClick={handleShare}
            disabled={isSharing || !email.trim()}
            className="w-full sm:w-auto"
          >
            {isSharing && <Spinner size="small" className="mr-2" />}
            {t("shareViaEmail.shareButton")}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default ShareViaEmail;
