'use client';

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { api } from '@/lib/api';
import { useLanguage } from '@/lib/language-context';
import { ShieldAlert, Trash2, UserPlus } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import ConfirmDialog from '@/components/common/ConfirmDialog';

interface TeamMember {
    _id: string;
    firstName: string;
    lastName: string;
    email: string;
    specialization: string;
    licenseNumber: string;
    isOwner: boolean;
}

import { useAuthStore } from '@/lib/auth-store';

export default function TeamManagementPage() {
    const { t } = useLanguage();
    const { token, user } = useAuthStore();
    const router = useRouter();
    const [team, setTeam] = useState<TeamMember[]>([]);
    const [loading, setLoading] = useState(true);
    const [isAdding, setIsAdding] = useState(false);
    const [isAddingDoctor, setIsAddingDoctor] = useState(false);
    const [deletingDoctorId, setDeletingDoctorId] = useState<string | null>(null);
    const [pendingDeleteDoctor, setPendingDeleteDoctor] = useState<TeamMember | null>(null);
    const getDoctorLimitFromPlan = (plan: any): number => {
        if (!plan) return 0;

        const period = String(plan.period || '').toLowerCase();
        const title = String(plan.title || '').toLowerCase();

        const isAnnualPlan =
            period === 'annual' ||
            period === '12-month' ||
            title.includes('annual') ||
            title.includes('yearly') ||
            title.includes('12 month');

        if (isAnnualPlan) return 5;

        const isSixMonthPlan =
            period === '6-month' ||
            title.includes('6 month');

        if (isSixMonthPlan) return 2;

        return 0;
    };

    // Form State
    const [formData, setFormData] = useState({
        firstName: '',
        lastName: '',
        email: '',
        specialization: '',
        licenseNumber: '',
    });

    const fetchTeam = async () => {
        try {
            if (!token) return;
            const res = await api.team.get(token);
            if (res.success && Array.isArray(res.data)) {
                setTeam(res.data);
            }
        } catch (error) {
            console.error('Error fetching team:', error);
        } finally {
            setLoading(false);
        }
    };



    const handleAddDoctor = async (e: React.SyntheticEvent<HTMLFormElement>) => {
        e.preventDefault();
        if (isAddingDoctor) return;
        try {
            if (!token) return;
            setIsAddingDoctor(true);
            const res = await api.team.add(token, formData);

            if (res.success) {
                toast.success(t('team.doctorAddedSuccess'));
                setIsAdding(false);
                fetchTeam();
                setFormData({
                    firstName: '',
                    lastName: '',
                    email: '',
                    specialization: '',
                    licenseNumber: '',
                });
            } else {
                // Extract error message from various possible locations in the response
                const errorMessage = res.error || res.msg || res.data?.error || res.data?.msg || t('team.doctorAddFailed');
                toast.error(errorMessage);
            }
        } catch (error: any) {
            console.error('Error adding doctor:', error);
            toast.error(error.message || t('team.doctorAddFailed'));
        } finally {
            setIsAddingDoctor(false);
        }
    };

    const handleUpgrade = async () => {
        router.push('/subscription');
    };

    const handleDeleteDoctor = async (member: TeamMember) => {
        if (member.isOwner) return;
        setPendingDeleteDoctor(member);
    };

    const confirmDeleteDoctor = async () => {
        if (!token || !pendingDeleteDoctor) return;
        try {
            setDeletingDoctorId(pendingDeleteDoctor._id);
            const res = await api.team.remove(token, pendingDeleteDoctor._id);
            if (res.success) {
                toast.success(t('common.deleted'));
                setTeam((prev) => prev.filter((doctor) => doctor._id !== pendingDeleteDoctor._id));
                setPendingDeleteDoctor(null);
            } else {
                toast.error(res.error || res.msg || t('common.error'));
            }
        } catch (error: any) {
            toast.error(error.message || t('common.error'));
        } finally {
            setDeletingDoctorId(null);
        }
    };

    const [maxDoctorsAllowed, setMaxDoctorsAllowed] = useState(0);

    const checkSubscription = async () => {
        if (!token || !user) return;

        // If user is not an owner, they can't add members regardless of plan
        if (user.ownerId) {
            setMaxDoctorsAllowed(0);
            return;
        }

        try {
            const res = await api.subscription.getMySubscription(token);
            if (res.success) {
                const subscriptions = Array.isArray(res.data) ? res.data : (res.data ? [res.data] : []);

                // Check active subscription and map it to allowed doctor seats
                const allowedDoctors = subscriptions.reduce((maxAllowed: number, sub: any) => {
                    const plan = sub.planId;
                    const isNotExpired = sub.endDate ? new Date(sub.endDate) > new Date() : true;
                    if (!plan || sub.status !== 'Active' || !isNotExpired) return maxAllowed;

                    return Math.max(maxAllowed, getDoctorLimitFromPlan(plan));
                }, 0);

                setMaxDoctorsAllowed(allowedDoctors);
            } else {
                setMaxDoctorsAllowed(0);
            }
        } catch (error) {
            console.error('Error checking subscription:', error);
            setMaxDoctorsAllowed(0);
        }
    };

    useEffect(() => {
        if (user?.userType === 'admin') {
            toast.error(t('team.notAllowed'));
            router.replace('/dashboard');
            setLoading(false);
            return;
        }

        fetchTeam();
        checkSubscription();
    }, [token, user, router]);

    if (user?.userType === 'admin') {
        return null;
    }

    const currentAddedDoctors = team.filter((member) => !member.isOwner).length;
    const canAddMembers = maxDoctorsAllowed > 0 && currentAddedDoctors < maxDoctorsAllowed;
    const canManageTeam = !!user && !user.ownerId;
    // Show upgrade prompt for no plan or lower tiers; hide only at the highest tier.
    const canUpgradeSeats = canManageTeam && maxDoctorsAllowed < 5;

    return (
        <div className="space-y-6">
            <div className="flex justify-between items-center">
                <h1 className="text-3xl font-bold tracking-tight">{t('team.title')}</h1>
                {canAddMembers && (
                    <Button onClick={() => setIsAdding(!isAdding)} className="bg-cyan-600 hover:bg-cyan-700">
                        <UserPlus className="mr-2 h-4 w-4" /> {t('team.addDoctor')}
                    </Button>
                )}
            </div>

            {isAdding && canAddMembers && (
                <Card className="mb-8 border-cyan-100 shadow-md">
                    <CardHeader className="bg-cyan-50/50 pb-4">
                        <div className="flex justify-between items-center">
                            <CardTitle className="text-cyan-900">{t('team.addNewDoctor')}</CardTitle>
                            <Button variant="ghost" size="sm" onClick={() => setIsAdding(false)}>{t('common.close')}</Button>
                        </div>
                    </CardHeader>
                    <CardContent className="pt-6">
                        <form onSubmit={handleAddDoctor} className="space-y-4">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label htmlFor="firstName">{t('common.firstName')}</Label>
                                    <Input
                                        id="firstName"
                                        value={formData.firstName}
                                        onChange={e => setFormData({ ...formData, firstName: e.target.value })}
                                        required
                                        placeholder={t('auth.firstNamePlaceholder')}
                                    />
                                </div>
                                <div className="space-y-2">
                                    <Label htmlFor="lastName">{t('common.lastName')}</Label>
                                    <Input
                                        id="lastName"
                                        value={formData.lastName}
                                        onChange={e => setFormData({ ...formData, lastName: e.target.value })}
                                        required
                                        placeholder={t('auth.lastNamePlaceholder')}
                                    />
                                </div>
                            </div>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label htmlFor="email">{t('common.email')}</Label>
                                    <Input
                                        id="email"
                                        type="email"
                                        value={formData.email}
                                        onChange={e => setFormData({ ...formData, email: e.target.value })}
                                        required
                                        placeholder={t('auth.emailPlaceholder')}
                                    />
                                </div>
                                <div className="space-y-2">
                                    <Label htmlFor="specialization">{t('profile.specialization')}</Label>
                                    <Input
                                        id="specialization"
                                        value={formData.specialization}
                                        onChange={e => setFormData({ ...formData, specialization: e.target.value })}
                                        required
                                        placeholder={t('profile.specializationPlaceholder')}
                                    />
                                </div>
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="licenseNumber">{t('common.license')}</Label>
                                <Input
                                    id="licenseNumber"
                                    value={formData.licenseNumber}
                                    onChange={e => setFormData({ ...formData, licenseNumber: e.target.value })}
                                    placeholder={t('profile.licenseNumberPlaceholder')}
                                />
                            </div>

                            <div className="flex justify-end gap-3 pt-2">
                                <Button type="button" variant="outline" onClick={() => setIsAdding(false)}>{t('common.cancel')}</Button>
                                <Button type="submit" disabled={isAddingDoctor} className="bg-cyan-600 hover:bg-cyan-700 text-white shadow-sm">
                                    <UserPlus className="w-4 h-4 mr-2" />
                                    {isAddingDoctor ? t('common.saving') : t('team.createAccount')}
                                </Button>
                            </div>
                        </form>
                    </CardContent>
                </Card>
            )}

            <Card>
                <CardHeader>
                    <CardTitle>{t('team.teamMembers')}</CardTitle>
                </CardHeader>
                <CardContent>
                    <div className="rounded-md border overflow-x-auto">
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead>{t('common.name')}</TableHead>
                                    <TableHead>{t('common.email')}</TableHead>
                                    <TableHead>{t('common.role')}</TableHead>
                                    <TableHead>{t('profile.specialization')}</TableHead>
                                    <TableHead>{t('common.license')}</TableHead>
                                    <TableHead>{t('common.status')}</TableHead>
                                    <TableHead>{t('common.actions')}</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {loading ? (
                                    <TableRow>
                                        <TableCell colSpan={7} className="text-center py-4">{t('common.loading')}</TableCell>
                                    </TableRow>
                                ) : team.map((member) => (
                                    <TableRow key={member._id}>
                                        <TableCell className="font-medium whitespace-nowrap">
                                            {member.firstName} {member.lastName}
                                            {!member.isOwner && <span className="ml-2 text-xs bg-slate-100 text-slate-600 px-2 py-0.5 rounded-full">{t('common.doctor')}</span>}
                                            {member.isOwner && <span className="ml-2 text-xs bg-cyan-100 text-cyan-800 px-2 py-0.5 rounded-full">{t('common.owner')}</span>}
                                        </TableCell>
                                        <TableCell>{member.email}</TableCell>
                                        <TableCell>{member.isOwner ? t('common.administrator') : t('common.doctor')}</TableCell>
                                        <TableCell>{member.specialization}</TableCell>
                                        <TableCell>{member.licenseNumber}</TableCell>
                                        <TableCell>
                                            <div className="flex items-center gap-2">
                                                <div className="w-2 h-2 rounded-full bg-green-500" />
                                                {t('common.active')}
                                            </div>
                                        </TableCell>
                                        <TableCell>
                                            {canManageTeam && !member.isOwner && (
                                                <Button
                                                    variant="ghost"
                                                    size="sm"
                                                    className="text-red-600 hover:text-red-700 hover:bg-red-50"
                                                    onClick={() => handleDeleteDoctor(member)}
                                                    disabled={deletingDoctorId === member._id}
                                                >
                                                    <Trash2 className="w-4 h-4 mr-1" />
                                                    {t('common.delete')}
                                                </Button>
                                            )}
                                        </TableCell>
                                    </TableRow>
                                ))}
                                {team.length === 0 && !loading && (
                                    <TableRow>
                                        <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                                            {t('team.noMembers')}
                                        </TableCell>
                                    </TableRow>
                                )}
                            </TableBody>
                        </Table>
                    </div>

                    {canUpgradeSeats && (
                        <div className="mt-8 p-4 bg-slate-50 rounded-lg border border-slate-200">
                            <div className="flex flex-col sm:flex-row items-center gap-4 text-center sm:text-left">
                                <div className="p-2 bg-yellow-100 rounded-full shrink-0">
                                    <ShieldAlert className="w-6 h-6 text-yellow-600" />
                                </div>
                                <div className="flex-1">
                                    <h4 className="font-semibold text-slate-800">{t('team.needMoreSeats')}</h4>
                                    <p className="text-sm text-slate-600">{t('team.upgradePlanDescription')}</p>
                                </div>
                                <Button variant="secondary" className="w-full sm:w-auto mt-2 sm:mt-0" onClick={handleUpgrade}>
                                    {t('team.upgradePlan')}
                                </Button>
                            </div>
                        </div>
                    )}
                </CardContent>
            </Card>

            <ConfirmDialog
                open={!!pendingDeleteDoctor}
                onOpenChange={(open) => !open && setPendingDeleteDoctor(null)}
                title={t('common.confirmDelete')}
                confirmLabel={t('common.delete')}
                cancelLabel={t('common.cancel')}
                loading={deletingDoctorId === pendingDeleteDoctor?._id}
                onConfirm={confirmDeleteDoctor}
            />
        </div>
    );
}
