"use client";

import { useEffect, useState } from 'react';
import api from '../../lib/api';
import { Group, UserInfo } from '../../types';
import {
    PlusIcon,
    TrashIcon,
    PencilSquareIcon,
    UserGroupIcon,
    CheckBadgeIcon,
} from '@heroicons/react/24/outline';

const GroupsPage = () => {
    const [groups, setGroups] = useState<Group[]>([]);
    const [users, setUsers] = useState<UserInfo[]>([]);
    const [defaultGroupId, setDefaultGroupId] = useState<number | null>(null);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingGroup, setEditingGroup] = useState<Group | null>(null);
    const [formData, setFormData] = useState({ name: '', description: '', user_ids: [] as number[] });
    const [status, setStatus] = useState<{ message: string, type: string }>({ message: '', type: '' });

    const fetchData = async () => {
        try {
            const [gRes, uRes, dRes] = await Promise.all([
                api.get('/api/v1/groups'),
                api.get('/auth/users').catch(() => ({ data: [] })),
                api.get('/api/v1/groups/default').catch(() => ({ data: null }))
            ]);
            setGroups(gRes.data);
            setUsers(uRes.data);
            setDefaultGroupId(dRes.data);
        } catch (error) {
            console.error("Failed to fetch data", error);
        } finally {
            setLoading(false);
        }
    };

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

    const handleOpenModal = (group: Group | null = null) => {
        setEditingGroup(group);
        if (group) {
            setFormData({
                name: group.name,
                description: group.description || '',
                user_ids: group.members.map(m => m.id)
            });
        } else {
            setFormData({ name: '', description: '', user_ids: [] });
        }
        setIsModalOpen(true);
        setStatus({ message: '', type: '' });
    };

    const handleSave = async () => {
        if (!formData.name) {
            setStatus({ message: 'Name is required', type: 'error' });
            return;
        }

        try {
            if (editingGroup) {
                await api.put(`/api/v1/groups/${editingGroup.id}`, formData);
            } else {
                await api.post('/api/v1/groups', formData);
            }
            setIsModalOpen(false);
            fetchData();
        } catch (error: any) {
            setStatus({ message: error.response?.data?.detail || 'Failed to save group', type: 'error' });
        }
    };

    const handleDelete = async (id: number) => {
        if (!confirm('Are you sure you want to delete this group?')) return;
        try {
            await api.delete(`/api/v1/groups/${id}`);
            fetchData();
        } catch (error) {
            console.error(error);
        }
    };

    const handleSetDefault = async (id: number | null) => {
        try {
            if (id === null) {
                await api.post(`/api/v1/groups/default`);
                setDefaultGroupId(null);
            } else {
                await api.post(`/api/v1/groups/default?group_id=${id}`);
                setDefaultGroupId(id);
            }
        } catch (error) {
            console.error(error);
        }
    };

    const toggleUserSelection = (userId: number) => {
        setFormData(prev => ({
            ...prev,
            user_ids: prev.user_ids.includes(userId)
                ? prev.user_ids.filter(id => id !== userId)
                : [...prev.user_ids, userId]
        }));
    };

    if (loading) return <div className="p-8 text-center font-mono">Loading Groups...</div>;

    return (
        <div className="max-w-7xl mx-auto p-6">
            <div className="md:flex md:items-center md:justify-between mb-8">
                <div className="min-w-0 flex-1">
                    <h2 className="text-3xl font-bold leading-7 text-gray-900 font-mono">
                        User Groups
                    </h2>
                    <p className="mt-1 text-sm text-gray-500 font-mono">Manage groups for bulk assignment and notifications.</p>
                </div>
                <div className="mt-4 flex md:ml-4 md:mt-0">
                    <button
                        onClick={() => handleOpenModal()}
                        className="inline-flex items-center rounded-md bg-vulncheck-blue px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-blue-600 font-mono"
                    >
                        <PlusIcon className="h-4 w-4 mr-2" />
                        Create Group
                    </button>
                </div>
            </div>

            <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
                {groups.map((group) => (
                    <div key={group.id} className="relative flex flex-col bg-white border border-gray-200 rounded-lg shadow-sm hover:border-blue-300 transition-colors p-6">
                        <div className="flex justify-between items-start mb-4">
                            <div className="flex items-center gap-2">
                                <UserGroupIcon className="h-8 w-8 text-gray-400" />
                                <div>
                                    <h3 className="text-lg font-bold text-gray-900 font-mono">{group.name}</h3>
                                    {defaultGroupId === group.id && (
                                        <span className="inline-flex items-center rounded-full bg-green-50 px-2 py-1 text-xs font-medium text-green-700 ring-1 ring-inset ring-green-600/20">
                                            Default
                                        </span>
                                    )}
                                </div>
                            </div>
                            <div className="flex gap-2">
                                <button onClick={() => handleOpenModal(group)} className="text-gray-400 hover:text-blue-600">
                                    <PencilSquareIcon className="h-5 w-5" />
                                </button>
                                <button onClick={() => handleDelete(group.id)} className="text-gray-400 hover:text-red-600">
                                    <TrashIcon className="h-5 w-5" />
                                </button>
                            </div>
                        </div>
                        <p className="text-sm text-gray-600 mb-4 flex-grow font-mono">{group.description || 'No description'}</p>

                        <div className="border-t border-gray-100 pt-4 mt-auto">
                            <p className="text-xs text-gray-500 font-mono mb-2">{group.member_count} Members:</p>
                            <div className="flex flex-wrap gap-1">
                                {group.members.slice(0, 5).map(m => (
                                    <span key={m.id} className="inline-flex items-center rounded bg-gray-50 px-2 py-1 text-xs font-medium text-gray-600 ring-1 ring-inset ring-gray-500/10">
                                        {m.username}
                                    </span>
                                ))}
                                {group.member_count > 5 && <span className="text-xs text-gray-400">+{group.member_count - 5} more</span>}
                            </div>

                            {defaultGroupId !== group.id ? (
                                <button
                                    onClick={() => handleSetDefault(group.id)}
                                    className="mt-4 w-full flex justify-center items-center gap-2 px-3 py-1.5 text-xs font-medium text-blue-600 bg-blue-50 hover:bg-blue-100 rounded border border-blue-200"
                                >
                                    <CheckBadgeIcon className="h-4 w-4" />
                                    Set as Default
                                </button>
                            ) : (
                                <button
                                    onClick={() => handleSetDefault(null)}
                                    className="mt-4 w-full flex justify-center items-center gap-2 px-3 py-1.5 text-xs font-medium text-gray-600 bg-gray-50 hover:bg-gray-100 rounded border border-gray-200"
                                >
                                    Remove Default
                                </button>
                            )}
                        </div>
                    </div>
                ))}
            </div>

            {/* Modal */}
            {isModalOpen && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-gray-500 bg-opacity-75">
                    <div className="bg-white rounded-lg shadow-xl max-w-lg w-full p-6">
                        <h3 className="text-lg font-bold mb-4 font-mono">{editingGroup ? 'Edit Group' : 'Create Group'}</h3>

                        <div className="space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 font-mono">Name</label>
                                <input
                                    type="text"
                                    value={formData.name}
                                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm"
                                />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 font-mono">Description</label>
                                <textarea
                                    value={formData.description}
                                    onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-vulncheck-blue focus:ring-vulncheck-blue sm:text-sm"
                                    rows={3}
                                />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 font-mono mb-2">Members ({formData.user_ids.length})</label>
                                <div className="max-h-48 overflow-y-auto border border-gray-200 rounded-md p-2 space-y-2">
                                    {users.map(u => (
                                        <div key={u.id} className="flex items-center">
                                            <input
                                                type="checkbox"
                                                id={`user-${u.id}`}
                                                checked={formData.user_ids.includes(u.id)}
                                                onChange={() => toggleUserSelection(u.id)}
                                                className="h-4 w-4 rounded border-gray-300 text-vulncheck-blue focus:ring-vulncheck-blue"
                                            />
                                            <label htmlFor={`user-${u.id}`} className="ml-2 block text-sm text-gray-900 font-mono">
                                                {u.username} <span className="text-gray-400 text-xs">({u.email})</span>
                                            </label>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </div>

                        {status.message && (
                            <p className={`mt-4 text-sm ${status.type === 'error' ? 'text-red-600' : 'text-green-600'}`}>{status.message}</p>
                        )}

                        <div className="flex justify-end gap-2 mt-6">
                            <button onClick={() => setIsModalOpen(false)} className="rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50">Cancel</button>
                            <button onClick={handleSave} className="rounded-md bg-vulncheck-blue px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-blue-600">Save</button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default GroupsPage;
