import { createResource, createSignal, Show, For } from "solid-js";
import { useNavigate } from "@solidjs/router";
import DashboardLayout from "~/components/DashboardLayout";
import { api } from "~/lib/api";

interface LeadRequest {
  id: string;
  requirement: {
    id: string;
    title: string;
    location: string;
    budget: number;
  };
  status: "PENDING" | "ACCEPTED" | "REJECTED" | "EXPIRED";
  tracecoins_reserved: number;
  expires_at: string;
  requested_at: string;
}

export default function MyRequestsPage() {
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = createSignal("ALL");

  const [requests, { refetch }] = createResource(async () => {
    const res = await api.get("/leads/requests/me");
    return res.data?.data || [];
  });

  const filteredRequests = () => {
    const all = requests() || [];
    if (activeTab() === "ALL") return all;
    return all.filter((r: LeadRequest) => r.status === activeTab());
  };

  const cancelRequest = async (id: string) => {
    if (!confirm("Are you sure you want to cancel this request?")) return;

    try {
      await api.delete(`/leads/requests/${id}`);
      refetch();
    } catch (e) {
      alert("Failed to cancel request");
    }
  };

  const formatDate = (date: string) => {
    return new Date(date).toLocaleDateString("en-IN", {
      day: "numeric",
      month: "short",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  const getTimeRemaining = (expiresAt: string) => {
    const now = new Date();
    const expiry = new Date(expiresAt);
    const diff = expiry.getTime() - now.getTime();

    if (diff <= 0) return "Expired";

    const hours = Math.floor(diff / (1000 * 60 * 60));
    if (hours < 1) {
      const mins = Math.floor(diff / (1000 * 60));
      return `${mins}m remaining`;
    }
    return `${hours}h remaining`;
  };

  const getStatusBadge = (status: string) => {
    const classes = {
      PENDING: "bg-yellow-100 text-yellow-800",
      ACCEPTED: "bg-green-100 text-green-800",
      REJECTED: "bg-red-100 text-red-800",
      EXPIRED: "bg-gray-100 text-gray-800",
    };
    return classes[status as keyof typeof classes] || classes.EXPIRED;
  };

  return (
    <DashboardLayout>
      <div class="p-6">
        <h1 class="text-2xl font-bold mb-6">My Lead Requests</h1>

        {/* Filter Tabs */}
        <div class="flex gap-2 mb-6">
          {["ALL", "PENDING", "ACCEPTED", "REJECTED", "EXPIRED"].map((tab) => (
            <button
              onClick={() => setActiveTab(tab)}
              class={`px-4 py-2 rounded-lg font-medium transition-colors ${
                activeTab() === tab
                  ? "bg-orange-500 text-white"
                  : "bg-gray-100 text-gray-700 hover:bg-gray-200"
              }`}
            >
              {tab === "ALL" ? "All Requests" : tab.charAt(0) + tab.slice(1).toLowerCase()}
            </button>
          ))}
        </div>

        {/* Loading State */}
        <Show when={requests.loading}>
          <div class="text-center py-12">
            <div class="animate-spin w-8 h-8 border-2 border-orange-500 border-t-transparent rounded-full mx-auto mb-4" />
            <p class="text-gray-500">Loading requests...</p>
          </div>
        </Show>

        {/* Empty State */}
        <Show when={!requests.loading && filteredRequests().length === 0}>
          <div class="text-center py-12 bg-gray-50 rounded-xl">
            <div class="text-6xl mb-4">📋</div>
            <h3 class="text-lg font-semibold text-gray-700 mb-2">No requests found</h3>
            <p class="text-gray-500 mb-4">
              {activeTab() === "ALL"
                ? "You haven't sent any lead requests yet."
                : `No ${activeTab().toLowerCase()} requests.`}
            </p>
            <button
              onClick={() => navigate("/dashboard/marketplace")}
              class="px-6 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600 transition-colors"
            >
              Browse Marketplace
            </button>
          </div>
        </Show>

        {/* Requests List */}
        <div class="space-y-4">
          <For each={filteredRequests()}>
            {(request: LeadRequest) => (
              <div class="bg-white border rounded-xl p-6 hover:shadow-md transition-shadow">
                <div class="flex justify-between items-start mb-4">
                  <div>
                    <h3 class="text-lg font-semibold text-gray-900">{request.requirement.title}</h3>
                    <p class="text-gray-500 text-sm">{request.requirement.location}</p>
                  </div>
                  <span
                    class={`px-3 py-1 rounded-full text-sm font-medium ${getStatusBadge(request.status)}`}
                  >
                    {request.status}
                  </span>
                </div>

                <div class="grid grid-cols-3 gap-4 mb-4 text-sm">
                  <div>
                    <p class="text-gray-500">Budget</p>
                    <p class="font-semibold">
                      ₹{request.requirement.budget?.toLocaleString() || "Not specified"}
                    </p>
                  </div>
                  <div>
                    <p class="text-gray-500">Reserved</p>
                    <p class="font-semibold text-orange-600">{request.tracecoins_reserved} TC</p>
                  </div>
                  <div>
                    <p class="text-gray-500">
                      {request.status === "PENDING" ? "Expires" : "Requested"}
                    </p>
                    <p class="font-semibold">
                      {request.status === "PENDING"
                        ? getTimeRemaining(request.expires_at)
                        : formatDate(request.requested_at)}
                    </p>
                  </div>
                </div>

                <div class="flex gap-3">
                  <button
                    onClick={() => navigate(`/dashboard/marketplace/${request.requirement.id}`)}
                    class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                  >
                    View Requirement
                  </button>

                  <Show when={request.status === "PENDING"}>
                    <button
                      onClick={() => cancelRequest(request.id)}
                      class="px-4 py-2 border border-red-300 text-red-600 rounded-lg hover:bg-red-50 transition-colors"
                    >
                      Cancel Request
                    </button>
                  </Show>

                  <Show when={request.status === "ACCEPTED"}>
                    <button
                      onClick={() => navigate(`/dashboard/leads/accepted/${request.id}`)}
                      class="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors"
                    >
                      View Contact Details
                    </button>
                  </Show>
                </div>
              </div>
            )}
          </For>
        </div>
      </div>
    </DashboardLayout>
  );
}
