/**
 * Centralized API service for all User Panel pages.
 * Each function calls the Laravel backend and returns typed data.
 */

const getApiUrl = () => {
    const url = process.env.NEXT_PUBLIC_API_URL;
    if (!url) throw new Error('NEXT_PUBLIC_API_URL is not set');
    return url;
};

const authHeaders = (token: string) => ({
    'Accept': 'application/json',
    'Authorization': `Bearer ${token}`,
});

// ===================== NOTIFICATIONS =====================

export interface NotificationItem {
    id: number;
    title: string;
    message: string;
    type: string | null;
    read: boolean;
    createdAt: string;
}

export async function getNotifications(token: string): Promise<NotificationItem[]> {
    try {
        const res = await fetch(`${getApiUrl()}/user/notifications`, {
            headers: authHeaders(token),
            cache: 'no-store',
        });
        if (!res.ok) return [];
        const json = await res.json();
        const data = json.data?.data || json.data || [];
        if (!Array.isArray(data)) return [];
        return data.map((n: any) => ({
            id: n.id,
            title: n.title || '',
            message: n.message || '',
            type: n.type || null,
            read: !!n.read,
            createdAt: n.created_at || '',
        }));
    } catch (e) {
        console.error('Error fetching notifications:', e);
        return [];
    }
}

export async function markNotificationRead(token: string, id: number): Promise<boolean> {
    try {
        const res = await fetch(`${getApiUrl()}/user/notifications/${id}/read`, {
            method: 'PATCH',
            headers: { ...authHeaders(token), 'Content-Type': 'application/json' },
        });
        return res.ok;
    } catch { return false; }
}

export async function markAllNotificationsRead(token: string): Promise<boolean> {
    try {
        const res = await fetch(`${getApiUrl()}/user/notifications/read-all`, {
            method: 'PATCH',
            headers: { ...authHeaders(token), 'Content-Type': 'application/json' },
        });
        return res.ok;
    } catch { return false; }
}

// ===================== FAVORITES =====================

export interface FavoriteProperty {
    id: number;          // favorite record id
    propertyId: number;
    title: string;
    subtitle: string;
    image: string;
    price: string;
    area: number;
    bedrooms: number;
    bathrooms: number;
    floors: number;
    badge: string;
    company: string;
    companyLogo: string;
    typeOfProperty: string;     // discriminator: 'project' vs others
    section: string;            // 'sale' | 'rent'
    isPremium: boolean;
    createdAt: string;
}

export async function getFavorites(token: string): Promise<FavoriteProperty[]> {
    try {
        const res = await fetch(`${getApiUrl()}/user/favorites`, {
            headers: authHeaders(token),
            cache: 'no-store',
        });
        if (!res.ok) return [];
        const json = await res.json();
        const data = json.data?.data || json.data || [];
        if (!Array.isArray(data)) return [];
        return data.map((fav: any) => {
            const p = fav.property || {};
            const priceNum = parseFloat(p.price || '0');
            return {
                id: fav.id,
                propertyId: p.id,
                title: p.title || '',
                subtitle: p.address || '',
                image: p.images?.[0]?.url || '/no-image.png',
                price: priceNum.toLocaleString(),
                area: parseInt(p.spaces || '0', 10) || 0,
                bedrooms: parseInt(p.room || '0', 10) || 0,
                bathrooms: parseInt(p.bathroom || '0', 10) || 0,
                floors: parseInt(p.floor || '0', 10) || 0,
                badge: Number(p.is_premium) === 1 ? 'مميز' : '',
                company: p.owner?.name || '',
                companyLogo: p.owner?.avatar || '/placeholder-avatar.png',
                typeOfProperty: p.type_of_property || '',
                section: (p.section || '').includes('sale') ? 'sale' : 'rent',
                isPremium: Number(p.is_premium) === 1,
                createdAt: fav.created_at || '',
            };
        });
    } catch (e) {
        console.error('Error fetching favorites:', e);
        return [];
    }
}

// ===================== INTERESTS =====================

export interface InterestData {
    id?: number;
    cityIds: number[];
    governorateIds: number[];
    districtIds: number[];
    cityNames?: string[];
}

export async function getInterests(token: string): Promise<InterestData | null> {
    try {
        const res = await fetch(`${getApiUrl()}/user/interests/show`, {
            headers: authHeaders(token),
            cache: 'no-store',
        });
        if (!res.ok) return null;
        const json = await res.json();
        const d = json.data?.data || json.data;
        if (!d) return null;
        return {
            id: d.id,
            cityIds: d.city_ids || [],
            governorateIds: d.governorate_ids || [],
            districtIds: d.district_ids || [],
        };
    } catch (e) {
        console.error('Error fetching interests:', e);
        return null;
    }
}

