// components/Support/SupportRequestModal.js
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useSocket } from '@/context/SocketContext';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useToast } from '@/hooks/useToast';
import { useAuthStore } from '@/stores/authStore';


const SUPPORT_CATEGORIES = [
    { label: 'Technical Issue', value: 'technical' },
    { label: 'Billing Question', value: 'billing' },
    { label: 'Account Help', value: 'account' },
    { label: 'General Inquiry', value: 'general' },
];

export default function SupportRequestModal({ isOpen, onClose }) {
    const router = useRouter();
    const { socket } = useSocket();
    const { toast } = useToast();
    const [form, setForm] = useState({
        subject: '',
        category: '',
        description: ''
    });
    const [isSubmitting, setIsSubmitting] = useState(false);
    const user = useAuthStore((state) => state.user);


    const handleSubmit = async (e) => {
        e.preventDefault();
        setIsSubmitting(true);

        try {
            socket.emit('request-support', {
                subject: form.subject,
                category: form.category,
                description: form.description
            }, (response) => {
                console.log('Support request response:', response);
                if (response.success) {
                    toast({
                        title: 'Support Request Sent',
                        description: 'A support agent will be with you shortly.',
                        variant: 'default'
                    });
                    onClose();
                    let routePrefix = '/support'; // default

                    if (user?.role === 'pharmacy') {
                        routePrefix = '/dashboard/pharmacy/support';
                    } else if (user?.role === 'lab') {
                        routePrefix = '/dashboard/lab/support';
                    } else if (user?.role === 'doctor') {
                        routePrefix = '/dashboard/doctor/support';
                    } else if (user?.role === 'patient') {
                        routePrefix = '/dashboard/patient/support';
                    }
                    router.push(`${routePrefix}/tickets/${response.ticketId}`);
                } else {
                    toast({
                        title: 'Error',
                        description: response.error || 'Failed to send support request',
                        variant: 'destructive'
                    });
                }
            });
        } catch (error) {
            toast({
                title: 'Error',
                description: error.message,
                variant: 'destructive'
            });
        } finally {
            setIsSubmitting(false);
        }
    };

    const handleChange = (e) => {
        const { name, value } = e.target;
        setForm(prev => ({ ...prev, [name]: value }));
    };

    return (
        <Dialog open={isOpen} onOpenChange={onClose}>
            <DialogContent className="sm:max-w-[600px] bg-white p-6 rounded-lg shadow-lg">
                <DialogHeader>
                    <DialogTitle className="text-2xl">Contact Support</DialogTitle>
                </DialogHeader>

                <form onSubmit={handleSubmit} className="space-y-4">
                    <div className="space-y-2">
                        <label htmlFor="subject" className="block text-sm font-medium">
                            Subject
                        </label>
                        <Input
                            id="subject"
                            name="subject"
                            value={form.subject}
                            onChange={handleChange}
                            placeholder="Briefly describe your issue"
                            required
                        />
                    </div>

                    <div className="space-y-2">
                        <label htmlFor="category" className="block text-sm font-medium">
                            Category
                        </label>
                        <Select
                            onValueChange={(value) => setForm(prev => ({ ...prev, category: value }))}
                            value={form.category}
                            required
                        >
                            <SelectTrigger>
                                <SelectValue placeholder="Select a category" />
                            </SelectTrigger>
                            <SelectContent className="max-h-60 overflow-y-auto bg-white">
                                {SUPPORT_CATEGORIES.map((category) => (
                                    <SelectItem key={category.value} value={category.value} className="cursor-pointer hover:bg-gray-300">
                                        {category.label}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </div>

                    <div className="space-y-2">
                        <label htmlFor="description" className="block text-sm font-medium">
                            Description
                        </label>
                        <Textarea
                            id="description"
                            name="description"
                            value={form.description}
                            onChange={handleChange}
                            rows={5}
                            placeholder="Please describe your issue in detail..."
                            required
                        />
                    </div>

                    <div className="flex justify-end gap-2 pt-4">
                        <Button
                            type="button"
                            variant="outline"
                            onClick={onClose}
                            disabled={isSubmitting}
                            className="text-gray-600 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
                        >
                            Cancel
                        </Button>
                        <Button
                            type="submit"
                            disabled={isSubmitting || !form.subject || !form.category || !form.description}
                            className="bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
                        >
                            {isSubmitting ? 'Sending...' : 'Submit Request'}
                        </Button>
                    </div>
                </form>
            </DialogContent>
        </Dialog>
    );
}