"use client";

import { useState, useEffect, useCallback } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Skeleton } from '@/components/ui/skeleton';

export function DndToggle() {
    const { token } = useAuth();
    const [dndStatus, setDndStatus] = useState(false);
    const [loading, setLoading] = useState(true);

    const fetchDndStatus = useCallback(async () => {
        if (!token) return;
        setLoading(true);
        try {
            const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001'}/extensions/me/dnd`, {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            const data = await res.json();
            setDndStatus(data.dndStatus);
        } catch (error) {
            console.error("Failed to fetch DND status", error);
        } finally {
            setLoading(false);
        }
    }, [token]);

    useEffect(() => {
        fetchDndStatus();
    }, [fetchDndStatus]);

    const handleToggle = async (checked) => {
        if (!token) return;
        setDndStatus(checked); // Optimistic update
        try {
            await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001'}/extensions/me/dnd`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ dndStatus: checked })
            });
        } catch (error) {
            console.error("Failed to update DND status", error);
            setDndStatus(!checked); // Revert on failure
        }
    };

    return (
        <Card className="bg-gray-950/50 border-gray-800">
            <CardHeader>
                <CardTitle>Do Not Disturb</CardTitle>
                <CardDescription>When enabled, calls will not ring your extension.</CardDescription>
            </CardHeader>
            <CardContent>
                {loading ? (
                    <div className="flex items-center space-x-2">
                        <Skeleton className="h-6 w-11 rounded-full" />
                        <Skeleton className="h-5 w-20" />
                    </div>
                ) : (
                    <div className="flex items-center space-x-2">
                        <Switch
                            id="dnd-mode"
                            checked={dndStatus}
                            onCheckedChange={handleToggle}
                        />
                        <Label htmlFor="dnd-mode">{dndStatus ? 'Enabled' : 'Disabled'}</Label>
                    </div>
                )}
            </CardContent>
        </Card>
    );
}