export async function saveInterests(token: string, data: { city_ids: number[]; governorate_ids: number[]; district_ids: number[] }): Promise<boolean> {
    try {
        const res = await fetch(`${getApiUrl()}/user/interests`, {
            method: 'POST',
            headers: { ...authHeaders(token), 'Content-Type': 'application/json' },
            body: JSON.stringify(data),
        });
        return res.ok;
    } catch { return false; }
}

// ===================== MARKETING PROPERTIES (Requests Page) =====================

export interface MarketingPropertyListItem {
    id: number;
    title: string;
    city: string;
    status: string;
    statusDisplay: string;
    price: number;
    img: string;
}

const MARKETING_STATUS_MAP: Record<string, string> = {
    'draft': 'مسودة',
    'pending': 'تحت المراجعة',
    'paid': 'تم الدفع',
    'payment_failed': 'فشل الدفع',
};

export async function getMarketingProperties(token: string): Promise<MarketingPropertyListItem[]> {
    try {
        const res = await fetch(`${getApiUrl()}/user/marketing-properties`, {
            headers: authHeaders(token),
            cache: 'no-store',
        });
        if (!res.ok) return [];
        const json = await res.json();
        const data = json.data?.data || json.data || [];
        if (!Array.isArray(data)) return [];
        return data.map((m: any) => ({
            id: m.id,
            title: m.title || '',
            city: m.city?.name || m.address || '',
            status: m.status || 'draft',
            statusDisplay: MARKETING_STATUS_MAP[m.status] || m.status || 'مسودة',
            price: parseFloat(m.price || '0'),
            img: m.images?.[0]?.url || '/no-image.png',
        }));
    } catch (e) {
        console.error('Error fetching marketing properties:', e);
        return [];
    }
}



// ===================== TAWTHEEQ CONTRACTS (Contract Requests Page) =====================

export interface TawtheeqContractListItem {
    id: number;
    requestId: string;
    contractRequestId: string;
    status: string;
    statusDisplay: string;
    type: string;
    typeDisplay: string;
    img: string;
    rentAmount: number;
    propertyType: string;
}

const CONTRACT_STATUS_MAP: Record<string, string> = {
    'paid': 'تم الدفع',
    'payment_failed': 'فشل الدفع',
    'draft': 'مسودة',
    'pending': 'بانتظار المراجعة',
    'pending_review': 'بانتظار المراجعة',
    'property_update_required': 'تحديث بيانات العقار',
    'approved': 'مقبول',
    'rejected': 'مرفوض',
};

const CONTRACT_TYPE_MAP: Record<string, string> = {
    'residential': 'سكني',
    'commercial': 'تجاري',
};

export async function getTawtheeqContracts(token: string): Promise<TawtheeqContractListItem[]> {
    try {
        const res = await fetch(`${getApiUrl()}/user/tawtheeq-contracts`, {
            headers: authHeaders(token),
            cache: 'no-store',
        });
        if (!res.ok) return [];
        const json = await res.json();
        const data = json.data?.data || json.data || [];
        if (!Array.isArray(data)) return [];
        return data.map((c: any) => ({
            id: c.id,
            requestId: String(c.id),
            contractRequestId: c.lessor_id_number || String(c.id),
            status: c.status || 'draft',
            statusDisplay: CONTRACT_STATUS_MAP[c.status] || c.status || 'مسودة',
            type: c.type || 'residential',
            typeDisplay: CONTRACT_TYPE_MAP[c.type] || c.type || 'سكني',
            img: '/no-image.png',
            rentAmount: parseFloat(c.rent_amount || '0'),
            propertyType: c.property_type || '',
        }));
    } catch (e) {
        console.error('Error fetching tawtheeq contracts:', e);
        return [];
    }
}



// ===================== FINANCE REQUESTS =====================

export interface FinanceRequestListItem {
    id: number;
    fullName: string;
    occupation: string;
    status: string;
    statusDisplay: string;
    img: string;
    salary: number;
    bank: string;
}

const FINANCE_STATUS_MAP: Record<string, string> = {
    'completed': 'مكتمل',
    'reviewing': 'تحت المراجعة',
    'pending': 'تحت المراجعة',
    'approved': 'مكتمل',
    'rejected': 'مرفوض',
};

