"use client";

import { useState } from "react";
import Layout from "../../components/Layout";
import { useGetApplicationsQuery, useUpdateApplicationStatusMutation } from "@/redux/apis/financeApi";
import { Search, Filter, Clock, CheckCircle2, XCircle, FileText } from "lucide-react";

export default function FinanceRequestsPage() {
    const [page, setPage] = useState(1);
    const [search, setSearch] = useState("");
    const [statusFilter, setStatusFilter] = useState("all");

    const { data: response, isLoading } = useGetApplicationsQuery({
        page,
        limit: 10,
        status: statusFilter !== 'all' ? statusFilter : undefined,
        search: search || undefined,
    });

    const [updateStatus, { isLoading: isUpdating }] = useUpdateApplicationStatusMutation();

    const handleStatusChange = async (id: number, status: string) => {
        if (confirm(`Are you sure you want to mark this application as ${status}?`)) {
            try {
                await updateStatus({ id, status }).unwrap();
            } catch (error) {
                console.error("Failed to update status", error);
                alert("Failed to update status");
            }
        }
    };

    const getStatusBadge = (status: string) => {
        switch (status) {
            case "approved":
                return (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium bg-green-50 text-green-700 border border-green-100">
                        <CheckCircle2 className="w-3.5 h-3.5" />
                        Approved
                    </span>
                );
            case "rejected":
                return (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium bg-red-50 text-red-700 border border-red-100">
                        <XCircle className="w-3.5 h-3.5" />
                        Rejected
                    </span>
                );
            case "reviewed":
                return (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium bg-blue-50 text-blue-700 border border-blue-100">
                        <FileText className="w-3.5 h-3.5" />
                        Reviewed
                    </span>
                );
            default:
                return (
                    <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium bg-amber-50 text-amber-700 border border-amber-100">
                        <Clock className="w-3.5 h-3.5" />
                        Pending
                    </span>
                );
        }
    };

    return (
        <Layout>
            <div className="flex flex-col h-full bg-gray-50">
                {/* Header Toolbar - Sticky */}
                <div className="bg-white border-b border-gray-200 sticky top-0 z-20 px-6 py-4 shadow-sm flex flex-col md:flex-row md:items-center justify-between gap-4">
                    <div>
                        <h1 className="text-xl font-bold text-gray-900 tracking-tight">Finance Applications</h1>
                        <p className="text-sm text-gray-500 mt-0.5">Manage and review incoming loan requests</p>
                    </div>

                    <div className="flex items-center gap-3">
                        <div className="flex items-center bg-gray-100 rounded-lg p-1 border border-gray-200 transition-shadow focus-within:ring-2 focus-within:ring-blue-500/20 focus-within:border-blue-500/50">
                            <div className="relative">
                                <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
                                <input
                                    type="text"
                                    placeholder="Search by name, email..."
                                    className="pl-9 pr-4 py-1.5 bg-transparent border-none focus:ring-0 text-sm w-48 md:w-64 text-gray-900 placeholder-gray-500"
                                    value={search}
                                    onChange={(e) => setSearch(e.target.value)}
                                />
                            </div>
                            <div className="w-px h-5 bg-gray-300 mx-1"></div>
                            <div className="relative flex items-center pr-2">
                                <select
                                    className="appearance-none bg-transparent border-none focus:ring-0 text-sm text-gray-700 font-medium cursor-pointer pr-6 py-1.5 pl-2"
                                    value={statusFilter}
                                    onChange={(e) => {
                                        setStatusFilter(e.target.value);
                                        setPage(1);
                                    }}
                                >
                                    <option value="all">All Status</option>
                                    <option value="pending">Pending</option>
                                    <option value="reviewed">Reviewed</option>
                                    <option value="approved">Approved</option>
                                    <option value="rejected">Rejected</option>
                                </select>
                                <Filter className="w-3.5 h-3.5 absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 pointer-events-none" />
                            </div>
                        </div>
                    </div>
                </div>

                {/* Table Content */}
                <div className="flex-1 p-6 overflow-hidden flex flex-col">
                    <div className="bg-white rounded-xl shadow-sm border border-gray-200 flex-1 overflow-hidden flex flex-col">
                        <div className="overflow-auto flex-1">
                            <table className="w-full text-left text-sm text-gray-600">
                                <thead className="bg-gray-50/80 backdrop-blur-sm text-xs uppercase font-medium text-gray-500 sticky top-0 z-10 border-b border-gray-200">
                                    <tr>
                                        <th className="px-6 py-4 font-semibold tracking-wider">Date</th>
                                        <th className="px-6 py-4 font-semibold tracking-wider">Applicant</th>
                                        <th className="px-6 py-4 font-semibold tracking-wider">Company Details</th>
                                        <th className="px-6 py-4 font-semibold tracking-wider">Loan Request</th>
                                        <th className="px-6 py-4 font-semibold tracking-wider">Status</th>
                                        <th className="px-6 py-4 font-semibold tracking-wider text-right">Actions</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-100">
                                    {isLoading ? (
                                        <tr>
                                            <td colSpan={6} className="px-6 py-12 text-center text-gray-500">
                                                <div className="flex flex-col items-center justify-center gap-2">
                                                    <div className="w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
                                                    <p>Loading applications...</p>
                                                </div>
                                            </td>
                                        </tr>
                                    ) : response?.data.length === 0 ? (
                                        <tr>
                                            <td colSpan={6} className="px-6 py-12 text-center text-gray-500">
                                                No applications found matching your search.
                                            </td>
                                        </tr>
                                    ) : (
                                        response?.data.map((app) => (
                                            <tr key={app.id} className="hover:bg-blue-50/50 transition-colors group">
                                                <td className="px-6 py-4 whitespace-nowrap text-gray-500">
                                                    {new Date(app.createdAt).toLocaleDateString("en-US", { year: 'numeric', month: 'short', day: 'numeric' })}
                                                </td>
                                                <td className="px-6 py-4">
                                                    <div className="flex flex-col">
                                                        <span className="font-semibold text-gray-900 group-hover:text-blue-700 transition-colors">{app.fullName}</span>
                                                        <span className="text-xs text-gray-500">{app.email}</span>
                                                        <span className="text-xs text-gray-400 font-mono mt-0.5">{app.mobileNumber}</span>
                                                    </div>
                                                </td>
                                                <td className="px-6 py-4">
                                                    <div className="font-medium text-gray-900">{app.companyName}</div>
                                                    <div className="text-xs text-gray-500 bg-gray-100 inline-block px-1.5 py-0.5 rounded mt-1 border border-gray-200">
                                                        TO: {app.annualTurnover}
                                                    </div>
                                                </td>
                                                <td className="px-6 py-4">
                                                    <div className="font-semibold text-gray-900">{app.loanType}</div>
                                                    <div className="text-sm text-green-600 font-medium">{app.loanAmount}</div>
                                                    {app.purpose && (
                                                        <div className="text-xs text-gray-400 mt-1 truncate max-w-[150px]" title={app.purpose}>
                                                            {app.purpose}
                                                        </div>
                                                    )}
                                                </td>
                                                <td className="px-6 py-4">
                                                    {getStatusBadge(app.status)}
                                                </td>
                                                <td className="px-6 py-4 text-right">
                                                    <select
                                                        className="px-2.5 py-1.5 text-xs font-medium border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 bg-white text-gray-700 shadow-sm transition-all hover:border-gray-400"
                                                        value={app.status}
                                                        onChange={(e) => handleStatusChange(app.id, e.target.value)}
                                                        disabled={isUpdating}
                                                    >
                                                        <option value="pending">Pending</option>
                                                        <option value="reviewed">Mark Reviewed</option>
                                                        <option value="approved">Approve</option>
                                                        <option value="rejected">Reject</option>
                                                    </select>
                                                </td>
                                            </tr>
                                        ))
                                    )}
                                </tbody>
                            </table>
                        </div>

                        {/* Pagination Footer */}
                        {response?.pagination && response.pagination.pages > 1 && (
                            <div className="px-6 py-3 border-t border-gray-200 bg-gray-50 flex justify-between items-center text-sm">
                                <span className="text-gray-500">
                                    Showing page <span className="font-medium text-gray-900">{page}</span> of <span className="font-medium text-gray-900">{response.pagination.pages}</span>
                                </span>
                                <div className="flex gap-2">
                                    <button
                                        disabled={page === 1}
                                        onClick={() => setPage(p => Math.max(1, p - 1))}
                                        className="px-3 py-1.5 border border-gray-300 rounded-md bg-white text-gray-600 hover:bg-gray-50 hover:text-gray-900 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                                    >
                                        Previous
                                    </button>
                                    <button
                                        disabled={page === response.pagination.pages}
                                        onClick={() => setPage(p => Math.min(response.pagination.pages, p + 1))}
                                        className="px-3 py-1.5 border border-gray-300 rounded-md bg-white text-gray-600 hover:bg-gray-50 hover:text-gray-900 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                                    >
                                        Next
                                    </button>
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </div>
        </Layout>
    );
}
