import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { PenTool, Check } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";

interface DigitalSignatureProps {
  title: string;
  signedBy?: string;
  signedAt?: string;
  onSign?: (signatureData: { signedBy: string; signedAt: string; signatureImageUrl?: string }) => void;
  signatureImageUrl?: string;
  required?: boolean;
  isEditable?: boolean;
  currentApprovalText?: string;
  signatureType?: 'expert' | 'manager'; // To determine position-based access
}

export default function DigitalSignature({
  title,
  signedBy,
  signedAt,
  onSign,
  signatureImageUrl,
  required = false,
  isEditable = true,
  currentApprovalText,
  signatureType,
}: DigitalSignatureProps) {
  const { user } = useAuth();
  const [isLoading, setIsLoading] = useState(false);
  
  // Check if user can sign based on their position
  const canUserSign = () => {
    if (!user || !signatureType) return true; // Default to allow if no position check needed
    
    console.log(`Frontend position check: user=${user.fullName}, position=${(user as any).position}, signatureType=${signatureType}`);
    
    const userPosition = (user as any).position;
    
    // Expert/supervisor signature fields - allow کارشناس, سرپرست, but not مدیر
    if (signatureType === 'expert') {
      return userPosition === 'کارشناس' || userPosition === 'سرپرست';
    }
    
    // Manager signature fields - only allow مدیر
    if (signatureType === 'manager') {
      return userPosition === 'مدیر';
    }
    
    return true;
  };

  const handleSign = async () => {
    if (!onSign || !user) return;
    
    setIsLoading(true);
    try {
      const signatureData = {
        signedBy: user.fullName,
        signedAt: new Date().toISOString(),
        signatureImageUrl: user.signatureImageUrl,
      };
      await onSign(signatureData);
    } finally {
      setIsLoading(false);
    }
  };

  const isSigned = (signedBy && signedBy.trim()) || (currentApprovalText && currentApprovalText.trim());

  return (
    <Card className={`${required && !isSigned ? 'border-red-200 bg-red-50' : ''}`}>
      <CardHeader>
        <CardTitle className="flex items-center gap-2 text-sm">
          {isSigned ? <Check className="h-4 w-4 text-green-600" /> : <PenTool className="h-4 w-4" />}
          {title}
          {required && !isSigned && <span className="text-red-500 text-xs">(اجباری)</span>}
        </CardTitle>
      </CardHeader>
      <CardContent>
        {isSigned ? (
          <div className="space-y-3">
            {currentApprovalText && (
              <div className="bg-gray-50 p-3 rounded border text-sm text-right">
                <p className="font-medium mb-1">متن تایید:</p>
                <p>{currentApprovalText}</p>
              </div>
            )}
            {signatureImageUrl && signatureImageUrl.trim() && (
              <div className="flex justify-center">
                <img 
                  src={signatureImageUrl} 
                  alt="امضای دیجیتال"
                  className="max-w-[150px] max-h-[60px] object-contain border rounded"
                  onError={(e) => {
                    console.log("Image load error for signature:", signatureImageUrl);
                    (e.target as HTMLImageElement).style.display = 'none';
                  }}
                  onLoad={() => {
                    console.log("Image loaded successfully:", signatureImageUrl);
                  }}
                />
              </div>
            )}
            <div className="text-center text-sm text-gray-600">
              <p>امضا شده توسط: <strong>{signedBy || user?.fullName}</strong></p>
              {signedAt && (
                <p className="text-xs text-gray-500">
                  تاریخ: {new Date(signedAt).toLocaleDateString('fa-IR')}
                </p>
              )}
            </div>
          </div>
        ) : (
          <div className="space-y-3">
            {isEditable && onSign && canUserSign() && (
              <Button
                onClick={(e) => {
                  e.preventDefault();
                  handleSign();
                }}
                disabled={isLoading}
                className="w-full"
                variant={required ? "default" : "outline"}
                type="button"
              >
                {isLoading ? "در حال اعمال امضا..." : "امضای دیجیتال"}
              </Button>
            )}
            {!canUserSign() && (
              <div className="bg-yellow-50 border border-yellow-200 p-3 rounded text-sm text-center">
                <p className="text-yellow-700">
                  {signatureType === 'expert' && (user as any)?.position === 'مدیر' 
                    ? "کاربران با سمت مدیر نمی‌توانند در قسمت امضای کارشناس/سرپرست امضا کنند"
                    : "فقط کاربران با سمت مدیر می‌توانند در قسمت امضای مدیر امضا کنند"
                  }
                </p>
              </div>
            )}
            {canUserSign() && (
              <p className="text-sm text-gray-500 text-center">
                {isEditable && onSign 
                  ? "برای اعمال امضای دیجیتال کلیک کنید"
                  : "منتظر امضای دیجیتال"
                }
              </p>
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
}