export async function getFinanceRequests(token: string): Promise<FinanceRequestListItem[]> {
    try {
        const res = await fetch(`${getApiUrl()}/user/client-finance-requests`, {
            headers: authHeaders(token),
            cache: 'no-store',
        });
        if (!res.ok) return [];
        const json = await res.json();
        const data = json.data?.data || json.data || [];
        if (!Array.isArray(data)) return [];
        return data.map((f: any) => ({
            id: f.id,
            fullName: f.name || '',
            occupation: f.job || '',
            status: f.status || 'reviewing',
            statusDisplay: FINANCE_STATUS_MAP[f.status] || f.status || 'تحت المراجعة',
            img: f.id_image || '/no-image.png',
            salary: parseFloat(f.salary || '0'),
            bank: f.bank || '',
        }));
    } catch (e) {
        console.error('Error fetching finance requests:', e);
        return [];
    }
}



// ===================== MY PROPERTIES (Expired Properties Page) =====================

export interface MyProperty {
    id: number;
    title: string;
    address: string;
    image: string;
    price: string;
    section: string;
    active: boolean;
    isExpired: boolean;
    daysUntilExpiration: number;
    expirationDate: string;
    area: number;
    bedrooms: number;
    bathrooms: number;
}

export async function getMyProperties(token: string): Promise<MyProperty[]> {
    try {
        const res = await fetch(`${getApiUrl()}/user/property/my-properties`, {
            headers: authHeaders(token),
            cache: 'no-store',
        });
        if (!res.ok) return [];
        const json = await res.json();
        const data = json.data?.data || json.data || [];
        if (!Array.isArray(data)) return [];
        return data.map((p: any) => ({
            id: p.id,
            title: p.title || '',
            address: p.address || '',
            image: p.images?.[0]?.url || '/no-image.png',
            price: parseFloat(p.price || '0').toLocaleString(),
            section: (p.section || '').includes('sale') ? 'sale' : 'rent',
            active: !!p.active,
            isExpired: p.expiration_info?.is_expired ?? false,
            daysUntilExpiration: p.expiration_info?.days_until_expiration ?? 0,
            expirationDate: p.expiration_info?.expiration_date || '',
            area: parseInt(p.spaces || '0', 10) || 0,
            bedrooms: parseInt(p.room || '0', 10) || 0,
            bathrooms: parseInt(p.bathroom || '0', 10) || 0,
        }));
    } catch (e) {
        console.error('Error fetching my properties:', e);
        return [];
    }
}

// ===================== PACKAGES (Plans Page) =====================

export interface PackageItemFeature {
    id: number;
    titleAr: string;
    titleEn: string;
    available: boolean;
}

export interface PackageData {
    id: number;
    titleAr: string;
    titleEn: string;
    type: string;
    descriptionAr: string;
    descriptionEn: string;
    tenantType: string;
    price: number;
    features: PackageItemFeature[];
}

export interface CurrentPackageInfo {
    hasPackage: boolean;
    packageId: number | null;
    startDate: string | null;
    endDate: string | null;
    packageName: string | null;
}

export async function getPackages(): Promise<PackageData[]> {
    try {
        const res = await fetch(`${getApiUrl()}/user/packages`, { cache: 'no-store' });
        if (!res.ok) return [];
        const json = await res.json();
        // Handle both {data: {data: [...]}} and {data: [...]} structures
        const data = Array.isArray(json.data) ? json.data : (json.data?.data || []);
        if (!Array.isArray(data)) return [];
        return data.map((pkg: any) => ({
            id: pkg.id,
            titleAr: pkg.ar_title || '',
            titleEn: pkg.en_title || '',
            type: pkg.type || 'monthly',
            descriptionAr: pkg.ar_description || '',
            descriptionEn: pkg.en_description || '',
            tenantType: pkg.tenant_type || 'normal',
            price: parseFloat(pkg.price || '0'),
            features: (pkg.package_items || pkg.items || []).map((item: any) => ({
                id: item.id,
                titleAr: item.ar_title || '',
                titleEn: item.en_title || '',
                available: item.pivot?.available ?? item.available ?? true,
            })),
        }));
    } catch (e) {
        console.error('Error fetching packages:', e);
        return [];
    }
}

export async function getCurrentPackageInfo(token: string): Promise<CurrentPackageInfo> {
    const defaultInfo: CurrentPackageInfo = { hasPackage: false, packageId: null, startDate: null, endDate: null, packageName: null };
    try {
        const res = await fetch(`${getApiUrl()}/user/current-package-info`, {
            headers: authHeaders(token),
            cache: 'no-store',
        });
        if (!res.ok) return defaultInfo;
        const json = await res.json();
        const d = json.data || json;
        return {
            hasPackage: !!d.has_package || !!d.package,
            packageId: d.package?.id || d.package_id || null,
            startDate: d.package_start_date || d.start_date || null,
            endDate: d.package_end_date || d.end_date || null,
            packageName: d.package?.ar_title || d.package?.en_title || null,
        };
    } catch (e) {
        console.error('Error fetching current package info:', e);
        return defaultInfo;
    }
}

