"use client";

import { useEffect, useState } from 'react';
import { notFound } from 'next/navigation';
import Image from 'next/image';
import {
    Activity, ShieldAlert, CreditCard, LayoutDashboard,
    MessageSquare, Briefcase, FileText, User as UserIcon,
    ArrowLeft, Mail, MapPin, Calendar, Clock,
    CheckCircle2, XCircle, MoreHorizontal, Key, AlertCircle
} from 'lucide-react';
import Link from 'next/link';

// Tab Components (to be built)
import { OverviewTab } from './tabs/OverviewTab';
import { ProfileTab } from './tabs/ProfileTab';
import { ActivityTab } from './tabs/ActivityTab';

interface UserDetailDashboardProps {
    userId: string;
}

const TABS = [
    { id: 'overview', label: 'Overview', icon: LayoutDashboard },
    { id: 'profile', label: 'Profile', icon: UserIcon },
    { id: 'activity', label: 'Activity', icon: Activity },
    { id: 'jobs', label: 'Jobs / Apps', icon: Briefcase },
    { id: 'messages', label: 'Messages', icon: MessageSquare },
    { id: 'payments', label: 'Payments', icon: CreditCard },
    { id: 'security', label: 'Security', icon: ShieldAlert },
    { id: 'reports', label: 'Reports', icon: FileText },
];

