import { useQuery } from "@tanstack/react-query"
import { useParams, Link } from "@tanstack/react-router"
import { api } from "../lib/api"
import { Breadcrumb } from "../components/Breadcrumb"
import type { Customer, Project, TimeEntry } from "@emberclone/shared"

export default function CustomerDetail() {
  const { customerId } = useParams({ from: "/customers/$customerId" })

  const { data: customer, isLoading: customerLoading, isError: customerError } = useQuery({
    queryKey: ["customer", customerId],
    queryFn: () => api.getCustomer(customerId!)
  })

  const { data: projects, isLoading: projectsLoading } = useQuery({
    queryKey: ["customerProjects", customerId],
    queryFn: () => api.getCustomerProjects(customerId!),
    enabled: !!customerId
  })

  const { data: entries, isLoading: entriesLoading } = useQuery({
    queryKey: ["customerEntries", customerId],
    queryFn: () => api.getCustomerTimeEntries(customerId!),
    enabled: !!customerId
  })

  if (customerLoading || projectsLoading || entriesLoading) {
    return <div className="p-6 text-gray-500">Loading customer details...</div>
  }

  if (customerError || !customer) {
    return <div className="p-6 text-red-500">Customer not found or error loading data.</div>
  }

  return (
    <div className="p-6 max-w-6xl mx-auto space-y-8">
      <Breadcrumb 
        items={[
          { label: 'Dashboard', to: '/' },
          { label: 'Customers', to: '/customers' },
          { label: customer.name }
        ]} 
      />

      <header className="flex justify-between items-start">
        <div>
          <Link to="/customers" className="text-sm text-blue-600 hover:underline mb-2 block">
            ← Back to Customers
          </Link>
          <h1 className="text-3xl font-bold text-gray-900">{customer.name}</h1>
          <p className="text-gray-500">Customer ID: {customer.id}</p>
        </div>
        <div className="px-3 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800 border border-green-200">
          Active
        </div>
      </header>

      <section className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div className="lg:col-span-1 space-y-6">
          <div className="bg-white p-6 rounded-lg border border-gray-200 shadow-sm">
            <h2 className="text-lg font-semibold mb-4">Projects</h2>
            {projects && projects.length > 0 ? (
              <ul className="space-y-3">
                {projects.map((project: Project) => (
                  <li key={project.id}>
                    <Link 
                      to="/projects/$projectId" 
                      params={{ projectId: project.id }}
                      className="block p-3 rounded-md border border-gray-100 bg-gray-50 hover:bg-blue-50 hover:border-blue-200 transition-colors text-sm font-medium text-gray-700 hover:text-blue-700"
                    >
                      {project.name}
                    </Link>
                  </li>
                ))}
              </ul>
            ) : (
              <p className="text-sm text-gray-500 italic">No projects assigned to this customer.</p>
            )}
          </div>
        </div>

        <div className="lg:col-span-2">
          <div className="bg-white rounded-lg border border-gray-200 shadow-sm overflow-hidden">
            <div className="p-6 border-b border-gray-200">
              <h2 className="text-lg font-semibold">Recent Time Entries</h2>
              <p className="text-sm text-gray-500">Showing the last 20 entries</p>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full text-left border-collapse">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-xs font-semibold text-gray-600 uppercase tracking-wider">Date</th>
                    <th className="px-6 py-3 text-xs font-semibold text-gray-600 uppercase tracking-wider">Project</th>
                    <th className="px-6 py-3 text-xs font-semibold text-gray-600 uppercase tracking-wider text-right">Hours</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200">
                  {entries && entries.length > 0 ? (
                    entries.map((entry: TimeEntry) => (
                      <tr key={entry.id} className="hover:bg-gray-50 transition-colors">
                        <td className="px-6 py-4 text-sm text-gray-600">
                          {new Date(entry.date).toLocaleDateString()}
                        </td>
                        <td className="px-6 py-4 text-sm text-gray-900 font-medium">
                          {entry.projectName || 'Unknown Project'}
                        </td>
                        <td className="px-6 py-4 text-sm text-gray-600 text-right">
                          {entry.hours}h
                        </td>
                      </tr>
                    ))
                  ) : (
                    <tr>
                      <td colSpan={3} className="px-6 py-10 text-center text-sm text-gray-500 italic">
                        No time entries found for this customer.
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </section>
    </div>
  )
}