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

interface AcceptedLead {
  id: string;
  requirement: {
    id: string;
    title: string;
    profession_key: string;
    location: string;
    budget: number;
    preferred_date: string;
    description: string;
  };
  customer_contact: {
    full_name: string;
    phone: string;
    email: string;
    city: string;
  };
  tracecoins_deducted: number;
  accepted_at: string;
}

export default function AcceptedLeadsPage() {
  const navigate = useNavigate();
  const params = useParams();

  // If ID param exists, show detail view
  const isDetailView = () => !!params.id;

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

  const [selectedLead, setSelectedLead] = createSignal<AcceptedLead | null>(null);

  // Fetch single lead if in detail view
  createResource(async () => {
    if (params.id) {
      try {
        const res = await api.get(`/leads/accepted/${params.id}`);
        setSelectedLead(res.data);
      } catch (e) {
        navigate("/dashboard/leads/accepted");
      }
    }
  });

  const formatDate = (date: string) => {
    return new Date(date).toLocaleDateString("en-IN", {
      day: "numeric",
      month: "long",
      year: "numeric",
    });
  };

  const formatPhone = (phone: string) => {
    return phone.replace(/(\d{5})(\d{5})/, "$1-$2");
  };

  // Detail View
  if (isDetailView() && selectedLead()) {
    const lead = selectedLead()!;
    return (
      <DashboardLayout>
        <div class="p-6 max-w-4xl mx-auto">
          <button
            onClick={() => navigate("/dashboard/leads/accepted")}
            class="mb-4 text-gray-600 hover:text-gray-900 flex items-center gap-2"
          >
            ← Back to Accepted Leads
          </button>

          <div class="bg-white border rounded-xl overflow-hidden">
            {/* Header */}
            <div class="bg-green-50 p-6 border-b">
              <div class="flex justify-between items-start">
                <div>
                  <span class="inline-block px-3 py-1 bg-green-500 text-white text-sm rounded-full mb-2">
                    Lead Accepted
                  </span>
                  <h1 class="text-2xl font-bold text-gray-900">{lead.requirement.title}</h1>
                  <p class="text-gray-600 mt-1">Accepted on {formatDate(lead.accepted_at)}</p>
                </div>
                <div class="text-right">
                  <p class="text-sm text-gray-500">Tracecoins Deducted</p>
                  <p class="text-2xl font-bold text-orange-600">{lead.tracecoins_deducted} TC</p>
                </div>
              </div>
            </div>

            <div class="p-6 grid md:grid-cols-2 gap-8">
              {/* Customer Contact Card */}
              <div>
                <h2 class="text-lg font-semibold mb-4 flex items-center gap-2">
                  👤 Customer Contact
                </h2>
                <div class="bg-gray-50 rounded-xl p-6 space-y-4">
                  <div>
                    <p class="text-sm text-gray-500">Name</p>
                    <p class="text-lg font-semibold">{lead.customer_contact.full_name}</p>
                  </div>
                  <div>
                    <p class="text-sm text-gray-500">Phone</p>
                    <a
                      href={`tel:${lead.customer_contact.phone}`}
                      class="text-lg font-semibold text-orange-600 hover:underline"
                    >
                      {formatPhone(lead.customer_contact.phone)}
                    </a>
                  </div>
                  <div>
                    <p class="text-sm text-gray-500">Email</p>
                    <a
                      href={`mailto:${lead.customer_contact.email}`}
                      class="text-lg font-semibold text-orange-600 hover:underline"
                    >
                      {lead.customer_contact.email}
                    </a>
                  </div>
                  <div>
                    <p class="text-sm text-gray-500">Location</p>
                    <p class="font-medium">{lead.customer_contact.city}</p>
                  </div>
                </div>

                <div class="mt-4 flex gap-3">
                  <a
                    href={`tel:${lead.customer_contact.phone}`}
                    class="flex-1 px-4 py-3 bg-green-500 text-white rounded-lg text-center font-medium hover:bg-green-600 transition-colors"
                  >
                    📞 Call Customer
                  </a>
                  <a
                    href={`https://wa.me/${lead.customer_contact.phone.replace(/\D/g, "")}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    class="flex-1 px-4 py-3 bg-green-600 text-white rounded-lg text-center font-medium hover:bg-green-700 transition-colors"
                  >
                    💬 WhatsApp
                  </a>
                </div>
              </div>

              {/* Requirement Details */}
              <div>
                <h2 class="text-lg font-semibold mb-4 flex items-center gap-2">
                  📋 Requirement Details
                </h2>
                <div class="space-y-4">
                  <div>
                    <p class="text-sm text-gray-500">Service Type</p>
                    <p class="font-medium capitalize">
                      {lead.requirement.profession_key.toLowerCase().replace(/_/g, " ")}
                    </p>
                  </div>
                  <div>
                    <p class="text-sm text-gray-500">Location</p>
                    <p class="font-medium">{lead.requirement.location}</p>
                  </div>
                  <div>
                    <p class="text-sm text-gray-500">Budget</p>
                    <p class="font-medium">
                      ₹{lead.requirement.budget?.toLocaleString() || "Not specified"}
                    </p>
                  </div>
                  {lead.requirement.preferred_date && (
                    <div>
                      <p class="text-sm text-gray-500">Preferred Date</p>
                      <p class="font-medium">{formatDate(lead.requirement.preferred_date)}</p>
                    </div>
                  )}
                  <div>
                    <p class="text-sm text-gray-500">Description</p>
                    <p class="text-gray-700 mt-1">{lead.requirement.description}</p>
                  </div>
                </div>
              </div>
            </div>

            {/* Footer */}
            <div class="bg-gray-50 p-6 border-t">
              <p class="text-sm text-gray-500 text-center">
                Contact the customer to discuss the project details and finalize the engagement.
              </p>
            </div>
          </div>
        </div>
      </DashboardLayout>
    );
  }

  // List View
  return (
    <DashboardLayout>
      <div class="p-6">
        <h1 class="text-2xl font-bold mb-6">Accepted Leads</h1>

        {/* Loading State */}
        <Show when={leads.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 leads...</p>
          </div>
        </Show>

        {/* Empty State */}
        <Show when={!leads.loading && (leads() || []).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 accepted leads yet</h3>
            <p class="text-gray-500 mb-4">
              Browse the marketplace and send requests to view customer contacts.
            </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>

        {/* Leads Grid */}
        <div class="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
          <For each={leads() || []}>
            {(lead: AcceptedLead) => (
              <div
                onClick={() => navigate(`/dashboard/leads/accepted/${lead.id}`)}
                class="bg-white border rounded-xl p-6 hover:shadow-lg transition-all cursor-pointer"
              >
                <div class="flex justify-between items-start mb-3">
                  <span class="inline-block px-2 py-1 bg-green-100 text-green-800 text-xs rounded-full">
                    Accepted
                  </span>
                  <span class="text-orange-600 font-semibold text-sm">
                    -{lead.tracecoins_deducted} TC
                  </span>
                </div>

                <h3 class="font-semibold text-gray-900 mb-2 line-clamp-2">
                  {lead.requirement.title}
                </h3>

                <div class="space-y-2 text-sm">
                  <p class="text-gray-600 flex items-center gap-2">
                    <span>👤</span> {lead.customer_contact.full_name}
                  </p>
                  <p class="text-gray-600 flex items-center gap-2">
                    <span>📍</span> {lead.requirement.location}
                  </p>
                  {lead.requirement.budget && (
                    <p class="text-gray-600 flex items-center gap-2">
                      <span>💰</span> ₹{lead.requirement.budget.toLocaleString()}
                    </p>
                  )}
                </div>

                <div class="mt-4 pt-4 border-t">
                  <p class="text-xs text-gray-500">Accepted {formatDate(lead.accepted_at)}</p>
                </div>
              </div>
            )}
          </For>
        </div>
      </div>
    </DashboardLayout>
  );
}