export function UserDetailDashboard({ userId }: UserDetailDashboardProps) {
    const [user, setUser] = useState<any>(null);
    const [loading, setLoading] = useState(true);
    const [activeTab, setActiveTab] = useState('overview');
    const [resetLoading, setResetLoading] = useState(false);
    const [feedback, setFeedback] = useState<{ type: 'success' | 'error', message: string, link?: string } | null>(null);

    useEffect(() => {
        async function fetchUser() {
            try {
                const res = await fetch(`/api/admin/users/${userId}`);
                if (!res.ok) {
                    if (res.status === 404) notFound();
                    throw new Error("Failed to fetch");
                }
                const data = await res.json();
                setUser(data);
            } catch (error) {
                console.error("Error fetching user details:", error);
            } finally {
                setLoading(false);
            }
        }
        fetchUser();
    }, [userId]);

    const handleForcePasswordReset = async () => {
        if (!confirm('Are you sure you want to force a password reset for this user? Check your audit logs to ensure this is authorized.')) return;

        setResetLoading(true);
        setFeedback(null);
        try {
            const res = await fetch(`/api/admin/users/${userId}/reset-password`, { method: 'POST' });
            const data = await res.json();
            if (!res.ok) throw new Error(data.error || 'Failed to force reset');

            setFeedback({ type: 'success', message: data.message, link: data.resetLink });
        } catch (error: any) {
            setFeedback({ type: 'error', message: error.message });
        } finally {
            setResetLoading(false);
        }
    };

    if (loading) {
        return (
            <div className="flex items-center justify-center min-h-[400px]">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            </div>
        );
    }

    if (!user) return null;

    return (
        <div className="space-y-6">
            {/* Top Navigation */}
            <div>
                <Link href="/admin/users" className="inline-flex items-center text-sm font-medium text-slate-500 hover:text-slate-900 transition-colors">
                    <ArrowLeft className="w-4 h-4 mr-1" /> Back to Users
                </Link>
            </div>

            {/* Header Profile Card */}
            <div className="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
                <div className="p-6 sm:p-8">
                    <div className="sm:flex sm:items-center sm:justify-between">
                        <div className="sm:flex sm:space-x-5">
                            <div className="flex-shrink-0 relative">
                                <div className="h-20 w-20 rounded-full bg-slate-200 border-4 border-white shadow-sm flex items-center justify-center text-2xl font-bold text-slate-500 overflow-hidden">
                                    {user.avatarUrl ? (
                                        <Image src={user.avatarUrl} alt={user.name} fill className="object-cover" />
                                    ) : (
                                        user.name.charAt(0)
                                    )}
                                </div>
                                <span className={`absolute bottom-0 right-0 block h-4 w-4 rounded-full border-2 border-white
                                    ${user.is_active ? 'bg-green-400' : 'bg-red-400'}`}
                                />
                            </div>
                            <div className="mt-4 sm:mt-0 sm:pt-1 sm:text-left text-center">
                                <p className="text-xl font-bold text-slate-900 sm:text-2xl">{user.name}</p>
                                <p className="text-sm font-medium text-slate-600 flex items-center justify-center sm:justify-start gap-1.5 mt-1">
                                    <span className="capitalize">{user.role}</span>
                                    {user.department && <span className="text-slate-400">• {user.department}</span>}
                                </p>
                                <div className="mt-2 flex flex-wrap items-center justify-center sm:justify-start gap-4 text-sm text-slate-500">
                                    <div className="flex items-center gap-1.5">
                                        <Mail className="w-4 h-4" /> {user.email}
                                        {!!user.email_verified && <CheckCircle2 className="w-4 h-4 text-green-500 ml-1" />}
                                    </div>
                                    <div className="flex items-center gap-1.5">
                                        <Calendar className="w-4 h-4" /> Joined: {new Date(user.created_at).toLocaleDateString()}
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className="mt-5 flex justify-center sm:mt-0 gap-3">
                            <button
                                onClick={handleForcePasswordReset}
                                disabled={resetLoading}
                                className="inline-flex items-center gap-2 px-4 py-2 bg-white border border-red-200 rounded-lg text-sm font-medium text-red-600 hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 shadow-sm transition-colors disabled:opacity-50"
                            >
                                <Key className="w-4 h-4" /> Reset Password
                            </button>
                            <button className="px-4 py-2 bg-blue-600 border border-transparent rounded-lg text-sm font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 shadow-sm transition-colors">
                                Edit Profile
                            </button>
                        </div>
                    </div>

                    {/* Feedback Toast */}
                    {feedback && (
                        <div className={`mt-6 p-4 rounded-lg flex items-start gap-3 border ${feedback.type === 'success' ? 'bg-green-50 border-green-200 text-green-800' : 'bg-red-50 border-red-200 text-red-800'
                            }`}>
                            {feedback.type === 'success' ? <CheckCircle2 className="w-5 h-5 shrink-0" /> : <AlertCircle className="w-5 h-5 shrink-0" />}
                            <div className="flex-1">
                                <p className="font-medium text-sm">{feedback.message}</p>
                                {feedback.link && (
                                    <div className="mt-2 bg-white p-2 rounded border border-green-200 text-xs font-mono break-all selection:bg-green-200 selectable">
                                        Reset Link to Share: <br /> {feedback.link}
                                    </div>
                                )}
                            </div>
                            <button onClick={() => setFeedback(null)} className="opacity-50 hover:opacity-100">
                                <span className="sr-only">Dismiss</span>
                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                            </button>
                        </div>
                    )}
                </div>

                {/* 8-Tab Navigation */}
                <div className="border-t border-slate-200 bg-slate-50/50">
                    <div className="px-6 overflow-x-auto">
                        <nav className="-mb-px flex space-x-8" aria-label="Tabs">
                            {TABS.map((tab) => (
                                <button
                                    key={tab.id}
                                    onClick={() => setActiveTab(tab.id)}
                                    className={`
                                        whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm flex items-center gap-2 transition-colors
                                        ${activeTab === tab.id
                                            ? 'border-blue-500 text-blue-600'
                                            : 'border-transparent text-slate-500 hover:text-slate-700 hover:border-slate-300'
                                        }
                                    `}
                                >
                                    <tab.icon className={`w-4 h-4 ${activeTab === tab.id ? 'text-blue-500' : 'text-slate-400'}`} />
                                    {tab.label}
                                </button>
                            ))}
                        </nav>
                    </div>
                </div>
            </div>

            {/* Tab Contents */}
            <div className="mt-6">
                {activeTab === 'overview' && <OverviewTab user={user} />}
                {activeTab === 'profile' && <ProfileTab user={user} />}
                {activeTab === 'activity' && <ActivityTab userId={user.id} />}
                {/* Other tabs omitted for brevity, fallback */}
                {['jobs', 'messages', 'payments', 'security', 'reports'].includes(activeTab) && (
                    <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-12 text-center text-slate-500">
                        {TABS.find(t => t.id === activeTab)?.label} Module - Under Construction
                    </div>
                )}
            </div>

        </div>
    );
}
