'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { ArrowLeft, Edit, Plus, Calendar, DollarSign, Users, FileText, Clock, CheckCircle, AlertCircle, PlayCircle, PauseCircle, XCircle, Globe, Target } from 'lucide-react';
import Link from 'next/link';
import { CustomerDomains } from '@/components/customers/CustomerDomains';
import { CustomerTasks } from '@/components/customers/CustomerTasks';
import VoiceRecorder from '@/src/components/attachments/VoiceRecorder';
import FileUploader from '@/src/components/attachments/FileUploader';
import AttachmentsGallery from '@/src/components/attachments/AttachmentsGallery';
import AppLayout from '@/src/components/layout/AppLayout';

interface Customer {
    id: string;
    name: string;
    email?: string;
    phone?: string;
    company?: string;
    address?: string;
    status: string;
    stage: string;
    value: number;
    assigned_sales_rep?: string;
    notes?: string;
    created_date: string;
    updated_at: string;
}

interface CustomerStats {
    domains_count: number;
    domains_expiring_soon: number;
    active_tasks: number;
    urgent_tasks: number;
    total_tasks: number;
    active_projects: number;
    total_projects: number;
    total_revenue: number;
    outstanding_debt: number;
    upcoming_events: number;
}

const statusConfig = {
    active: { label: 'פעיל', color: 'bg-green-100 text-green-800', icon: CheckCircle },
    inactive: { label: 'לא פעיל', color: 'bg-gray-100 text-gray-800', icon: PauseCircle },
    potential: { label: 'פוטנציאלי', color: 'bg-yellow-100 text-yellow-800', icon: Clock },
    vip: { label: 'VIP', color: 'bg-purple-100 text-purple-800', icon: Users }
};

const stageConfig = {
    lead: { label: 'ליד', color: 'bg-blue-100 text-blue-800' },
    qualified: { label: 'מוסמך', color: 'bg-green-100 text-green-800' },
    proposal: { label: 'הצעת מחיר', color: 'bg-yellow-100 text-yellow-800' },
    negotiation: { label: 'משא ומתן', color: 'bg-orange-100 text-orange-800' },
    closed_won: { label: 'נסגר בהצלחה', color: 'bg-green-100 text-green-800' },
    closed_lost: { label: 'נסגר ללא הצלחה', color: 'bg-red-100 text-red-800' }
};