// ===================== CHATS & MESSAGES =====================

export interface ChatMember {
    memberId: number;
    memberType: string;
    memberable: {
        name: string;
        username: string;
        avatar: string | null;
        clientType: string;
    };
}

export interface Chat {
    id: number;
    latestMessage?: {
        text: string;
        createdAt: string;
    };
    chatMembers: ChatMember[];
}

export interface Message {
    id: number;
    chatId: number;
    text: string;
    senderId: number;
    senderType: string;
    media: string | null;
    read: boolean;
    createdAt: string;
    sender: {
        name: string;
        username: string;
        avatar: string | null;
        clientType: string;
    };
}

export async function getChats(token: string): Promise<Chat[]> {
    try {
        const res = await fetch(`${getApiUrl()}/user/get-chats`, {
            headers: authHeaders(token),
            cache: 'no-store',
        });
        if (!res.ok) return [];
        const json = await res.json();
        const data = json.data || [];

        return data.map((d: any) => ({
            id: d.id,
            latestMessage: d.latest_message ? {
                text: d.latest_message.text,
                createdAt: d.latest_message.created_at,
            } : undefined,
            chatMembers: (d.chat_members || d.members || []).map((m: any) => ({
                memberId: m.member_id,
                memberType: m.member_type,
                memberable: {
                    name: m.name || m.username || 'مستخدم',
                    username: m.username || '',
                    avatar: m.avatar || null,
                    clientType: m.client_type || '',
                }
            }))
        }));
    } catch (e) {
        console.error('Error fetching chats:', e);
        return [];
    }
}

export async function getMessages(token: string, chatId: number): Promise<Message[]> {
    try {
        const res = await fetch(`${getApiUrl()}/user/chats/${chatId}/messages`, {
            headers: authHeaders(token),
            cache: 'no-store',
        });
        if (!res.ok) return [];
        const json = await res.json();
        const data = json.data || [];

        return data.map((d: any) => ({
            id: d.id,
            chatId: d.chat_id,
            text: d.text,
            senderId: d.sender_id,
            senderType: d.sender_type,
            media: d.media || null,
            read: !!d.read,
            createdAt: d.created_at,
            sender: {
                name: d.sender?.name || d.sender?.username || 'مستخدم',
                username: d.sender?.username || '',
                avatar: d.sender?.avatar || null,
                clientType: d.sender?.client_type || d.sender?.clientType || '',
            }
        }));
    } catch (e) {
        console.error('Error fetching messages:', e);
        return [];
    }
}

export async function sendMessage(token: string, chatId: number, text: string): Promise<Message | null> {
    try {
        const res = await fetch(`${getApiUrl()}/user/chats/${chatId}/messages`, {
            method: 'POST',
            headers: { ...authHeaders(token), 'Content-Type': 'application/json' },
            body: JSON.stringify({ text }),
        });
        if (!res.ok) return null;
        const json = await res.json();
        const d = json.data;
        if (!d) return null;

        return {
            id: d.id,
            chatId: d.chat_id,
            text: d.text,
            senderId: d.sender_id,
            senderType: d.sender_type,
            media: d.media || null,
            read: !!d.read,
            createdAt: d.created_at,
            sender: {
                name: d.sender?.name || d.sender?.username || 'مستخدم',
                username: d.sender?.username || '',
                avatar: d.sender?.avatar || null,
                clientType: d.sender?.client_type || d.sender?.clientType || '',
            }
        };
    } catch (e) {
        console.error('Error sending message:', e);
        return null;
    }
}

export async function getChatById(token: string, chatId: number): Promise<Chat | null> {
    try {
        const res = await fetch(`${getApiUrl()}/user/get-chats`, {
            headers: authHeaders(token),
            cache: 'no-store',
        });
        if (!res.ok) return null;
        const json = await res.json();
        const data = json.data || [];
        const chatData = data.find((d: any) => d.id === chatId);
        if (!chatData) return null;

        return {
            id: chatData.id,
            latestMessage: chatData.latest_message ? {
                text: chatData.latest_message.text,
                createdAt: chatData.latest_message.created_at,
            } : undefined,
            chatMembers: (chatData.chat_members || chatData.members || []).map((m: any) => ({
                memberId: m.member_id,
                memberType: m.member_type,
                memberable: {
                    name: m.name || m.username || 'مستخدم',
                    username: m.username || '',
                    avatar: m.avatar || null,
                    clientType: m.client_type || '',
                }
            }))
        };
    } catch (e) {
        console.error('Error fetching chat by ID:', e);
        return null;
    }
}

