'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Checkbox } from '@/components/ui/checkbox';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { ArrowLeft, Save, X } from 'lucide-react';
import { CustomerSelect } from '@/components/customers/CustomerSelect';
import { DomainSelect } from '@/components/domains/DomainSelect';

const projectSchema = z.object({
    title: z.string().min(2, 'כותרת חייבת להכיל לפחות 2 תווים'),
    description: z.string().optional(),
    customer_id: z.string().min(1, 'בחר לקוח'),
    domain_id: z.string().optional(),
    status: z.enum(['planning', 'in_progress', 'pending', 'completed', 'cancelled']),
    start_date: z.string().optional(),
    end_date: z.string().optional(),
    budget: z.number().min(0).optional(),
    progress: z.number().min(0).max(100).optional(),
    assigned_team: z.array(z.string()).optional(),
    notes: z.string().optional(),
});

type ProjectForm = z.infer<typeof projectSchema>;

interface Project {
    id: string;
    title: string;
    description?: string;
    customer_id: string;
    domain_id?: string;
    status: string;
    start_date?: string;
    end_date?: string;
    budget: number;
    progress: number;
    assigned_team: string[];
    notes?: string;
}

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

    const projectId = params.id as string;

    const form = useForm<ProjectForm>({
        resolver: zodResolver(projectSchema),
        defaultValues: {
            title: '',
            description: '',
            customer_id: '',
            domain_id: '',
            status: 'planning',
            start_date: '',
            end_date: '',
            budget: 0,
            progress: 0,
            assigned_team: [],
            notes: '',
        },
    });

    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);

            // Populate form with project data
            form.reset({
                title: data.title,
                description: data.description || '',
                customer_id: data.customer_id,
                domain_id: data.domain_id || '',
                status: data.status,
                start_date: data.start_date || '',
                end_date: data.end_date || '',
                budget: data.budget || 0,
                progress: data.progress || 0,
                assigned_team: data.assigned_team || [],
                notes: data.notes || '',
            });
        } catch (err) {
            console.error('Error fetching project:', err);
            setError(err instanceof Error ? err.message : 'שגיאה בטעינת הפרויקט');
        } finally {
            setLoading(false);
        }
    };

    const onSubmit = async (data: ProjectForm) => {
        try {
            setSaving(true);
            setError(null);

            const response = await fetch(`/api/projects/${projectId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.error || 'שגיאה בעדכון הפרויקט');
            }

            // Redirect to project view page
            router.push(`/projects/${projectId}`);
        } catch (err) {
            console.error('Error updating project:', err);
            setError(err instanceof Error ? err.message : 'שגיאה בעדכון הפרויקט');
        } finally {
            setSaving(false);
        }
    };

    const formatDateForInput = (dateString?: string) => {
        if (!dateString) return '';
        return new Date(dateString).toISOString().split('T')[0];
    };

    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">
                    <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>
        );
    }

    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/${projectId}`)}
                        className="mb-4"
                    >
                        <ArrowLeft className="w-4 h-4 ml-2" />
                        חזרה לפרויקט
                    </Button>
                </div>

                <h1 className="text-3xl font-bold text-gray-900 mb-2">
                    עריכת פרויקט
                </h1>
                <p className="text-gray-600">
                    ערוך את פרטי הפרויקט #{project.id}
                </p>
            </div>

            <div className="max-w-4xl">
                <Card>
                    <CardHeader>
                        <CardTitle>פרטי הפרויקט</CardTitle>
                        <CardDescription>
                            עדכן את המידע הבסיסי של הפרויקט
                        </CardDescription>
                    </CardHeader>
                    <CardContent>
                        <Form {...form}>
                            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
                                {error && (
                                    <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded">
                                        {error}
                                    </div>
                                )}

                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    {/* Title */}
                                    <FormField
                                        control={form.control}
                                        name="title"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>כותרת הפרויקט *</FormLabel>
                                                <FormControl>
                                                    <Input placeholder="הזן כותרת" {...field} />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    {/* Customer */}
                                    <FormField
                                        control={form.control}
                                        name="customer_id"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>לקוח *</FormLabel>
                                                <FormControl>
                                                    <CustomerSelect
                                                        value={field.value}
                                                        onChange={field.onChange}
                                                        placeholder="בחר לקוח"
                                                    />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    {/* Status */}
                                    <FormField
                                        control={form.control}
                                        name="status"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>סטטוס</FormLabel>
                                                <Select onValueChange={field.onChange} value={field.value}>
                                                    <FormControl>
                                                        <SelectTrigger>
                                                            <SelectValue placeholder="בחר סטטוס" />
                                                        </SelectTrigger>
                                                    </FormControl>
                                                    <SelectContent>
                                                        <SelectItem value="planning">תכנון</SelectItem>
                                                        <SelectItem value="in_progress">בביצוע</SelectItem>
                                                        <SelectItem value="pending">ממתין</SelectItem>
                                                        <SelectItem value="completed">הושלם</SelectItem>
                                                        <SelectItem value="cancelled">בוטל</SelectItem>
                                                    </SelectContent>
                                                </Select>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    {/* Domain */}
                                    <FormField
                                        control={form.control}
                                        name="domain_id"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>דומיין</FormLabel>
                                                <FormControl>
                                                    <DomainSelect
                                                        customerId={form.watch('customer_id')}
                                                        value={field.value}
                                                        onChange={field.onChange}
                                                        placeholder="בחר דומיין"
                                                    />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    {/* Start Date */}
                                    <FormField
                                        control={form.control}
                                        name="start_date"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>תאריך התחלה</FormLabel>
                                                <FormControl>
                                                    <Input
                                                        type="date"
                                                        value={formatDateForInput(field.value)}
                                                        onChange={(e) => field.onChange(e.target.value)}
                                                    />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    {/* End Date */}
                                    <FormField
                                        control={form.control}
                                        name="end_date"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>תאריך סיום</FormLabel>
                                                <FormControl>
                                                    <Input
                                                        type="date"
                                                        value={formatDateForInput(field.value)}
                                                        onChange={(e) => field.onChange(e.target.value)}
                                                    />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    {/* Budget */}
                                    <FormField
                                        control={form.control}
                                        name="budget"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>תקציב (₪)</FormLabel>
                                                <FormControl>
                                                    <Input
                                                        type="number"
                                                        min="0"
                                                        step="0.01"
                                                        value={field.value}
                                                        onChange={(e) => field.onChange(parseFloat(e.target.value) || 0)}
                                                    />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    {/* Progress */}
                                    <FormField
                                        control={form.control}
                                        name="progress"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>התקדמות (%)</FormLabel>
                                                <FormControl>
                                                    <Input
                                                        type="number"
                                                        min="0"
                                                        max="100"
                                                        value={field.value}
                                                        onChange={(e) => field.onChange(parseInt(e.target.value) || 0)}
                                                    />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                </div>

                                {/* Description */}
                                <FormField
                                    control={form.control}
                                    name="description"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>תיאור הפרויקט</FormLabel>
                                            <FormControl>
                                                <Textarea
                                                    placeholder="הזן תיאור מפורט של הפרויקט"
                                                    className="min-h-[100px]"
                                                    {...field}
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                {/* Notes */}
                                <FormField
                                    control={form.control}
                                    name="notes"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>הערות</FormLabel>
                                            <FormControl>
                                                <Textarea
                                                    placeholder="הזן הערות נוספות"
                                                    className="min-h-[80px]"
                                                    {...field}
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />

                                {/* Submit Buttons */}
                                <div className="flex justify-end gap-3 pt-6">
                                    <Button
                                        type="button"
                                        variant="outline"
                                        onClick={() => router.push(`/projects/${projectId}`)}
                                        disabled={saving}
                                    >
                                        <X className="w-4 h-4 ml-2" />
                                        ביטול
                                    </Button>
                                    <Button
                                        type="submit"
                                        className="bg-blue-600 hover:bg-blue-700"
                                        disabled={saving}
                                    >
                                        {saving ? (
                                            <>
                                                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white ml-2"></div>
                                                שומר...
                                            </>
                                        ) : (
                                            <>
                                                <Save className="w-4 h-4 ml-2" />
                                                שמור שינויים
                                            </>
                                        )}
                                    </Button>
                                </div>
                            </form>
                        </Form>
                    </CardContent>
                </Card>
            </div>
        </div>
    );
}
