"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { useToast } from "@/components/ui/use-toast";
import { shareVersionWithClient } from "@/actions/versions";
import { Send, CheckCircle2 } from "lucide-react";

interface ShareWithClientButtonProps {
  versionId: string;
  isAlreadyShared?: boolean;
  onShared?: () => void;
  size?: "sm" | "default";
}

export function ShareWithClientButton({
  versionId,
  isAlreadyShared = false,
  onShared,
  size = "sm",
}: ShareWithClientButtonProps) {
  const [shared, setShared] = useState(isAlreadyShared);
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

  const handleShare = async () => {
    if (shared) return;
    setLoading(true);
    try {
      await shareVersionWithClient(versionId);
      setShared(true);
      toast({ title: "Version shared with client" });
      onShared?.();
    } catch (err) {
      toast({
        title: "Failed to share version",
        description: (err as Error).message,
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  if (shared) {
    return (
      <Button
        size={size}
        variant="outline"
        disabled
        className="h-7 text-xs gap-1 text-amber-400 border-amber-500/30"
      >
        <CheckCircle2 className="h-3 w-3" />
        <span className="hidden sm:inline">Shared with Client</span>
      </Button>
    );
  }

  return (
    <Button
      size={size}
      variant="outline"
      disabled={loading}
      onClick={handleShare}
      className="h-7 text-xs gap-1 text-amber-400 border-amber-500/30 hover:bg-amber-500/10"
    >
      <Send className="h-3 w-3" />
      <span className="hidden sm:inline">{loading ? "Sharing…" : "Share with Client"}</span>
    </Button>
  );
}
