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 { Textarea } from '@/components/ui/textarea';
import { AlertCircle, FileText, Loader2, Upload, X } from 'lucide-react';
import { useState } from 'react';

interface ModuleSettingsConfirmationModalProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    onConfirm: (reason: string, attachments: File[]) => void;
    isLoading?: boolean;
}

export function ModuleSettingsConfirmationModal({
    open,
    onOpenChange,
    onConfirm,
    isLoading = false,
}: ModuleSettingsConfirmationModalProps) {
    const [reason, setReason] = useState('');
    const [attachments, setAttachments] = useState<File[]>([]);
    const [errors, setErrors] = useState<{ reason?: string; attachments?: string }>({});

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const files = Array.from(e.target.files || []);
        
        // Validate file size (max 10MB per file)
        const maxSize = 10 * 1024 * 1024; // 10MB
        const invalidFiles = files.filter(file => file.size > maxSize);
        
        if (invalidFiles.length > 0) {
            setErrors(prev => ({
                ...prev,
                attachments: 'Some files exceed the 10MB size limit'
            }));
            return;
        }
        
        setAttachments(prev => [...prev, ...files]);
        setErrors(prev => ({ ...prev, attachments: undefined }));
    };

    const removeFile = (index: number) => {
        setAttachments(prev => prev.filter((_, i) => i !== index));
    };

    const handleConfirm = () => {
        // Validate
        const newErrors: { reason?: string; attachments?: string } = {};
        
        if (!reason.trim()) {
            newErrors.reason = 'Reason is required';
        }
        
        if (Object.keys(newErrors).length > 0) {
            setErrors(newErrors);
            return;
        }
        
        onConfirm(reason, attachments);
    };

    const handleClose = () => {
        if (!isLoading) {
            setReason('');
            setAttachments([]);
            setErrors({});
            onOpenChange(false);
        }
    };

    return (
        <Dialog open={open} onOpenChange={handleClose}>
            <DialogContent className="sm:max-w-[600px]">
                <DialogHeader>
                    <DialogTitle className="flex items-center gap-2">
                        <AlertCircle className="h-5 w-5 text-orange-500" />
                        Confirm Module Settings Change
                    </DialogTitle>
                    <DialogDescription>
                        Please provide a reason for changing the module settings. This will be logged for audit purposes.
                    </DialogDescription>
                </DialogHeader>

                <div className="space-y-4 py-4">
                    {/* Reason Input */}
                    <div className="space-y-2">
                        <Label htmlFor="reason" className="text-sm font-medium">
                            Reason for Change <span className="text-red-500">*</span>
                        </Label>
                        <Textarea
                            id="reason"
                            placeholder="e.g., Disabling unused modules to improve performance..."
                            value={reason}
                            onChange={(e) => {
                                setReason(e.target.value);
                                setErrors(prev => ({ ...prev, reason: undefined }));
                            }}
                            className={errors.reason ? 'border-red-500' : ''}
                            rows={4}
                            disabled={isLoading}
                        />
                        {errors.reason && (
                            <p className="text-sm text-red-500">{errors.reason}</p>
                        )}
                    </div>

                    {/* File Upload */}
                    <div className="space-y-2">
                        <Label htmlFor="attachments" className="text-sm font-medium">
                            Supporting Documents (Optional)
                        </Label>
                        <div className="flex items-center gap-2">
                            <Input
                                id="attachments"
                                type="file"
                                multiple
                                onChange={handleFileChange}
                                className="hidden"
                                disabled={isLoading}
                                accept=".pdf,.doc,.docx,.txt,.png,.jpg,.jpeg"
                            />
                            <Button
                                type="button"
                                variant="outline"
                                onClick={() => document.getElementById('attachments')?.click()}
                                disabled={isLoading}
                                className="w-full"
                            >
                                <Upload className="mr-2 h-4 w-4" />
                                Upload Files
                            </Button>
                        </div>
                        <p className="text-xs text-muted-foreground">
                            Accepted formats: PDF, DOC, DOCX, TXT, PNG, JPG (Max 10MB per file)
                        </p>
                        {errors.attachments && (
                            <p className="text-sm text-red-500">{errors.attachments}</p>
                        )}

                        {/* Attached Files List */}
                        {attachments.length > 0 && (
                            <div className="mt-3 space-y-2">
                                <p className="text-sm font-medium">Attached Files:</p>
                                <div className="space-y-1">
                                    {attachments.map((file, index) => (
                                        <div
                                            key={index}
                                            className="flex items-center justify-between rounded-md border bg-muted/50 p-2"
                                        >
                                            <div className="flex items-center gap-2">
                                                <FileText className="h-4 w-4 text-muted-foreground" />
                                                <span className="text-sm">{file.name}</span>
                                                <span className="text-xs text-muted-foreground">
                                                    ({(file.size / 1024).toFixed(1)} KB)
                                                </span>
                                            </div>
                                            <Button
                                                type="button"
                                                variant="ghost"
                                                size="sm"
                                                onClick={() => removeFile(index)}
                                                disabled={isLoading}
                                            >
                                                <X className="h-4 w-4" />
                                            </Button>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>
                </div>

                <DialogFooter>
                    <Button
                        type="button"
                        variant="outline"
                        onClick={handleClose}
                        disabled={isLoading}
                    >
                        Cancel
                    </Button>
                    <Button
                        type="button"
                        onClick={handleConfirm}
                        disabled={isLoading}
                    >
                        {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                        Confirm & Save
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}
