"use client";

import { useGetMyApplicationsQuery } from "@/redux/apis/tenderApplyApi";
import Header from "../components/Header";
import Footer from "../components/Footer";
import { motion } from "framer-motion";
import Link from "next/link";
import { ArrowLeft, FileText, Clock, CheckCircle, XCircle, MapPin, IndianRupee, Calendar } from "lucide-react";

export default function MyAppliedTendersPage() {
  const { data: applicationsData, isLoading, error } = useGetMyApplicationsQuery();

  const getStatusColor = (status: string) => {
    switch (status.toLowerCase()) {
      case "accepted":
        return "bg-green-100 text-green-800 border-green-200";
      case "reviewed":
        return "bg-blue-100 text-blue-800 border-blue-200";
      case "pending":
        return "bg-yellow-100 text-yellow-800 border-yellow-200";
      case "rejected":
        return "bg-red-100 text-red-800 border-red-200";
      default:
        return "bg-gray-100 text-gray-800 border-gray-200";
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status.toLowerCase()) {
      case "accepted":
        return <CheckCircle className="w-4 h-4" />;
      case "reviewed":
        return <FileText className="w-4 h-4" />;
      case "pending":
        return <Clock className="w-4 h-4" />;
      case "rejected":
        return <XCircle className="w-4 h-4" />;
      default:
        return null;
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col font-sans">
      <Header />

      <main className="flex-grow pt-24 sm:pt-32 pb-16 px-4 sm:px-6 lg:px-8">
        <div className="max-w-5xl mx-auto">
          {/* Header Section */}
          <div className="flex flex-col md:flex-row md:items-center justify-between mb-8 gap-4">
            <div>
              <Link
                href="/profile"
                className="inline-flex items-center gap-2 text-gray-500 hover:text-primary-600 transition-colors text-sm mb-2"
              >
                <ArrowLeft className="w-4 h-4" />
                Back to Profile
              </Link>
              <h1 className="text-3xl font-bold text-gray-900 tracking-tight">My Applied Tenders</h1>
              <p className="text-gray-500 mt-1">Track and manage all your tender applications in one place.</p>
            </div>

            <div className="bg-white px-4 py-2 rounded-xl border border-gray-200 shadow-sm flex items-center gap-3">
              <div className="w-10 h-10 bg-primary-50 rounded-lg flex items-center justify-center">
                <FileText className="w-5 h-5 text-primary-600" />
              </div>
              <div>
                <p className="text-xs text-gray-500 font-medium uppercase tracking-wider">Total Applications</p>
                <p className="text-lg font-bold text-gray-900">{applicationsData?.data?.length || 0}</p>
              </div>
            </div>
          </div>

          {isLoading ? (
            <div className="grid gap-6">
              {[1, 2, 3].map((i) => (
                <div key={i} className="bg-white h-48 rounded-2xl animate-pulse border border-gray-100 shadow-sm" />
              ))}
            </div>
          ) : error ? (
            <div className="bg-white p-12 rounded-2xl border border-gray-100 shadow-sm text-center">
              <XCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
              <h3 className="text-lg font-bold text-gray-900">Failed to load applications</h3>
              <p className="text-gray-500 mt-2">There was an error fetching your data. Please try again later.</p>
            </div>
          ) : !applicationsData?.data || applicationsData.data.length === 0 ? (
            <div className="bg-white p-16 rounded-2xl border border-gray-100 shadow-sm text-center flex flex-col items-center">
              <div className="w-20 h-20 bg-gray-50 rounded-full flex items-center justify-center mb-6">
                <FileText className="w-10 h-10 text-gray-300" />
              </div>
              <h3 className="text-xl font-bold text-gray-900">No Applications Found</h3>
              <p className="text-gray-500 mt-2 max-w-xs mx-auto mb-8">
                You haven&apos;t applied for any tenders yet. Explore live tenders and start applying today!
              </p>
              <Link
                href="/tenders"
                className="bg-primary-600 text-white px-8 py-3 rounded-xl font-bold shadow-lg shadow-primary-600/20 hover:bg-primary-700 transition-all active:scale-95"
              >
                Browse Live Tenders
              </Link>
            </div>
          ) : (
            <div className="grid gap-6">
              {applicationsData.data.map((app: any, idx) => (
                <motion.div
                  key={app.id}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: idx * 0.1 }}
                  className="bg-white rounded-2xl border border-gray-100 shadow-sm hover:shadow-xl transition-all group overflow-hidden"
                >
                  <div className="p-6 md:p-8">
                    <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4 mb-6">
                      <div className="flex-1">
                        <div className="flex items-center gap-3 mb-2">
                          <span className={`px-3 py-1 rounded-full text-xs font-bold border flex items-center gap-1.5 ${getStatusColor(app.status)}`}>
                            {getStatusIcon(app.status)}
                            {app.status.toUpperCase()}
                          </span>
                          <span className="text-[10px] text-gray-400 font-bold uppercase tracking-widest">
                            REF: #{app.id.toString().padStart(5, '0')}
                          </span>
                        </div>
                        <h3 className="text-xl font-bold text-gray-900 group-hover:text-primary-600 transition-colors line-clamp-2">
                          {app.tender?.tenderTitle || "Tender Application"}
                        </h3>
                      </div>

                      <div className="text-left lg:text-right shrink-0">
                        <p className="text-xs text-gray-500 uppercase font-bold tracking-wider mb-1">Your Quotation</p>
                        <p className="text-2xl font-black text-gray-900 flex items-center lg:justify-end gap-1">
                          <IndianRupee className="w-5 h-5" />
                          {app.quotation?.toLocaleString('en-IN') || "0"}
                        </p>
                      </div>
                    </div>

                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 pt-6 border-t border-gray-50">
                      <div className="flex items-center gap-3">
                        <div className="w-9 h-9 bg-gray-50 rounded-lg flex items-center justify-center text-gray-400">
                          <MapPin className="w-4 h-4" />
                        </div>
                        <div>
                          <p className="text-[10px] text-gray-400 font-bold uppercase tracking-wider">Location</p>
                          <p className="text-sm font-semibold text-gray-700">{app.tender?.city || app.tender?.state || "N/A"}</p>
                        </div>
                      </div>

                      <div className="flex items-center gap-3">
                        <div className="w-9 h-9 bg-gray-50 rounded-lg flex items-center justify-center text-gray-400">
                          <Calendar className="w-4 h-4" />
                        </div>
                        <div>
                          <p className="text-[10px] text-gray-400 font-bold uppercase tracking-wider">Applied Date</p>
                          <p className="text-sm font-semibold text-gray-700">{new Date(app.createdAt).toLocaleDateString('en-IN', { day: 'numeric', month: 'short', year: 'numeric' })}</p>
                        </div>
                      </div>

                      <div className="flex items-center gap-3">
                        <div className="w-9 h-9 bg-gray-50 rounded-lg flex items-center justify-center text-gray-400">
                          <FileText className="w-4 h-4" />
                        </div>
                        <div>
                          <p className="text-[10px] text-gray-400 font-bold uppercase tracking-wider">Documents</p>
                          <p className="text-sm font-semibold text-gray-700">
                            {(() => {
                              try {
                                const docs = JSON.parse(app.documents);
                                return `${docs.length} File(s)`;
                              } catch { return "1 File"; }
                            })()}
                          </p>
                        </div>
                      </div>

                      <div className="flex items-center lg:justify-end">
                        <Link
                          href={`/tenders/${app.tenderId}`}
                          className="w-full sm:w-auto text-center px-6 py-2.5 bg-gray-900 text-white rounded-xl text-sm font-bold hover:bg-gray-800 transition-colors shadow-lg shadow-gray-200"
                        >
                          View Tender
                        </Link>
                      </div>
                    </div>
                  </div>
                </motion.div>
              ))}
            </div>
          )}
        </div>
      </main>

      <Footer />
    </div>
  );
}
