import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { SigviewRecord as Signature } from "@/lib/pbtypes";
import { getSignatureMeta, getSignatureTypes } from "@/hooks/useSignatureCategories";
import { toast } from "@/hooks/use-toast";

interface SignatureEditModalProps {
	signature: Signature;
	isOpen: boolean;
	onClose: () => void;
	onSave: (updatedSignature: Partial<Signature>) => Promise<void>;
}

export const SignatureEditModal = ({ signature, isOpen, onClose, onSave }: SignatureEditModalProps) => {
	const [formData, setFormData] = useState({
		type: signature.type || "unknown",
		signame: signature.signame || "",
		dangerous: signature.dangerous || false,
		scanned: signature.scanned || "",
		identifier: signature.identifier || ""
	});
	const [isLoading, setIsLoading] = useState(false);

	const signatureTypes = getSignatureTypes();
	const currentMeta = getSignatureMeta(formData.type === "unknown" ? "" : formData.type);

	const handleSave = async () => {
		setIsLoading(true);
		try {
			await onSave({
				identifier: signature.identifier,
				type: formData.type === "unknown" ? undefined : formData.type,
				signame: formData.signame || undefined,
				dangerous: formData.dangerous,
				scanned: formData.scanned || undefined
			});
			onClose();
			toast({
				title: "Signature Updated",
				description: "The signature has been successfully updated.",
			});
		} catch (error) {
			console.error('Failed to update signature:', error);
			toast({
				title: "Update Failed",
				description: error instanceof Error ? error.message : "Failed to update signature.",
				variant: "destructive"
			});
		} finally {
			setIsLoading(false);
		}
	};

	const handleClose = () => {
		// Reset form data to original values when closing
		setFormData({
			type: signature.type || "unknown",
			signame: signature.signame || "",
			dangerous: signature.dangerous || false,
			scanned: signature.scanned || "",
			identifier: signature.identifier || ""
		});
		onClose();
	};

	return (
		<Dialog open={isOpen} onOpenChange={handleClose}>
			<DialogContent className="bg-slate-800 border-slate-700 max-w-md">
				<DialogHeader>
					<DialogTitle className="text-white flex items-center gap-2">
						{currentMeta.icon}
						Edit Signature
					</DialogTitle>
					<DialogDescription className="text-slate-300">
						Modify the signature details below. All changes will be saved immediately.
					</DialogDescription>
				</DialogHeader>

				<div className="space-y-4 py-4">
					{/* Signature Identifier (Read-only) */}
					<div className="space-y-2">
						<Label htmlFor="identifier" className="text-slate-200">Signature ID</Label>
						<Input
							id="identifier"
							value={formData.identifier}
							disabled
							className="bg-slate-700 border-slate-600 text-slate-300 font-mono"
						/>
					</div>

					{/* Signature Type */}
					<div className="space-y-2">
						<Label htmlFor="type" className="text-slate-200">Type</Label>
						<Select value={formData.type} onValueChange={(value) => setFormData(prev => ({ ...prev, type: value }))}>
							<SelectTrigger className="bg-slate-700 border-slate-600 text-slate-200">
								<SelectValue placeholder="Select signature type" />
							</SelectTrigger>
							<SelectContent className="bg-slate-700 border-slate-600">
								<SelectItem value="unknown" className="text-slate-200">Unknown Type</SelectItem>
								{signatureTypes.map((type) => (
									<SelectItem key={type} value={type} className="text-slate-200">
										{type}
									</SelectItem>
								))}
							</SelectContent>
						</Select>
						{formData.type !== "unknown" && (
							<Badge variant="outline" className={`${currentMeta.color} mt-2`}>
								{currentMeta.icon}
								{formData.type}
							</Badge>
						)}
					</div>

					{/* Signature Name */}
					<div className="space-y-2">
						<Label htmlFor="signame" className="text-slate-200">Name</Label>
						<Input
							id="signame"
							value={formData.signame}
							onChange={(e) => setFormData(prev => ({ ...prev, signame: e.target.value }))}
							placeholder="Enter signature name"
							className="bg-slate-700 border-slate-600 text-slate-200"
						/>
					</div>

					{/* Scanned Percentage */}
					<div className="space-y-2">
						<Label htmlFor="scanned" className="text-slate-200">Scanned (%)</Label>
						<Input
							id="scanned"
							type="number"
							min="0"
							max="100"
							value={formData.scanned}
							onChange={(e) => setFormData(prev => ({ ...prev, scanned: e.target.value }))}
							placeholder="0-100"
							className="bg-slate-700 border-slate-600 text-slate-200"
						/>
					</div>

					{/* Dangerous Flag */}
					<div className="flex items-center justify-between">
						<Label htmlFor="dangerous" className="text-slate-200">Dangerous</Label>
						<Switch
							id="dangerous"
							checked={formData.dangerous}
							onCheckedChange={(checked) => setFormData(prev => ({ ...prev, dangerous: checked }))}
						/>
					</div>

					{/* Preview */}
					<div className="pt-4 border-t border-slate-600">
						<Label className="text-slate-200 text-sm">Preview</Label>
						<div className="mt-2 p-3 bg-slate-700 rounded border border-slate-600">
							<div className="flex items-center gap-2 mb-2">
								<Badge variant="outline" className={`${currentMeta.color}`}>
									{currentMeta.icon}
									{formData.type === "unknown" ? "Unknown Type" : formData.type}
								</Badge>
								{formData.dangerous && (
									<Badge variant="outline" className="bg-red-900/50 text-red-200 border-red-500">
										DANGEROUS
									</Badge>
								)}
							</div>
							<div className="text-slate-200 font-mono text-sm">{formData.identifier}</div>
							<div className="text-white">{formData.signame || "Unnamed Signature"}</div>
							{formData.scanned && (
								<div className="text-slate-400 text-sm">Scanned: {formData.scanned}%</div>
							)}
						</div>
					</div>
				</div>

				<DialogFooter>
					<Button
						variant="outline"
						onClick={handleClose}
						className="bg-slate-700 border-slate-600 text-slate-200 hover:bg-slate-600"
					>
						Cancel
					</Button>
					<Button
						onClick={handleSave}
						disabled={isLoading}
						className="bg-blue-600 hover:bg-blue-700 text-white"
					>
						{isLoading ? "Saving..." : "Save Changes"}
					</Button>
				</DialogFooter>
			</DialogContent>
		</Dialog>
	);
}; 