import { useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
    AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { SigviewRecord as Signature } from "@/lib/pbtypes";
import { getSignatureMeta } from "@/hooks/useSignatureCategories";
import { Trash2 } from "lucide-react";
import { SignatureEditModal } from "@/components/SignatureEditModal";

interface SignatureCardProps {
  signature: Signature;
  onDelete?: (signatureId: string) => Promise<void>;
  onUpdate?: (updatedSignature: Partial<Signature>) => Promise<void>;
}

export const SignatureCard = ({ signature, onDelete, onUpdate }: SignatureCardProps) => {
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const meta = getSignatureMeta(signature.type);
  const isGasSite = signature.type?.toLowerCase().includes('gas');

  const handleDelete = async () => {
    if (onDelete) {
      try {
        await onDelete(signature.id);
      } catch (error) {
        console.error('Failed to delete signature:', error);
      }
    }
  };

  const handleUpdate = async (updatedSignature: Partial<Signature>) => {
    if (onUpdate) {
      try {
        await onUpdate(updatedSignature);
      } catch (error) {
        console.error('Failed to update signature:', error);
        throw error;
      }
    }
  };

  return (
    <>
      <Card 
        className={`${isGasSite ? 'bg-emerald-900/40 border-emerald-500 shadow-[0_0_15px_rgba(16,185,129,0.5)] hover:shadow-[0_0_20px_rgba(16,185,129,0.7)]' : 'bg-slate-800/40 border-slate-700'} hover:bg-slate-800/60 transition-all duration-200 hover:border-slate-600 relative cursor-pointer`}
        onClick={() => setIsEditModalOpen(true)}
      >
        <CardContent className="pt-6">
          <div className="space-y-3">
            {/* Type Badge - Most Important */}
            <div className="flex items-center justify-center">
              <Badge 
                variant="outline" 
                className={`${meta.color} px-3 py-1 text-sm font-semibold flex items-center gap-2`}
              >
                {meta.icon}
                {signature.type || 'Unknown Type'}
              </Badge>
            </div>
            
            {/* Signature Name */}
            <div className="text-center">
              <h3 className="text-white font-medium text-lg">
                {signature.signame || 'Unnamed Signature'}
              </h3>
              {signature.note && (
                <div className="mt-2">
                  <Badge variant="outline" className="bg-blue-900/50 text-blue-200 border-blue-500 px-3 py-1 text-sm font-semibold">
                    {signature.note}
                  </Badge>
                </div>
              )}
            </div>
            
            {/* Additional Info */}
            <div className="space-y-2 text-sm text-slate-400">
              <div className="flex justify-between">
                <span>System:</span>
                <span className="text-slate-200">{signature.system}</span>
              </div>
              <div className="flex justify-between">
                <span>ID:</span>
                <span className="text-slate-200 font-mono text-xs">{signature.id}</span>
              </div>
            </div>
          </div>

          {/* Delete Button */}
          {onDelete && (
            <div className="absolute top-2 right-2">
              <AlertDialog>
                <AlertDialogTrigger asChild>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-6 w-6 text-slate-400 hover:text-red-400 hover:bg-red-900/20 transition-colors"
                    onClick={(e) => e.stopPropagation()} // Prevent opening edit modal when clicking delete
                  >
                    <Trash2 className="h-3 w-3" />
                  </Button>
                </AlertDialogTrigger>
                <AlertDialogContent className="bg-slate-800 border-slate-700">
                  <AlertDialogHeader>
                    <AlertDialogTitle className="text-white">Delete Signature</AlertDialogTitle>
                    <AlertDialogDescription className="text-slate-300">
                      Are you sure you want to delete signature <span className="font-mono text-white">{signature.identifier}</span>?
                      <br />
                      This action cannot be undone.
                    </AlertDialogDescription>
                  </AlertDialogHeader>
                  <AlertDialogFooter>
                    <AlertDialogCancel className="bg-slate-700 border-slate-600 text-slate-200 hover:bg-slate-600">
                      Cancel
                    </AlertDialogCancel>
                    <AlertDialogAction
                      onClick={handleDelete}
                      className="bg-red-600 hover:bg-red-700 text-white"
                    >
                      Delete
                    </AlertDialogAction>
                  </AlertDialogFooter>
                </AlertDialogContent>
              </AlertDialog>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Edit Modal */}
      {onUpdate && (
        <SignatureEditModal
          signature={signature}
          isOpen={isEditModalOpen}
          onClose={() => setIsEditModalOpen(false)}
          onSave={handleUpdate}
        />
      )}
    </>
  );
};
