'use client';

import { AlertDescription } from '@/components/ui/alert';
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 {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { api } from '@/lib/api';
import { useAuthStore } from '@/lib/auth-store';
import { API_BASE_URL } from '@/lib/constants';
import { useLanguage } from '@/lib/language-context';
import { Infinity } from 'lucide-react';
import React, { useEffect, useState } from 'react';

interface Doctor {
    _id?: string;
    userId?: string; // User's _id (needed for subscription lookup/update)
    firstName: string;
    lastName: string;
    email: string;
    isDentist: boolean;
    phone?: string;
    licenseNumber?: string;
}

interface Plan {
    _id: string;
    title: string;
    price: number;
    period: string;
}

interface SubscriptionResponse {
    planId?: string | Plan | null;
}

interface DoctorFormProps {
    initialData?: Doctor | null;
    onSuccess?: () => void;
    onCancel?: () => void;
    isAdmin?: boolean;
}

export default function DoctorForm({ initialData, onSuccess, onCancel, isAdmin }: DoctorFormProps) {
    const { t } = useLanguage();
    const { token } = useAuthStore();
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [success, setSuccess] = useState<string | null>(null);
    const [plans, setPlans] = useState<Plan[]>([]);
    const [selectedPlanId, setSelectedPlanId] = useState<string>('none');
    const [currentSubPlan, setCurrentSubPlan] = useState<Plan | null>(null);
    const [currentSubPlanId, setCurrentSubPlanId] = useState<string | null>(null);
    const [subLoading, setSubLoading] = useState(false);

    const isEditing = !!initialData;

    const [formData, setFormData] = useState<Doctor>(() => ({
        firstName: initialData?.firstName || '',
        lastName: initialData?.lastName || '',
        email: initialData?.email || '',
        isDentist: initialData?.isDentist || false,
        phone: initialData?.phone || '',
        licenseNumber: initialData?.licenseNumber || '',
    }));

    useEffect(() => {
        if (initialData) {
            setFormData({
                firstName: initialData.firstName,
                lastName: initialData.lastName,
                email: initialData.email,
                isDentist: initialData.isDentist || false,
                phone: initialData.phone || '',
                licenseNumber: initialData.licenseNumber || '',
            });
        } else {
            setFormData({ firstName: '', lastName: '', email: '', isDentist: false, phone: '', licenseNumber: '' });
        }
    }, [initialData]);

    // Fetch plans for admins
    useEffect(() => {
        if (isAdmin && token) {
            api.admin.getPlans(token).then((res) => {
                if (res.success && res.data) {
                    setPlans(res.data as Plan[]);
                }
            });
        }
    }, [isAdmin, token]);

    // When editing, fetch the doctor's current subscription to pre-select the plan
    useEffect(() => {
        if (isAdmin && isEditing && initialData?.userId && token) {
            console.log('[DoctorForm] Fetching subscription for userId:', initialData.userId);
            setSubLoading(true);
            api.admin.getSubscription(token, initialData.userId).then((res) => {
                console.log('[DoctorForm] Subscription response:', res);
                if (res.success && res.data) {
                    const sub = res.data as SubscriptionResponse;
                    const rawPlan = sub.planId;
                    const resolvedPlanId = typeof rawPlan === 'string' ? rawPlan : rawPlan?._id;

                    if (resolvedPlanId) {
                        setCurrentSubPlanId(resolvedPlanId);
                        setSelectedPlanId(resolvedPlanId);

                        if (typeof rawPlan === 'object' && rawPlan?._id) {
                            setCurrentSubPlan(rawPlan);
                        } else {
                            setCurrentSubPlan(null);
                        }
                    }
                }
            }).finally(() => setSubLoading(false));
        } else {
            console.log('[DoctorForm] Subscription fetch skipped — isAdmin:', isAdmin, 'isEditing:', isEditing, 'userId:', initialData?.userId, 'hasToken:', !!token);
            if (!isEditing) {
                setSelectedPlanId('none');
                setCurrentSubPlan(null);
                setCurrentSubPlanId(null);
            }
        }
    }, [isAdmin, isEditing, initialData?.userId, token]);

    useEffect(() => {
        if (!currentSubPlan && currentSubPlanId && plans.length > 0) {
            const planFromList = plans.find((plan) => plan._id === currentSubPlanId) || null;
            if (planFromList) {
                setCurrentSubPlan(planFromList);
            }
        }
    }, [currentSubPlan, currentSubPlanId, plans]);


    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
    };

    const handleSelectChange = (name: string, value: string) => {
        setFormData({
            ...formData,
            [name]: value === 'true' ? true : value === 'false' ? false : value,
        });
    };

    const handleSubmit = async (e: React.SyntheticEvent<HTMLFormElement>) => {
        e.preventDefault();
        setLoading(true);
        setError(null);
        setSuccess(null);

        const url = initialData?._id
            ? `${API_BASE_URL}/api/doctors/${initialData._id}`
            : `${API_BASE_URL}/api/doctors`;
        const method = initialData?._id ? 'PUT' : 'POST';

        const body: Record<string, unknown> = { ...formData };
        if (!isEditing && selectedPlanId && selectedPlanId !== 'none') {
            body.planId = selectedPlanId;
        }

        try {
            const response = await fetch(url, {
                method,
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(body),
            });
            const data = await response.json();

            if (!response.ok) {
                setError(data.error || t('doctors.failedToSaveDoctor'));
                setLoading(false);
                return;
            }

            // If editing + admin + plan changed → update subscription separately
            if (isEditing && isAdmin && initialData?.userId && selectedPlanId && selectedPlanId !== 'none' && token) {
                const currentPlanId = currentSubPlanId || currentSubPlan?._id;
                if (selectedPlanId !== currentPlanId) {
                    const subRes = await api.admin.updateSubscription(token, initialData.userId, selectedPlanId);
                    if (!subRes.success) {
                        setError(`${t('doctors.doctorSavedSubFailed')}: ${subRes.error}`);
                        setLoading(false);
                        return;
                    }
                }
            }

            setSuccess(isEditing ? t('doctors.doctorUpdatedSuccess') : t('doctors.doctorCreatedSuccess'));
            setTimeout(() => { onSuccess?.(); }, 1500);
        } catch (err: unknown) {
            const errorMessage = err instanceof Error ? err.message : t('doctors.errorSavingDoctor');
            setError(errorMessage);
        } finally {
            setLoading(false);
        }
    };

    return (
        <Card className="border-0 shadow-none">
            <CardContent className="px-0">
                {error && (
                    <div className="mb-6 p-4 rounded-lg bg-red-50 border border-red-200">
                        <AlertDescription className="text-red-700 font-medium">{error}</AlertDescription>
                    </div>
                )}
                {success && (
                    <div className="mb-6 p-4 rounded-lg bg-green-50 border border-green-200">
                        <AlertDescription className="text-green-700 font-medium">{success}</AlertDescription>
                    </div>
                )}

                <form onSubmit={handleSubmit} className="space-y-6">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <Label htmlFor="firstName">{t('auth.firstName')}</Label>
                            <Input id="firstName" name="firstName" value={formData.firstName} onChange={handleChange} className="h-12" required />
                        </div>
                        <div>
                            <Label htmlFor="lastName">{t('auth.lastName')}</Label>
                            <Input id="lastName" name="lastName" value={formData.lastName} onChange={handleChange} className="h-12" required />
                        </div>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <Label htmlFor="email">{t('common.email')}</Label>
                            <Input id="email" name="email" type="email" value={formData.email} onChange={handleChange} className="h-12" required disabled={isEditing} />
                        </div>
                        <div>
                            <Label htmlFor="phone">{t('common.phone')}</Label>
                            <Input id="phone" name="phone" value={formData.phone} onChange={handleChange} className="h-12" />
                        </div>
                    </div>

                    <div>
                        <Label className="mb-3 block">{t('doctors.isDentist')}</Label>
                        <div className="flex gap-4">
                            <label className={`flex-1 relative border rounded-lg p-4 cursor-pointer hover:bg-gray-50 transition-all ${!formData.isDentist ? 'border-cyan-500 bg-cyan-50 ring-1 ring-cyan-500' : 'border-gray-200'}`}>
                                <input type="radio" className="sr-only" checked={!formData.isDentist} onChange={() => handleSelectChange('isDentist', 'false')} />
                                <div className="flex items-center justify-center gap-2">
                                    <span className={`font-medium ${!formData.isDentist ? 'text-cyan-700' : 'text-gray-600'}`}>{t('doctors.doctorType')}</span>
                                </div>
                            </label>
                            <label className={`flex-1 relative border rounded-lg p-4 cursor-pointer hover:bg-gray-50 transition-all ${formData.isDentist ? 'border-cyan-500 bg-cyan-50 ring-1 ring-cyan-500' : 'border-gray-200'}`}>
                                <input type="radio" className="sr-only" checked={formData.isDentist} onChange={() => handleSelectChange('isDentist', 'true')} />
                                <div className="flex items-center justify-center gap-2">
                                    <span className={`font-medium ${formData.isDentist ? 'text-cyan-700' : 'text-gray-600'}`}>{t('doctors.dentistType')}</span>
                                </div>
                            </label>
                        </div>
                    </div>

                    <div>
                        <Label htmlFor="licenseNumber">{t('doctors.licenseNumber')}</Label>
                        <Input id="licenseNumber" name="licenseNumber" value={formData.licenseNumber} onChange={handleChange} className="h-12" />
                    </div>

                    {/* Admin-only: Plan assignment / change */}
                    {isAdmin && (
                        <div className="space-y-3">
                            <Label className="block text-sm font-semibold">{t('doctors.subscriptionPlan')}</Label>

                            {/* Current subscription card — shown when editing */}
                            {isEditing && (
                                <div className={`rounded-lg border p-3 flex items-center gap-3 ${subLoading ? 'bg-gray-50 border-gray-200 animate-pulse' :
                                    currentSubPlan ? (
                                        currentSubPlan.price === 0 || currentSubPlan.period === 'freely'
                                            ? 'bg-green-50 border-green-200'
                                            : 'bg-blue-50 border-blue-200'
                                    ) : currentSubPlanId
                                        ? 'bg-slate-50 border-slate-200'
                                        : 'bg-amber-50 border-amber-200'
                                    }`}>
                                    {subLoading ? (
                                        <div className="flex items-center gap-2 text-sm text-muted-foreground">
                                            <div className="w-4 h-4 border-2 border-gray-300 border-t-transparent rounded-full animate-spin" />
                                            {t('doctors.loadingSubscription')}
                                        </div>
                                    ) : currentSubPlan ? (
                                        <>
                                            {(currentSubPlan.price === 0 || currentSubPlan.period === 'freely') ? (
                                                <span className="inline-flex items-center gap-1 text-xs bg-green-200 text-green-800 px-2 py-1 rounded-full font-bold shrink-0">
                                                    <Infinity className="w-3 h-3" /> {t('doctors.freeForever')}
                                                </span>
                                            ) : (
                                                <span className="inline-flex items-center text-xs bg-blue-200 text-blue-800 px-2 py-1 rounded-full font-bold shrink-0">
                                                    {t('doctors.paid')}
                                                </span>
                                            )}
                                            <div className="min-w-0">
                                                <p className="text-sm font-semibold text-gray-800 leading-tight">{currentSubPlan.title}</p>
                                                <p className="text-xs text-muted-foreground">
                                                    {currentSubPlan.price === 0 || currentSubPlan.period === 'freely'
                                                        ? t('doctors.doesNotExpire')
                                                        : `$${currentSubPlan.price} / ${currentSubPlan.period}`}
                                                </p>
                                            </div>
                                            <span className="ml-auto text-xs text-muted-foreground italic shrink-0">{t('doctors.current')}</span>
                                        </>
                                    ) : currentSubPlanId ? (
                                        <p className="text-sm text-slate-700 font-medium">{t('doctors.subscriptionAssigned')}</p>
                                    ) : (
                                        <p className="text-sm text-amber-700 font-medium">{t('doctors.noSubscriptionAssigned')}</p>
                                    )}
                                </div>
                            )}

                            {/* Change plan dropdown */}
                            <Select value={selectedPlanId} onValueChange={setSelectedPlanId} disabled={subLoading}>
                                <SelectTrigger className="h-12">
                                    <SelectValue placeholder={isEditing ? t('doctors.changePlan') : t('doctors.selectAPlan')} />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="none">
                                        <span className="text-slate-500">
                                            {isEditing ? t('doctors.keepCurrentPlan') : t('doctors.noPlanDefault')}
                                        </span>
                                    </SelectItem>
                                    {plans.map((plan) => {
                                        const isFree = plan.price === 0 || plan.period === 'freely';
                                        return (
                                            <SelectItem key={plan._id} value={plan._id}>
                                                <span className="flex items-center gap-2">
                                                    {isFree && (
                                                        <span className="inline-flex items-center gap-1 text-xs bg-green-100 text-green-700 px-1.5 py-0.5 rounded-full font-semibold">
                                                            <Infinity className="w-3 h-3" />
                                                            {t('doctors.freeForever')}
                                                        </span>
                                                    )}
                                                    {plan.title}
                                                    {!isFree && (
                                                        <span className="text-xs text-muted-foreground">
                                                            — ${plan.price}/{plan.period}
                                                        </span>
                                                    )}
                                                </span>
                                            </SelectItem>
                                        );
                                    })}
                                </SelectContent>
                            </Select>
                            {/* Hint when a plan is selected */}
                            {selectedPlanId && selectedPlanId !== 'none' && (() => {
                                const plan = plans.find(p => p._id === selectedPlanId);
                                const isFree = plan && (plan.price === 0 || plan.period === 'freely');
                                const isChanged = isEditing && selectedPlanId !== (currentSubPlanId || currentSubPlan?._id);
                                if (!plan) return null;
                                return (
                                    <p className={`text-xs flex items-center gap-1 ${isFree ? 'text-green-600' : 'text-blue-600'}`}>
                                        {isFree ? <Infinity className="w-3 h-3" /> : null}
                                        {isFree ? t('doctors.lifetimeAccess') : `${plan.title} ${t('doctors.assignedFor1Year')}`}
                                        {isEditing && isChanged && (
                                            <span className="ml-1 text-amber-600 font-medium">{t('doctors.willUpdateOnSave')}</span>
                                        )}
                                    </p>
                                );
                            })()}
                        </div>
                    )}

                    <div className="flex justify-end gap-2">
                        {onCancel && (
                            <Button type="button" variant="outline" onClick={onCancel} className="h-12">
                                {t('common.cancel')}
                            </Button>
                        )}
                        <Button type="submit" disabled={loading} className="h-12">
                            {loading ? t('common.saving') : (isEditing ? t('doctors.updateDoctor') : t('doctors.createDoctor'))}
                        </Button>
                    </div>
                </form>
            </CardContent>
        </Card >
    );
}
