"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Header from "@/app/components/Header";
import Footer from "@/app/components/Footer";
import { ArrowLeft, Upload, X, FileText, CheckCircle2, AlertCircle, Loader2, IndianRupee } from "lucide-react";
import { useApplyForTenderMutation } from "@/redux/apis/tenderApplyApi";
import { useGetTenderByIdQuery } from "@/redux/apis/tenderApi";
import { motion, AnimatePresence } from "framer-motion";

interface ApplyTenderClientProps {
    tenderId: string;
}

export default function ApplyTenderClient({ tenderId }: ApplyTenderClientProps) {
    const router = useRouter();
    const [files, setFiles] = useState<File[]>([]);
    const [quotation, setQuotation] = useState("");
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [success, setSuccess] = useState(false);

    const { data: tenderData, isLoading: isLoadingTender } = useGetTenderByIdQuery(parseInt(tenderId));
    const [applyForTender] = useApplyForTenderMutation();

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files) {
            const newFiles = Array.from(e.target.files);
            setFiles(prev => [...prev, ...newFiles]);
        }
    };

    const removeFile = (index: number) => {
        setFiles(prev => prev.filter((_, i) => i !== index));
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setError(null);

        if (files.length === 0) {
            setError("Please upload at least one document");
            return;
        }

        if (!quotation) {
            setError("Please enter your quotation amount");
            return;
        }

        setIsSubmitting(true);
        try {
            const formData = new FormData();
            formData.append("tenderId", tenderId);
            formData.append("quotation", quotation);

            files.forEach((file) => {
                formData.append("documents", file);
            });

            await applyForTender(formData).unwrap();
            setSuccess(true);
            setTimeout(() => {
                router.push(`/tenders/${tenderId}`);
            }, 2000);
        } catch (err: any) {
            console.error("Application failed:", err);
            setError(err?.data?.message || "Failed to submit application. Please try again.");
        } finally {
            setIsSubmitting(false);
        }
    };

    if (isLoadingTender) {
        return (
            <div className="min-h-screen bg-gray-50 flex flex-col">
                <Header />
                <div className="flex-grow flex items-center justify-center">
                    <Loader2 className="w-8 h-8 text-green-600 animate-spin" />
                </div>
                <Footer />
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-gray-50 flex flex-col font-sans">
            <Header />

            <main className="flex-grow pt-24 sm:pt-28 pb-12 px-4 sm:px-6 lg:px-8">
                <div className="max-w-3xl mx-auto">
                    <button
                        onClick={() => router.back()}
                        className="mb-6 flex items-center gap-2 text-gray-600 hover:text-green-600 transition-colors font-medium"
                    >
                        <ArrowLeft className="w-4 h-4" />
                        Back to Tender Details
                    </button>

                    <div className="bg-white rounded-2xl shadow-xl border border-gray-100 overflow-hidden">
                        {/* Status Header */}
                        <div className={`px-6 py-8 text-center text-white ${success ? 'bg-green-600' : 'bg-[#0066cc]'}`}>
                            <AnimatePresence mode="wait">
                                {success ? (
                                    <motion.div
                                        initial={{ opacity: 0, scale: 0.9 }}
                                        animate={{ opacity: 1, scale: 1 }}
                                        className="flex flex-col items-center"
                                    >
                                        <div className="w-16 h-16 bg-white/20 rounded-full flex items-center justify-center mb-4">
                                            <CheckCircle2 className="w-10 h-10 text-white" />
                                        </div>
                                        <h1 className="text-2xl font-bold">Application Submitted!</h1>
                                        <p className="mt-2 text-white/80">Refirecting you back to tender details...</p>
                                    </motion.div>
                                ) : (
                                    <div className="flex flex-col items-center">
                                        <div className="w-16 h-16 bg-white/10 rounded-full flex items-center justify-center mb-4">
                                            <Upload className="w-8 h-8 text-white" />
                                        </div>
                                        <h1 className="text-2xl font-bold uppercase tracking-wide">Tender Application Form</h1>
                                        <p className="mt-2 text-white/70 max-w-md mx-auto line-clamp-1">
                                            {tenderData?.data?.tenderTitle}
                                        </p>
                                    </div>
                                )}
                            </AnimatePresence>
                        </div>

                        {!success && (
                            <form onSubmit={handleSubmit} className="p-6 sm:p-10 space-y-8">
                                {/* Error Message */}
                                {error && (
                                    <motion.div
                                        initial={{ opacity: 0, y: -10 }}
                                        animate={{ opacity: 1, y: 0 }}
                                        className="p-4 bg-red-50 border-l-4 border-red-500 rounded-lg flex items-center gap-3 text-red-700"
                                    >
                                        <AlertCircle className="w-5 h-5 shrink-0" />
                                        <p className="text-sm font-medium">{error}</p>
                                    </motion.div>
                                )}

                                {/* Quotation Field */}
                                <div className="space-y-2">
                                    <label className="text-sm font-bold text-gray-700 uppercase tracking-wider flex items-center gap-2">
                                        <IndianRupee className="w-4 h-4 text-[#0066cc]" />
                                        Your Quotation Amount
                                    </label>
                                    <div className="relative group">
                                        <div className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-[#0066cc] transition-colors">
                                            ₹
                                        </div>
                                        <input
                                            type="number"
                                            value={quotation}
                                            onChange={(e) => setQuotation(e.target.value)}
                                            placeholder="Enter total amount (Ex: 500000)"
                                            className="w-full pl-10 pr-4 py-4 bg-gray-50 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[#0066cc] focus:border-transparent transition-all outline-none font-medium text-gray-900"
                                            required
                                        />
                                    </div>
                                    <p className="text-[11px] text-gray-500">Enter the total bid value for this tender.</p>
                                </div>

                                {/* File Upload Area */}
                                <div className="space-y-4">
                                    <label className="text-sm font-bold text-gray-700 uppercase tracking-wider flex items-center gap-2">
                                        <FileText className="w-4 h-4 text-[#0066cc]" />
                                        Technical & Financial Documents
                                    </label>

                                    <div className="relative">
                                        <input
                                            type="file"
                                            id="multiple-files"
                                            className="hidden"
                                            onChange={handleFileChange}
                                            multiple
                                            accept=".pdf,.doc,.docx,.jpg,.jpeg,.png"
                                        />

                                        <label
                                            htmlFor="multiple-files"
                                            className="flex flex-col items-center justify-center p-10 border-2 border-dashed border-gray-200 rounded-2xl bg-gray-50 hover:bg-gray-100 hover:border-[#0066cc] transition-all cursor-pointer group"
                                        >
                                            <div className="w-14 h-14 bg-white rounded-xl shadow-md flex items-center justify-center mb-4 group-hover:scale-110 transition-transform">
                                                <Upload className="w-6 h-6 text-[#0066cc]" />
                                            </div>
                                            <p className="text-gray-900 font-bold">Choose files to upload</p>
                                            <p className="text-sm text-gray-500 mt-1">PDF, Images or Word documents (Max 50MB each)</p>
                                        </label>
                                    </div>

                                    {/* Selected Files List */}
                                    <AnimatePresence>
                                        {files.length > 0 && (
                                            <motion.div
                                                initial={{ opacity: 0, height: 0 }}
                                                animate={{ opacity: 1, height: 'auto' }}
                                                exit={{ opacity: 0, height: 0 }}
                                                className="grid grid-cols-1 gap-3 pt-2"
                                            >
                                                {files.map((file, idx) => (
                                                    <motion.div
                                                        key={idx}
                                                        layout
                                                        initial={{ x: -20, opacity: 0 }}
                                                        animate={{ x: 0, opacity: 1 }}
                                                        className="flex items-center justify-between p-3 bg-white border border-gray-100 rounded-xl shadow-sm hover:shadow-md transition-shadow"
                                                    >
                                                        <div className="flex items-center gap-3 overflow-hidden">
                                                            <div className="w-10 h-10 bg-blue-50 text-[#0066cc] rounded-lg flex items-center justify-center shrink-0">
                                                                <FileText className="w-5 h-5" />
                                                            </div>
                                                            <div className="overflow-hidden">
                                                                <p className="text-sm font-bold text-gray-900 truncate">{file.name}</p>
                                                                <p className="text-[10px] text-gray-500 uppercase tracking-wider">{(file.size / 1024 / 1024).toFixed(2)} MB</p>
                                                            </div>
                                                        </div>
                                                        <button
                                                            type="button"
                                                            onClick={() => removeFile(idx)}
                                                            className="p-2 text-gray-400 hover:text-red-500 transition-colors"
                                                        >
                                                            <X className="w-5 h-5" />
                                                        </button>
                                                    </motion.div>
                                                ))}
                                            </motion.div>
                                        )}
                                    </AnimatePresence>
                                </div>

                                {/* Form Footer */}
                                <div className="flex flex-col sm:flex-row gap-4 pt-4">
                                    <button
                                        type="submit"
                                        disabled={isSubmitting || files.length === 0}
                                        className={`flex-1 py-4 px-8 rounded-xl font-bold flex items-center justify-center gap-2 shadow-lg transition-all active:scale-95 ${isSubmitting || files.length === 0
                                            ? "bg-gray-200 text-gray-400 cursor-not-allowed shadow-none"
                                            : "bg-[#0066cc] text-white hover:bg-[#0052a3] hover:shadow-blue-200"
                                            }`}
                                    >
                                        {isSubmitting ? (
                                            <>
                                                <Loader2 className="w-5 h-5 animate-spin" />
                                                Processing...
                                            </>
                                        ) : (
                                            "Submit Final Application"
                                        )}
                                    </button>

                                    <button
                                        type="button"
                                        onClick={() => router.back()}
                                        className="py-4 px-8 bg-white border border-gray-200 text-gray-700 font-bold rounded-xl hover:bg-gray-50 transition-all active:scale-95"
                                    >
                                        Cancel
                                    </button>
                                </div>
                            </form>
                        )}
                    </div>
                </div>
            </main>
            <Footer />
        </div>
    );
}

function FileIcon() {
    return (
        <svg className="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
        </svg>
    );
}
