'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 { Progress } from '@/components/ui/progress';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import {
    ArrowLeft,
    Edit,
    Trash2,
    Calendar,
    DollarSign,
    Users,
    FileText,
    Clock,
    CheckCircle,
    AlertCircle,
    PlayCircle,
    PauseCircle,
    XCircle
} from 'lucide-react';

interface Project {
    id: string;
    title: string;
    description?: string;
    customer_id: string;
    customer_name?: string;
    customer_company?: string;
    customer_email?: string;
    customer_phone?: string;
    status: string;
    start_date?: string;
    end_date?: string;
    budget: number;
    progress: number;
    assigned_team: string[];
    notes?: string;
    created_date: string;
    updated_at: string;
}

const statusConfig = {
    planning: { label: 'תכנון', color: 'bg-yellow-100 text-yellow-800', icon: Clock },
    in_progress: { label: 'בביצוע', color: 'bg-blue-100 text-blue-800', icon: PlayCircle },
    pending: { label: 'ממתין', color: 'bg-orange-100 text-orange-800', icon: PauseCircle },
    completed: { label: 'הושלם', color: 'bg-green-100 text-green-800', icon: CheckCircle },
    cancelled: { label: 'בוטל', color: 'bg-red-100 text-red-800', icon: XCircle }
};

const priorityConfig = {
    low: { label: 'נמוכה', color: 'bg-gray-100 text-gray-800' },
    medium: { label: 'בינונית', color: 'bg-blue-100 text-blue-800' },
    high: { label: 'גבוהה', color: 'bg-orange-100 text-orange-800' },
    urgent: { label: 'דחוף', color: 'bg-red-100 text-red-800' }
};