export default function CustomerDetailsPage() {
    const params = useParams();
    const router = useRouter();
    const [customer, setCustomer] = useState<Customer | null>(null);
    const [stats, setStats] = useState<CustomerStats | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [activeTab, setActiveTab] = useState('overview');

    const customerId = params.id as string;

    const fetchCustomerData = async () => {
        try {
            setLoading(true);

            // Fetch customer details
            const customerResponse = await fetch(`/api/customers/${customerId}`);
            if (!customerResponse.ok) {
                throw new Error('לקוח לא נמצא');
            }
            const customerData = await customerResponse.json();
            setCustomer(customerData);

            // Fetch customer stats from API
            const statsResponse = await fetch(`/api/customers/${customerId}/stats`);
            if (statsResponse.ok) {
                const statsData = await statsResponse.json();
                setStats(statsData);
            } else {
                // Fallback to mock data if API fails
                const mockStats: CustomerStats = {
                    domains_count: 0,
                    domains_expiring_soon: 0,
                    active_tasks: 0,
                    urgent_tasks: 0,
                    total_tasks: 0,
                    active_projects: 0,
                    total_projects: 0,
                    total_revenue: 0,
                    outstanding_debt: 0,
                    upcoming_events: 0
                };
                setStats(mockStats);
            }

        } catch (err) {
            console.error('Error fetching customer data:', err);
            setError(err instanceof Error ? err.message : 'שגיאה בטעינת נתוני הלקוח');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (customerId) {
            fetchCustomerData();
        }
    }, [customerId]);

    const formatDate = (dateString: string) => {
        return new Date(dateString).toLocaleDateString('he-IL');
    };

    const formatCurrency = (amount: number) => {
        return new Intl.NumberFormat('he-IL', {
            style: 'currency',
            currency: 'ILS'
        }).format(amount);
    };

    if (loading) {
        return (
            <div className="container mx-auto px-4 py-8">
                <div className="flex items-center justify-center h-64">
                    <div className="text-center">
                        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4"></div>
                        <p className="text-gray-600">טוען פרטי לקוח...</p>
                    </div>
                </div>
            </div>
        );
    }

    if (error || !customer) {
        return (
            <div className="container mx-auto px-4 py-8">
                <div className="text-center">
                    <AlertCircle className="h-12 w-12 text-red-500 mx-auto mb-4" />
                    <h1 className="text-2xl font-bold text-gray-900 mb-2">שגיאה</h1>
                    <p className="text-gray-600 mb-4">{error || 'לקוח לא נמצא'}</p>
                    <Button onClick={() => router.push('/customers')}>
                        <ArrowLeft className="w-4 h-4 ml-2" />
                        חזרה לרשימת הלקוחות
                    </Button>
                </div>
            </div>
        );
    }

    const statusInfo = statusConfig[customer.status as keyof typeof statusConfig] || statusConfig.active;
    const stageInfo = stageConfig[customer.stage as keyof typeof stageConfig] || stageConfig.lead;
    const StatusIcon = statusInfo.icon;

    return (
        <AppLayout>
            <div className="min-h-screen bg-gray-50">
                {/* Top Bar */}
                <div className="bg-white border-b border-gray-200 px-6 py-4">
                    <div className="flex items-center justify-between">
                        <Button
                            variant="outline"
                            onClick={() => router.push('/customers')}
                            className="flex items-center gap-2"
                        >
                            <ArrowLeft className="w-4 h-4" />
                            חזרה לרשימת הלקוחות
                        </Button>

                        <div className="flex items-center gap-4">
                            <h1 className="text-2xl font-bold text-gray-900">
                                {customer.name}
                            </h1>
                            <Badge className={`${statusInfo.color} px-3 py-1`}>
                                <StatusIcon className="w-4 h-4 ml-1" />
                                {statusInfo.label}
                            </Badge>
                        </div>

                        <Button onClick={() => router.push(`/customers/${customerId}/edit`)}>
                            <Edit className="w-4 h-4 ml-2" />
                            ערוך
                        </Button>
                    </div>
                </div>

                <div className="container mx-auto px-4 py-6">
                    {/* Customer Info Header */}
                    <div className="mb-6">
                        {customer.company && (
                            <p className="text-gray-600 text-lg mb-2">🏢 {customer.company}</p>
                        )}
                        <div className="flex items-center gap-4">
                            <Badge className={`${stageInfo.color} px-2 py-1`}>
                                {stageInfo.label}
                            </Badge>
                            <span className="text-lg font-semibold text-gray-700">
                                ערך: {formatCurrency(customer.value)}
                            </span>
                        </div>
                    </div>

                    {/* Summary Cards */}
                    {stats && (
                        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
                            <Card>
                                <CardHeader className="pb-3">
                                    <CardTitle className="text-sm font-medium text-gray-600">
                                        דומיינים
                                    </CardTitle>
                                </CardHeader>
                                <CardContent>
                                    <div className="text-3xl font-bold">🌐 {stats.domains_count}</div>
                                    {stats.domains_expiring_soon > 0 && (
                                        <p className="text-xs text-red-600 mt-1">
                                            {stats.domains_expiring_soon} פוגים בקרוב
                                        </p>
                                    )}
                                </CardContent>
                            </Card>

                            <Card>
                                <CardHeader className="pb-3">
                                    <CardTitle className="text-sm font-medium text-gray-600">
                                        משימות
                                    </CardTitle>
                                </CardHeader>
                                <CardContent>
                                    <div className="text-3xl font-bold">📋 {stats.active_tasks}</div>
                                    {stats.urgent_tasks > 0 && (
                                        <p className="text-xs text-red-600 mt-1">
                                            {stats.urgent_tasks} דחופות
                                        </p>
                                    )}
                                </CardContent>
                            </Card>

                            <Card>
                                <CardHeader className="pb-3">
                                    <CardTitle className="text-sm font-medium text-gray-600">
                                        פרויקטים
                                    </CardTitle>
                                </CardHeader>
                                <CardContent>
                                    <div className="text-3xl font-bold">📊 {stats.active_projects}</div>
                                    <p className="text-xs text-gray-600 mt-1">
                                        {stats.total_projects} סה"כ
                                    </p>
                                </CardContent>
                            </Card>

                            <Card>
                                <CardHeader className="pb-3">
                                    <CardTitle className="text-sm font-medium text-gray-600">
                                        הכנסות
                                    </CardTitle>
                                </CardHeader>
                                <CardContent>
                                    <div className="text-3xl font-bold">
                                        💰 {formatCurrency(stats.total_revenue)}
                                    </div>
                                    {stats.outstanding_debt > 0 && (
                                        <p className="text-xs text-red-600 mt-1">
                                            חוב: {formatCurrency(stats.outstanding_debt)}
                                        </p>
                                    )}
                                </CardContent>
                            </Card>
                        </div>
                    )}

                    {/* Tabs */}
                    <Tabs value={activeTab} onValueChange={setActiveTab}>
                        <TabsList className="mb-6">
                            <TabsTrigger value="overview">פרטים</TabsTrigger>
                            <TabsTrigger value="domains">
                                דומיינים
                                {stats && stats.domains_count > 0 && (
                                    <Badge variant="secondary" className="mr-2">
                                        {stats.domains_count}
                                    </Badge>
                                )}
                            </TabsTrigger>
                            <TabsTrigger value="tasks">
                                משימות
                                {stats && stats.active_tasks > 0 && (
                                    <Badge variant="secondary" className="mr-2">
                                        {stats.active_tasks}
                                    </Badge>
                                )}
                            </TabsTrigger>
                            <TabsTrigger value="projects">
                                פרויקטים
                                {stats && stats.active_projects > 0 && (
                                    <Badge variant="secondary" className="mr-2">
                                        {stats.active_projects}
                                    </Badge>
                                )}
                            </TabsTrigger>
                            <TabsTrigger value="events">אירועים</TabsTrigger>
                            <TabsTrigger value="attachments">קבצים מצורפים</TabsTrigger>
                            <TabsTrigger value="finance">כספים</TabsTrigger>
                            <TabsTrigger value="activity">היסטוריה</TabsTrigger>
                        </TabsList>

                        <TabsContent value="overview">
                            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                                {/* Customer Details */}
                                <Card>
                                    <CardHeader>
                                        <CardTitle className="flex items-center gap-2">
                                            <FileText className="w-5 h-5" />
                                            פרטי לקוח
                                        </CardTitle>
                                    </CardHeader>
                                    <CardContent>
                                        {customer.email && (
                                            <div className="flex items-center justify-between mb-3">
                                                <span className="text-gray-500">📧</span>
                                                <span className="text-right flex-1">{customer.email}</span>
                                            </div>
                                        )}

                                        {customer.phone && (
                                            <div className="flex items-center justify-between mb-3">
                                                <span className="text-gray-500">📞</span>
                                                <span className="text-right flex-1">{customer.phone}</span>
                                            </div>
                                        )}

                                        {customer.company && (
                                            <div className="flex items-center justify-between mb-3">
                                                <span className="text-gray-500">🏢</span>
                                                <span className="text-right flex-1">{customer.company}</span>
                                            </div>
                                        )}

                                        {customer.address && (
                                            <div className="flex items-center justify-between mb-3">
                                                <span className="text-gray-500">🏠</span>
                                                <span className="text-right flex-1">{customer.address}</span>
                                            </div>
                                        )}

                                        <div className="flex items-center justify-between mb-3">
                                            <span className="text-gray-500">📅</span>
                                            <span className="text-right flex-1">נוצר: {formatDate(customer.created_date)}</span>
                                        </div>

                                        <div className="flex items-center justify-between mb-3">
                                            <span className="text-gray-500">🔄</span>
                                            <span className="text-right flex-1">עדכון אחרון: {formatDate(customer.updated_at)}</span>
                                        </div>

                                        {customer.assigned_sales_rep && (
                                            <div className="flex items-center justify-between mb-3">
                                                <span className="text-gray-500">👤</span>
                                                <span className="text-right flex-1">נציג מכירות: {customer.assigned_sales_rep}</span>
                                            </div>
                                        )}

                                        {customer.notes && (
                                            <div className="pt-4 border-t">
                                                <p className="text-sm text-gray-500 mb-2">הערות:</p>
                                                <p className="text-sm" style={{ textAlign: 'right' }}>{customer.notes}</p>
                                            </div>
                                        )}
                                    </CardContent>
                                </Card>

                                {/* Statistics */}
                                {stats && (
                                    <Card>
                                        <CardHeader>
                                            <CardTitle className="flex items-center gap-2">
                                                <Users className="w-5 h-5" />
                                                סטטיסטיקות
                                            </CardTitle>
                                        </CardHeader>
                                        <CardContent>
                                            <div className="flex items-start justify-between mb-4">
                                                <span className="text-gray-500 mt-1">🌐</span>
                                                <div className="text-right flex-1">
                                                    <h4 className="font-medium mb-2">דומיינים:</h4>
                                                    <div className="text-sm text-gray-600 space-y-1">
                                                        <div className="text-right">• סה"כ דומיינים: {stats.domains_count}</div>
                                                        <div className="text-right">• דומיינים פעילים: {stats.domains_count}</div>
                                                        <div className="text-right">• דומיינים שפוגים ב-30 יום: {stats.domains_expiring_soon}</div>
                                                    </div>
                                                </div>
                                            </div>

                                            <div className="flex items-start justify-between mb-4">
                                                <span className="text-gray-500 mt-1">✅</span>
                                                <div className="text-right flex-1">
                                                    <h4 className="font-medium mb-2">משימות:</h4>
                                                    <div className="text-sm text-gray-600 space-y-1">
                                                        <div className="text-right">• סה"כ משימות: {stats.total_tasks}</div>
                                                        <div className="text-right">• משימות פעילות: {stats.active_tasks}</div>
                                                        <div className="text-right">• משימות דחופות: {stats.urgent_tasks}</div>
                                                    </div>
                                                </div>
                                            </div>

                                            <div className="flex items-start justify-between mb-4">
                                                <span className="text-gray-500 mt-1">📁</span>
                                                <div className="text-right flex-1">
                                                    <h4 className="font-medium mb-2">פרויקטים:</h4>
                                                    <div className="text-sm text-gray-600 space-y-1">
                                                        <div className="text-right">• סה"כ פרויקטים: {stats.total_projects}</div>
                                                        <div className="text-right">• פרויקטים פעילים: {stats.active_projects}</div>
                                                        <div className="text-right">• פרויקטים שהושלמו: {stats.total_projects - stats.active_projects}</div>
                                                    </div>
                                                </div>
                                            </div>

                                            <div className="flex items-start justify-between mb-4">
                                                <span className="text-gray-500 mt-1">💰</span>
                                                <div className="text-right flex-1">
                                                    <h4 className="font-medium mb-2">כספים:</h4>
                                                    <div className="text-sm text-gray-600 space-y-1">
                                                        <div className="text-right">• סה"כ הכנסות: {formatCurrency(stats.total_revenue)}</div>
                                                        <div className="text-right">• חובות: {formatCurrency(stats.outstanding_debt)}</div>
                                                    </div>
                                                </div>
                                            </div>
                                        </CardContent>
                                    </Card>
                                )}
                            </div>
                        </TabsContent>

                        <TabsContent value="domains">
                            <CustomerDomains customerId={customerId} />
                        </TabsContent>

                        <TabsContent value="tasks">
                            <CustomerTasks customerId={customerId} customerName={customer.name} />
                        </TabsContent>

                        <TabsContent value="projects">
                            <div className="space-y-4">
                                <div className="flex justify-between items-center">
                                    <h2 className="text-xl font-bold">📊 פרויקטים</h2>
                                    <Button onClick={() => window.location.href = `/projects/new?customer_id=${customerId}`}>
                                        <Plus className="w-4 h-4 ml-2" />
                                        פרויקט חדש
                                    </Button>
                                </div>
                                <Card>
                                    <CardContent className="py-12 text-center text-gray-500">
                                        <p className="text-xl mb-4">פרויקטים יוצגו כאן</p>
                                        <p className="text-sm">תכונה זו תתווסף בקרוב</p>
                                    </CardContent>
                                </Card>
                            </div>
                        </TabsContent>

                        <TabsContent value="events">
                            <div className="space-y-4">
                                <div className="flex justify-between items-center">
                                    <h2 className="text-xl font-bold">📅 אירועים</h2>
                                    <Button onClick={() => window.location.href = `/events/new?customer_id=${customerId}&customer_name=${encodeURIComponent(customer.name)}`}>
                                        <Plus className="w-4 h-4 ml-2" />
                                        אירוע חדש
                                    </Button>
                                </div>
                                <Card>
                                    <CardContent className="py-12 text-center text-gray-500">
                                        <p className="text-xl mb-4">אירועים יוצגו כאן</p>
                                        <p className="text-sm">תכונה זו תתווסף בקרוב</p>
                                    </CardContent>
                                </Card>
                            </div>
                        </TabsContent>

                        <TabsContent value="attachments">
                            <div className="space-y-6">
                                <div>
                                    <h2 className="text-xl font-bold mb-4">📎 העלאת קבצים והקלטות</h2>
                                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-6">
                                        <Card>
                                            <CardHeader>
                                                <CardTitle className="text-lg">🎤 הקלטה קולית</CardTitle>
                                            </CardHeader>
                                            <CardContent>
                                                <VoiceRecorder
                                                    entityType="customer"
                                                    entityId={customerId}
                                                    onUploadSuccess={fetchCustomerData}
                                                />
                                            </CardContent>
                                        </Card>

                                        <Card>
                                            <CardHeader>
                                                <CardTitle className="text-lg">📁 העלאת קבצים</CardTitle>
                                            </CardHeader>
                                            <CardContent>
                                                <FileUploader
                                                    entityType="customer"
                                                    entityId={customerId}
                                                    onUploadSuccess={fetchCustomerData}
                                                />
                                            </CardContent>
                                        </Card>
                                    </div>
                                </div>

                                <Card>
                                    <CardHeader>
                                        <CardTitle>📚 קבצים מצורפים</CardTitle>
                                    </CardHeader>
                                    <CardContent>
                                        <AttachmentsGallery
                                            entityType="customer"
                                            entityId={customerId}
                                            onDelete={fetchCustomerData}
                                        />
                                    </CardContent>
                                </Card>
                            </div>
                        </TabsContent>

                        <TabsContent value="finance">
                            <div className="space-y-4">
                                <div className="flex justify-between items-center">
                                    <h2 className="text-xl font-bold">💰 כספים</h2>
                                    <Button onClick={() => alert('יצירת חשבונית חדשה')}>
                                        <Plus className="w-4 h-4 ml-2" />
                                        חשבונית חדשה
                                    </Button>
                                </div>
                                <Card>
                                    <CardContent className="py-12 text-center text-gray-500">
                                        <p className="text-xl mb-4">מידע כספי יוצג כאן</p>
                                        <p className="text-sm">תכונה זו תתווסף בקרוב</p>
                                    </CardContent>
                                </Card>
                            </div>
                        </TabsContent>

                        <TabsContent value="activity">
                            <div className="space-y-4">
                                <h2 className="text-xl font-bold">📜 היסטוריית פעילות</h2>
                                <Card>
                                    <CardContent className="py-12 text-center text-gray-500">
                                        <p className="text-xl mb-4">היסטוריית פעילות תוצג כאן</p>
                                        <p className="text-sm">תכונה זו תתווסף בקרוב</p>
                                    </CardContent>
                                </Card>
                            </div>
                        </TabsContent>
                    </Tabs>
                </div>
            </div>
        </AppLayout>
    );
}