export async function markChatAsRead(token: string, chatId: number): Promise<boolean> {
    try {
        const res = await fetch(`${getApiUrl()}/user/chats/${chatId}/mark-as-read`, {
            method: 'PATCH',
            headers: authHeaders(token),
        });
        return res.ok;
    } catch { return false; }
}

// ===================== CREATION FUNCTIONS =====================

export async function createPropertyRequest(token: string, data: any): Promise<{ success: boolean; message?: string }> {
    try {
        const res = await fetch(`${getApiUrl()}/user/request/properties`, {
            method: 'POST',
            headers: { ...authHeaders(token), 'Content-Type': 'application/json' },
            body: JSON.stringify(data),
        });
        const json = await res.json();
        return { success: res.ok, message: json.message };
    } catch (e) {
        return { success: false, message: 'Failed to create request' };
    }
}

export async function createTawtheeqContract(token: string, formData: FormData): Promise<boolean> {
    try {
        const res = await fetch(`${getApiUrl()}/user/tawtheeq-contracts`, {
            method: 'POST',
            headers: authHeaders(token),
            body: formData,
        });
        return res.ok;
    } catch { return false; }
}

export async function createMarketingProperty(token: string, formData: FormData): Promise<{ success: boolean; data?: any; status?: number }> {
    try {
        const res = await fetch(`${getApiUrl()}/user/marketing-properties`, {
            method: 'POST',
            headers: authHeaders(token),
            body: formData,
        });
        const data = await res.json();
        return { success: res.ok, data, status: res.status };
    } catch (e) {
        return { success: false };
    }
}

export async function deleteMarketingProperty(token: string, id: number): Promise<{ success: boolean; status?: number }> {
    try {
        const res = await fetch(`${getApiUrl()}/user/marketing-properties/${id}`, {
            method: 'DELETE',
            headers: authHeaders(token),
        });
        return { success: res.ok, status: res.status };
    } catch { return { success: false }; }
}

export async function deleteTawtheeqContract(token: string, id: number): Promise<{ success: boolean; status?: number }> {
    try {
        const res = await fetch(`${getApiUrl()}/user/tawtheeq-contracts/${id}`, {
            method: 'DELETE',
            headers: authHeaders(token),
        });
        return { success: res.ok, status: res.status };
    } catch { return { success: false }; }
}

export async function deleteFinanceRequest(token: string, id: number): Promise<{ success: boolean; status?: number }> {
    try {
        const res = await fetch(`${getApiUrl()}/user/client-finance-requests/${id}`, {
            method: 'DELETE',
            headers: authHeaders(token),
        });
        return { success: res.ok, status: res.status };
    } catch { return { success: false }; }
}

// ===================== PUBLIC DATA FETCHING =====================

/**
 * Fetches a client (Broker/Owner) by ID
 */
export async function getClientById(id: string | number): Promise<any> {
    try {
        const res = await fetch(`${getApiUrl()}/clients/${id}`, {
            cache: 'no-store',
        });
        if (!res.ok) return null;
        const json = await res.json();
        return json;
    } catch (e) {
        console.error('Error fetching client by ID:', e);
        return null;
    }
}

/**
 * Fetches properties/projects for a specific owner
 */
export async function getOwnerProperties(ownerId: string | number, ownerType: 'client' | 'user' = 'client'): Promise<any[]> {
    try {
        const res = await fetch(`${getApiUrl()}/properties/owner/${ownerId}/${ownerType}`, {
            cache: 'no-store',
        });
        if (!res.ok) return [];
        const json = await res.json();
        return json.data || [];
    } catch (e) {
        console.error('Error fetching owner properties:', e);
        return [];
    }
}

/**
 * Fetches property requests for a specific owner
 */
export async function getOwnerRequests(ownerId: string | number): Promise<any[]> {
    try {
        const res = await fetch(`${getApiUrl()}/property-requests?client_id=${ownerId}`, {
            cache: 'no-store',
        });
        if (!res.ok) return [];
        const json = await res.json();
        return json.data || [];
    } catch (e) {
        console.error('Error fetching owner requests:', e);
        return [];
    }
}