export default function ProjectPage() {
    const params = useParams();
    const router = useRouter();
    const [project, setProject] = useState<Project | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    const projectId = params.id as string;

    useEffect(() => {
        if (projectId) {
            fetchProject();
        }
    }, [projectId]);

    const fetchProject = async () => {
        try {
            setLoading(true);
            const response = await fetch(`/api/projects/${projectId}`);

            if (!response.ok) {
                throw new Error('פרויקט לא נמצא');
            }

            const data = await response.json();
            setProject(data);
        } catch (err) {
            console.error('Error fetching project:', err);
            setError(err instanceof Error ? err.message : 'שגיאה בטעינת הפרויקט');
        } finally {
            setLoading(false);
        }
    };

    const handleEdit = () => {
        router.push(`/projects/${projectId}/edit`);
    };

    const handleDelete = async () => {
        if (!confirm('האם אתה בטוח שברצונך למחוק את הפרויקט?')) {
            return;
        }

        try {
            const response = await fetch(`/api/projects/${projectId}`, {
                method: 'DELETE'
            });

            if (!response.ok) {
                throw new Error('שגיאה במחיקת הפרויקט');
            }

            router.push('/projects');
        } catch (err) {
            console.error('Error deleting project:', err);
            alert('שגיאה במחיקת הפרויקט');
        }
    };

    const formatDate = (dateString?: string) => {
        if (!dateString) return 'לא צוין';
        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 || !project) {
        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('/projects')}>
                        <ArrowLeft className="w-4 h-4 ml-2" />
                        חזרה לרשימת הפרויקטים
                    </Button>
                </div>
            </div>
        );
    }

    const statusInfo = statusConfig[project.status as keyof typeof statusConfig] || statusConfig.planning;
    const StatusIcon = statusInfo.icon;

    return (
        <div className="container mx-auto px-4 py-8">
            {/* Header */}
            <div className="mb-6">
                <div className="flex items-center justify-between mb-4">
                    <Button
                        variant="outline"
                        onClick={() => router.push('/projects')}
                        className="mb-4"
                    >
                        <ArrowLeft className="w-4 h-4 ml-2" />
                        חזרה לרשימת הפרויקטים
                    </Button>

                    <div className="flex gap-2">
                        <Button onClick={handleEdit} className="bg-blue-600 hover:bg-blue-700">
                            <Edit className="w-4 h-4 ml-2" />
                            ערוך
                        </Button>
                        <Button
                            variant="destructive"
                            onClick={handleDelete}
                        >
                            <Trash2 className="w-4 h-4 ml-2" />
                            מחק
                        </Button>
                    </div>
                </div>

                <div className="flex items-start justify-between">
                    <div>
                        <h1 className="text-3xl font-bold text-gray-900 mb-2">
                            {project.title}
                        </h1>
                        <div className="flex items-center gap-4 mb-4">
                            <Badge className={`${statusInfo.color} px-3 py-1`}>
                                <StatusIcon className="w-4 h-4 ml-1" />
                                {statusInfo.label}
                            </Badge>
                            <span className="text-sm text-gray-500">
                                #{project.id}
                            </span>
                        </div>
                    </div>
                </div>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                {/* Main Content */}
                <div className="lg:col-span-2 space-y-6">
                    {/* Description */}
                    {project.description && (
                        <Card>
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2">
                                    <FileText className="w-5 h-5" />
                                    תיאור הפרויקט
                                </CardTitle>
                            </CardHeader>
                            <CardContent>
                                <p className="text-gray-700 whitespace-pre-wrap">
                                    {project.description}
                                </p>
                            </CardContent>
                        </Card>
                    )}

                    {/* Progress */}
                    <Card>
                        <CardHeader>
                            <CardTitle>התקדמות הפרויקט</CardTitle>
                        </CardHeader>
                        <CardContent>
                            <div className="space-y-4">
                                <div className="flex justify-between items-center">
                                    <span className="text-sm font-medium">התקדמות</span>
                                    <span className="text-sm text-gray-600">{project.progress}%</span>
                                </div>
                                <Progress value={project.progress} className="h-2" />
                            </div>
                        </CardContent>
                    </Card>

                    {/* Team */}
                    {project.assigned_team && project.assigned_team.length > 0 && (
                        <Card>
                            <CardHeader>
                                <CardTitle className="flex items-center gap-2">
                                    <Users className="w-5 h-5" />
                                    צוות מוקצה
                                </CardTitle>
                            </CardHeader>
                            <CardContent>
                                <div className="flex flex-wrap gap-2">
                                    {project.assigned_team.map((member, index) => (
                                        <Badge key={index} variant="secondary">
                                            {member}
                                        </Badge>
                                    ))}
                                </div>
                            </CardContent>
                        </Card>
                    )}

                    {/* Notes */}
                    {project.notes && (
                        <Card>
                            <CardHeader>
                                <CardTitle>הערות</CardTitle>
                            </CardHeader>
                            <CardContent>
                                <p className="text-gray-700 whitespace-pre-wrap">
                                    {project.notes}
                                </p>
                            </CardContent>
                        </Card>
                    )}
                </div>

                {/* Sidebar */}
                <div className="space-y-6">
                    {/* Project Details */}
                    <Card>
                        <CardHeader>
                            <CardTitle>פרטי הפרויקט</CardTitle>
                        </CardHeader>
                        <CardContent className="space-y-4">
                            <div className="flex items-center gap-3">
                                <Calendar className="w-4 h-4 text-gray-500" />
                                <div>
                                    <p className="text-sm text-gray-500">תאריך התחלה</p>
                                    <p className="font-medium">{formatDate(project.start_date)}</p>
                                </div>
                            </div>

                            <div className="flex items-center gap-3">
                                <Calendar className="w-4 h-4 text-gray-500" />
                                <div>
                                    <p className="text-sm text-gray-500">תאריך סיום</p>
                                    <p className="font-medium">{formatDate(project.end_date)}</p>
                                </div>
                            </div>

                            <div className="flex items-center gap-3">
                                <DollarSign className="w-4 h-4 text-gray-500" />
                                <div>
                                    <p className="text-sm text-gray-500">תקציב</p>
                                    <p className="font-medium">{formatCurrency(project.budget)}</p>
                                </div>
                            </div>
                        </CardContent>
                    </Card>

                    {/* Customer Info */}
                    <Card>
                        <CardHeader>
                            <CardTitle>פרטי הלקוח</CardTitle>
                        </CardHeader>
                        <CardContent className="space-y-3">
                            <div>
                                <p className="text-sm text-gray-500">שם הלקוח</p>
                                <p className="font-medium">{project.customer_name || 'לא צוין'}</p>
                            </div>

                            {project.customer_company && (
                                <div>
                                    <p className="text-sm text-gray-500">חברה</p>
                                    <p className="font-medium">{project.customer_company}</p>
                                </div>
                            )}

                            {project.customer_email && (
                                <div>
                                    <p className="text-sm text-gray-500">אימייל</p>
                                    <p className="font-medium">{project.customer_email}</p>
                                </div>
                            )}

                            {project.customer_phone && (
                                <div>
                                    <p className="text-sm text-gray-500">טלפון</p>
                                    <p className="font-medium">{project.customer_phone}</p>
                                </div>
                            )}

                            <Button
                                variant="outline"
                                className="w-full"
                                onClick={() => router.push(`/customers?search=${encodeURIComponent(project.customer_name || '')}`)}
                            >
                                צפה בפרופיל הלקוח
                            </Button>
                        </CardContent>
                    </Card>

                    {/* Project Timeline */}
                    <Card>
                        <CardHeader>
                            <CardTitle>ציר זמן</CardTitle>
                        </CardHeader>
                        <CardContent className="space-y-3">
                            <div>
                                <p className="text-sm text-gray-500">נוצר</p>
                                <p className="font-medium">{formatDate(project.created_date)}</p>
                            </div>

                            <div>
                                <p className="text-sm text-gray-500">עודכן לאחרונה</p>
                                <p className="font-medium">{formatDate(project.updated_at)}</p>
                            </div>
                        </CardContent>
                    </Card>
                </div>
            </div>
        </div>
    );
}
