import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { ArrowLeft, ChevronRight, Check } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useAuth } from '@/contexts/AuthContext';
import { getTemplates, WorkflowTemplate as BackendTemplate } from '@/services/workflowTemplateApi';
import { createWorkflowMultipart, submitWorkflow, CreateWorkflowFromFormPayload } from '@/services/workflowApi';
import { RequestTemplate } from '@/hooks/useCreateRequestForm';
import { FileText } from 'lucide-react';
import { AdminRequestDetailsStep } from './components/AdminRequestDetailsStep';
import { AdminRequestReviewStep } from './components/AdminRequestReviewStep';
import { toast } from 'sonner';

import { WizardStepper } from '@/components/workflow/CreateRequest/WizardStepper';

export function CreateAdminRequest() {
    const { templateId } = useParams<{ templateId: string }>();
    const navigate = useNavigate();
    const { user: _ } = useAuth(); // Keeping hook call but ignoring return if needed for auth check side effect, or just remove destructuring

    const [loading, setLoading] = useState(true);
    const [submitting, setSubmitting] = useState(false);
    const [template, setTemplate] = useState<RequestTemplate | null>(null);
    const [step, setStep] = useState(1);
    const [documents, setDocuments] = useState<File[]>([]);

    // Simplified form data
    const [formData, setFormData] = useState({
        title: '',
        description: '',
    });

    const stepNames = ['Request Details', 'Review & Submit'];

    useEffect(() => {
        const loadTemplate = async () => {
            try {
                setLoading(true);
                // Ideally we would have a getTemplateById API, but for now we filter from list
                // Optimization: In a real app, create a specific endpoint
                const templates = await getTemplates();
                const found = templates.find((t: BackendTemplate) => t.id === templateId);

                if (found) {
                    const mapped: RequestTemplate = {
                        id: found.id,
                        name: found.name,
                        description: found.description,
                        category: found.category,
                        icon: FileText,
                        estimatedTime: found.estimatedTime,
                        commonApprovers: found.approvers.map((a: any) => a.name),
                        workflowApprovers: found.approvers,
                        suggestedSLA: found.suggestedSLA,
                        priority: found.priority,
                        fields: found.fields || {}
                    };
                    setTemplate(mapped);

                    // Pre-fill
                    setFormData({
                        title: mapped.name,
                        description: mapped.description
                    });
                } else {
                    toast.error('Template not found');
                    // navigate('/new-request'); // Removed to prevent potential redirect loops
                    // We will show the "Template not found" UI below since template is null
                }
            } catch (error) {
                console.error('Error loading template:', error);
                toast.error('Failed to load template details');
            } finally {
                setLoading(false);
            }
        };

        if (templateId) {
            loadTemplate();
        }
    }, [templateId, navigate]);

    const handleSubmit = async () => {
        if (!template) return;

        try {
            setSubmitting(true);

            const formPayload: CreateWorkflowFromFormPayload = {
                templateId: template.id,
                templateType: 'TEMPLATE',
                title: formData.title,
                description: formData.description,
                priorityUi: template.priority === 'high' ? 'express' : 'standard',
                approverCount: template.workflowApprovers?.length || 0,
                approvers: (template.workflowApprovers || []).map((a: any) => ({
                    email: a.email,
                    name: a.name,
                    tat: a.tat,
                    tatType: 'hours'
                })),
                spectators: [],
                ccList: []
            };

            const response = await createWorkflowMultipart(formPayload, documents);

            if (response && response.id) {
                await submitWorkflow(response.id);
            }

            toast.success('Request Submitted Successfully', {
                description: `Your request "${formData.title}" has been created.`
            });

            navigate('/my-requests');

        } catch (error) {
            console.error('Submission failed:', error);
            toast.error('Failed to submit request');
        } finally {
            setSubmitting(false);
        }
    };

    if (loading) {
        return (
            <div className="min-h-screen bg-gray-50 flex items-center justify-center">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            </div>
        );
    }

    if (!template) {
        return (
            <div className="min-h-screen bg-gray-50 flex flex-col items-center justify-center p-4">
                <div className="bg-white p-8 rounded-lg shadow-md max-w-md w-full text-center">
                    <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <FileText className="w-8 h-8 text-red-600" />
                    </div>
                    <h2 className="text-2xl font-bold text-gray-900 mb-2">Template Not Found</h2>
                    <p className="text-gray-600 mb-6">
                        The requested template could not be loaded. It may have been deleted or you do not have permission to view it.
                    </p>
                    <div className="flex gap-3 justify-center">
                        <Button variant="outline" onClick={() => navigate('/dashboard')}>
                            Go to Dashboard
                        </Button>
                        <Button onClick={() => navigate('/new-request')}>
                            Browse Templates
                        </Button>
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="h-screen flex flex-col bg-gray-50 overflow-hidden">
            {/* Header */}
            <header className="bg-white border-b flex-shrink-0 z-10">
                <div className="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
                    <div className="flex items-center gap-4">
                        <Button variant="ghost" size="icon" onClick={() => navigate('/new-request')}>
                            <ArrowLeft className="w-5 h-5 text-gray-500" />
                        </Button>
                        <div>
                            <h1 className="text-xl font-bold text-gray-900">New Request</h1>
                            <p className="text-sm text-gray-500">{template.name}</p>
                        </div>
                    </div>
                    <Button variant="outline" onClick={() => navigate('/dashboard')}>
                        Cancel Request
                    </Button>
                </div>

                {/* Stepper */}
                <WizardStepper
                    currentStep={step}
                    totalSteps={2}
                    stepNames={stepNames}
                />
            </header>

            {/* Content */}
            <main className="flex-1 overflow-y-auto py-8 px-6 bg-gray-50/50">
                <div className="max-w-4xl mx-auto">
                    {step === 1 ? (
                        <AdminRequestDetailsStep
                            template={template}
                            formData={formData}
                            setFormData={setFormData}
                            documents={documents}
                            setDocuments={setDocuments}
                        />
                    ) : (
                        <AdminRequestReviewStep
                            template={template}
                            formData={formData}
                            documents={documents}
                        />
                    )}
                </div>
            </main>

            {/* Footer Actions */}
            <footer className="bg-white border-t px-6 py-4 flex-shrink-0 z-10">
                <div className="max-w-4xl mx-auto flex items-center justify-between">
                    <Button
                        variant="outline"
                        onClick={() => step === 1 ? navigate('/new-request') : setStep(1)}
                        disabled={submitting}
                    >
                        {step === 1 ? 'Cancel' : 'Back to Details'}
                    </Button>

                    <Button
                        onClick={() => step === 1 ? setStep(2) : handleSubmit()}
                        disabled={submitting}
                        className={step === 2 ? "bg-re-green hover:bg-re-green/90" : "bg-re-green hover:bg-re-green/90"}
                    >
                        {step === 1 ? (
                            <>Review Request <ChevronRight className="w-4 h-4 ml-1" /></>
                        ) : (
                            <>{submitting ? 'Submitting...' : 'Submit Request'} <Check className="w-4 h-4 ml-1" /></>
                        )}
                    </Button>
                </div>
            </footer>
        </div>
    );
}
