import { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { X, Save, ArrowLeft, Loader2, Clock } from 'lucide-react';
import { useUserSearch } from '@/hooks/useUserSearch';
import { createTemplate, updateTemplate, getTemplates, WorkflowTemplate } from '@/services/workflowTemplateApi';
import { toast } from 'sonner';

export function CreateTemplate() {
    const navigate = useNavigate();
    const { templateId } = useParams<{ templateId: string }>();
    const isEditing = !!templateId;

    const [loading, setLoading] = useState(false);
    const [fetching, setFetching] = useState(false);
    const { searchResults, searchLoading, searchUsersDebounced, clearSearch } = useUserSearch();
    const [approverSearchInput, setApproverSearchInput] = useState('');

    const [formData, setFormData] = useState({
        name: '',
        description: '',
        category: 'General',
        priority: 'medium' as 'low' | 'medium' | 'high',
        estimatedTime: '2 days',
        suggestedSLA: 24,
        approvers: [] as any[]
    });

    useEffect(() => {
        if (isEditing && templateId) {
            const fetchTemplate = async () => {
                try {
                    setFetching(true);
                    const templates = await getTemplates();
                    const template = templates.find((t: WorkflowTemplate) => t.id === templateId);

                    if (template) {
                        setFormData({
                            name: template.name,
                            description: template.description,
                            category: template.category,
                            priority: template.priority,
                            estimatedTime: template.estimatedTime,
                            suggestedSLA: template.suggestedSLA,
                            approvers: template.approvers || []
                        });
                    } else {
                        toast.error('Template not found');
                        navigate('/admin/templates');
                    }
                } catch (error) {
                    console.error('Failed to load template:', error);
                    toast.error('Failed to load template details');
                } finally {
                    setFetching(false);
                }
            };
            fetchTemplate();
        }
    }, [isEditing, templateId, navigate]);

    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        const { name, value } = e.target;
        setFormData(prev => ({ ...prev, [name]: value }));
    };

    const handleSelectChange = (name: string, value: string) => {
        setFormData(prev => ({ ...prev, [name]: value }));
    };

    const handleApproverSearch = (val: string) => {
        setApproverSearchInput(val);
        // Only trigger search if specifically starting with '@'
        // This prevents triggering on email addresses like "user@example.com"
        if (val.startsWith('@')) {
            const query = val.slice(1);
            // Search if we have at least 1 character after @
            // This allows searching for "L" in "@L"
            if (query.length >= 1) {
                // Pass the full query starting with @, as useUserSearch expects it
                searchUsersDebounced(val, 5);
                return;
            }
        }
        // If no @ at start or query too short, clear results
        clearSearch();
    };

    // ... (rest of the component)

    // In the return JSX:
    <div className="flex gap-2">
        <Input
            placeholder="Type '@' to search user by name or email..."
            value={approverSearchInput}
            onChange={(e) => handleApproverSearch(e.target.value)}
            className="border-gray-200"
        />
    </div>

    const addApprover = (user: any) => {
        if (formData.approvers.some(a => a.userId === user.userId)) {
            toast.error('Approver already added');
            return;
        }
        setFormData(prev => ({
            ...prev,
            approvers: [...prev.approvers, {
                userId: user.userId,
                name: user.displayName || user.email,
                email: user.email,
                level: prev.approvers.length + 1,
                tat: 24, // Default TAT in hours
                tatType: 'hours' // Default unit
            }]
        }));
        setApproverSearchInput('');
        clearSearch();
    };

    const removeApprover = (index: number) => {
        const newApprovers = [...formData.approvers];
        newApprovers.splice(index, 1);
        // Re-index levels
        newApprovers.forEach((a, i) => a.level = i + 1);
        setFormData(prev => ({ ...prev, approvers: newApprovers }));
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!formData.name || !formData.description) {
            toast.error('Please fill in required fields');
            return;
        }

        if (formData.approvers.length === 0) {
            toast.error('Please add at least one approver');
            return;
        }

        // Prepare payload with TAT conversion
        const payload = {
            ...formData,
            approvers: formData.approvers.map(a => ({
                ...a,
                tat: a.tatType === 'days' ? (parseInt(a.tat) * 24) : parseInt(a.tat)
            }))
        };

        try {
            setLoading(true);
            if (isEditing && templateId) {
                await updateTemplate(templateId, payload);
                toast.success('Template updated successfully');
            } else {
                await createTemplate(payload);
                toast.success('Template created successfully');
            }
            navigate('/admin/templates'); // Back to list
        } catch (error) {
            toast.error(isEditing ? 'Failed to update template' : 'Failed to create template');
            console.error(error);
        } finally {
            setLoading(false);
        }
    };

    if (fetching) {
        return (
            <div className="flex h-96 items-center justify-center">
                <Loader2 className="h-8 w-8 animate-spin text-gray-400" />
            </div>
        );
    }

    const isFormValid = formData.name &&
        formData.description &&
        formData.approvers.length > 0 &&
        formData.approvers.every((a: any) => {
            const val = parseInt(String(a.tat)) || 0;
            const max = a.tatType === 'days' ? 7 : 24;
            return val >= 1 && val <= max;
        });

    return (
        <div className="max-w-4xl mx-auto p-6 space-y-6">
            <div className="flex items-center gap-4 mb-6">
                <Button variant="ghost" size="icon" onClick={() => navigate('/admin/templates')}>
                    <ArrowLeft className="w-5 h-5" />
                </Button>
                <div>
                    <h1 className="text-3xl font-bold text-gray-900">
                        {isEditing ? 'Edit Workflow Template' : 'Create Workflow Template'}
                    </h1>
                    <p className="text-gray-500">
                        {isEditing ? 'Update existing workflow configuration' : 'Define a new standardized request workflow'}
                    </p>
                </div>
            </div>

            <form onSubmit={handleSubmit} className="space-y-6">
                <Card>
                    <CardHeader>
                        <CardTitle>Basic Information</CardTitle>
                        <CardDescription>General details about the template</CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-4">
                        <div className="grid grid-cols-2 gap-4">
                            <div className="space-y-2">
                                <Label htmlFor="name">Template Name *</Label>
                                <Input
                                    id="name"
                                    name="name"
                                    placeholder="e.g., Office Stationery Request"
                                    value={formData.name}
                                    onChange={handleInputChange}
                                    className="border-gray-200"
                                    required
                                />
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="category">Category</Label>
                                <div className="relative">
                                    {/* Simple text input for now, could be select */}
                                    <Input
                                        id="category"
                                        name="category"
                                        placeholder="e.g., Admin, HR, Finance"
                                        value={formData.category}
                                        onChange={handleInputChange}
                                        className="border-gray-200"
                                    />
                                </div>
                            </div>
                        </div>

                        <div className="space-y-2">
                            <Label htmlFor="description">Description *</Label>
                            <Textarea
                                id="description"
                                name="description"
                                placeholder="Describe what this request is for..."
                                value={formData.description}
                                onChange={handleInputChange}
                                className="border-gray-200"
                                required
                            />
                        </div>

                        <div className="grid grid-cols-3 gap-4">
                            <div className="space-y-2">
                                <Label htmlFor="priority">Default Priority</Label>
                                <Select
                                    name="priority"
                                    value={formData.priority}
                                    onValueChange={(val) => handleSelectChange('priority', val)}
                                >
                                    <SelectTrigger>
                                        <SelectValue placeholder="Select priority" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="low">Low</SelectItem>
                                        <SelectItem value="medium">Medium</SelectItem>
                                        <SelectItem value="high">High</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="estimatedTime">Estimated Time</Label>
                                <Input
                                    id="estimatedTime"
                                    name="estimatedTime"
                                    placeholder="e.g., 2 days"
                                    value={formData.estimatedTime}
                                    onChange={handleInputChange}
                                    className="border-gray-200"
                                />
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="suggestedSLA">SLA (Hours)</Label>
                                <Input
                                    id="suggestedSLA"
                                    name="suggestedSLA"
                                    type="number"
                                    placeholder="24"
                                    value={formData.suggestedSLA}
                                    onChange={handleInputChange}
                                    className="border-gray-200"
                                />
                            </div>
                        </div>
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader>
                        <CardTitle>Approver Workflow</CardTitle>
                        <CardDescription>Define static approvers for this template</CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-6">
                        <div className="space-y-4">
                            {formData.approvers.map((approver, index) => (
                                <div key={index} className="flex items-center gap-4 p-3 bg-gray-50 rounded-lg border border-gray-100">
                                    <Badge variant="outline" className="bg-white">Level {approver.level}</Badge>
                                    <div className="flex-1">
                                        <div className="font-medium text-gray-900">{approver.name}</div>
                                        <div className="text-sm text-gray-500">{approver.email}</div>
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <div className="flex flex-col gap-1">
                                            <Label htmlFor={`tat-${index}`} className="text-xs whitespace-nowrap">TAT</Label>
                                            <div className="flex items-center gap-1">
                                                <Input
                                                    id={`tat-${index}`}
                                                    type="number"
                                                    className="h-8 w-16 border-gray-200"
                                                    value={approver.tat || ''}
                                                    min={1}
                                                    max={approver.tatType === 'days' ? 7 : 24}
                                                    placeholder={approver.tatType === 'days' ? '1' : '24'}
                                                    onChange={(e) => {
                                                        const val = parseInt(e.target.value) || 0;
                                                        // const max = approver.tatType === 'days' ? 7 : 24;
                                                        // Optional: strict clamping or just allow typing and validate later
                                                        // For better UX, let's allow typing but validate in isFormValid
                                                        // But prevent entering negative numbers
                                                        if (val < 0) return;

                                                        const newApprovers = [...formData.approvers];
                                                        newApprovers[index].tat = e.target.value; // Store as string to allow clearing
                                                        setFormData(prev => ({ ...prev, approvers: newApprovers }));
                                                    }}
                                                />
                                                <Select
                                                    value={approver.tatType || 'hours'}
                                                    onValueChange={(val) => {
                                                        const newApprovers = [...formData.approvers];
                                                        newApprovers[index].tatType = val;
                                                        newApprovers[index].tat = 1; // Reset to 1 on change
                                                        setFormData(prev => ({ ...prev, approvers: newApprovers }));
                                                    }}
                                                >
                                                    <SelectTrigger className="h-8 w-20 text-xs px-2">
                                                        <SelectValue />
                                                    </SelectTrigger>
                                                    <SelectContent>
                                                        <SelectItem value="hours">Hours</SelectItem>
                                                        <SelectItem value="days">Days</SelectItem>
                                                    </SelectContent>
                                                </Select>
                                            </div>
                                        </div>
                                    </div>
                                    <Button type="button" variant="ghost" size="sm" onClick={() => removeApprover(index)}>
                                        <X className="w-4 h-4 text-gray-500 hover:text-red-600" />
                                    </Button>
                                </div>
                            ))}

                            {formData.approvers.length === 0 && (
                                <div className="text-center p-8 border-2 border-dashed rounded-lg text-gray-500 text-sm">
                                    No approvers defined. Requests will be auto-approved or require manual assignment.
                                </div>
                            )}
                        </div>

                        <div className="space-y-2 relative">
                            <Label>Add Approver</Label>
                            <div className="flex gap-2">
                                <Input
                                    placeholder="Type '@' to search user by name or email..."
                                    value={approverSearchInput}
                                    onChange={(e) => handleApproverSearch(e.target.value)}
                                    className="border-gray-200"
                                />
                            </div>

                            {(searchLoading || searchResults.length > 0) && (
                                <div className="absolute top-full left-0 right-0 mt-1 bg-white border rounded-lg shadow-lg z-10 max-h-60 overflow-y-auto">
                                    {searchLoading && <div className="p-2 text-sm text-gray-500">Searching...</div>}
                                    {searchResults.map(user => (
                                        <div
                                            key={user.userId}
                                            className="p-2 hover:bg-gray-50 cursor-pointer flex items-center gap-3"
                                            onClick={() => addApprover(user)}
                                        >
                                            <Avatar className="h-8 w-8">
                                                <AvatarFallback>{(user.displayName || 'U').substring(0, 2)}</AvatarFallback>
                                            </Avatar>
                                            <div>
                                                <div className="text-sm font-medium">{user.displayName}</div>
                                                <div className="text-xs text-gray-500">{user.email}</div>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            )}
                        </div>

                        {/* TAT Summary */}
                        {formData.approvers.length > 0 && (
                            <div className="mt-6 p-4 bg-gradient-to-r from-emerald-50 to-teal-50 rounded-lg border border-emerald-200">
                                <div className="flex items-start gap-3">
                                    <Clock className="w-5 h-5 text-emerald-600 mt-0.5" />
                                    <div className="flex-1">
                                        <div className="flex items-center justify-between mb-2">
                                            <h4 className="font-semibold text-emerald-900">TAT Summary</h4>
                                            <div className="text-right">
                                                {(() => {
                                                    const totalCalendarDays = formData.approvers.reduce((sum: number, a: any) => {
                                                        const tat = Number(a.tat || 0);
                                                        const tatType = a.tatType || 'hours';
                                                        if (tatType === 'days') {
                                                            return sum + tat;
                                                        } else {
                                                            return sum + (tat / 24);
                                                        }
                                                    }, 0) || 0;
                                                    const displayDays = Math.ceil(totalCalendarDays);
                                                    return (
                                                        <>
                                                            <div className="text-lg font-bold text-emerald-800">{displayDays} {displayDays === 1 ? 'Day' : 'Days'}</div>
                                                            <div className="text-xs text-emerald-600">Total Duration</div>
                                                        </>
                                                    );
                                                })()}
                                            </div>
                                        </div>
                                        <div className="space-y-3">
                                            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                                {formData.approvers.map((approver: any, idx: number) => {
                                                    const tat = Number(approver.tat || 0);
                                                    const tatType = approver.tatType || 'hours';
                                                    const hours = tatType === 'days' ? tat * 24 : tat;
                                                    if (!tat) return null;
                                                    return (
                                                        <div key={idx} className="bg-white/60 p-2 rounded border border-emerald-100">
                                                            <div className="flex items-center justify-between">
                                                                <span className="text-sm font-medium text-emerald-900">Level {idx + 1}</span>
                                                                <span className="text-sm text-emerald-700">{hours} {hours === 1 ? 'hour' : 'hours'}</span>
                                                            </div>
                                                        </div>
                                                    );
                                                })}
                                            </div>
                                            {(() => {
                                                const totalHours = formData.approvers.reduce((sum: number, a: any) => {
                                                    const tat = Number(a.tat || 0);
                                                    const tatType = a.tatType || 'hours';
                                                    if (tatType === 'days') {
                                                        return sum + (tat * 24);
                                                    } else {
                                                        return sum + tat;
                                                    }
                                                }, 0) || 0;
                                                const workingDays = Math.ceil(totalHours / 8);
                                                if (totalHours === 0) return null;
                                                return (
                                                    <div className="bg-white/80 p-3 rounded border border-emerald-200">
                                                        <div className="grid grid-cols-2 gap-4 text-center">
                                                            <div>
                                                                <div className="text-lg font-bold text-emerald-800">{totalHours}h</div>
                                                                <div className="text-xs text-emerald-600">Total Hours</div>
                                                            </div>
                                                            <div>
                                                                <div className="text-lg font-bold text-emerald-800">{workingDays}</div>
                                                                <div className="text-xs text-emerald-600">Working Days*</div>
                                                            </div>
                                                        </div>
                                                        <p className="text-xs text-emerald-600 mt-2 text-center">*Based on 8-hour working days</p>
                                                    </div>
                                                );
                                            })()}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        )}
                    </CardContent>
                </Card>

                <div className="flex justify-end gap-3 pt-4">
                    <Button type="button" variant="outline" onClick={() => navigate('/admin/templates')}>Cancel</Button>
                    <Button type="submit" disabled={loading || !isFormValid} className="bg-re-green hover:bg-re-green/90">
                        {loading ? 'Saving...' : (
                            <>
                                <Save className="w-4 h-4 mr-2" />
                                {isEditing ? 'Update Template' : 'Create Template'}
                            </>
                        )}
                    </Button>
                </div>
            </form>
        </div>
    );
}
