import React from 'react'
import { cookies } from 'next/headers'
import { headers } from 'next/headers'
import { Route } from '@/app/types'

async function getRoutes() {
  const cookieStore = await cookies()
  const headersList = await headers()
  const protocol = headersList.get('x-forwarded-proto') || 'http'
  const host = headersList.get('host') || 'localhost:3000'

  const response = await fetch(`${protocol}://${host}/api/account/routes`, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      Cookie: cookieStore.toString(),
    },
  })

  if (!response.ok) {
    const error = await response.json()
    console.error('Error fetching routes:', error)
    throw new Error(error.message || 'Failed to fetch routes')
  }

  return response.json()
}

export default async function UserRoutes() {
  let routes: Route[] = []
  try {
    routes = (await getRoutes()) || []
  } catch (error) {
    console.error('Component error:', error)
    return (
      <div className="flex items-center justify-center py-12">
        <div className="text-red-500">
          {error instanceof Error ? error.message : 'Не удалось загрузить маршруты'}
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-3">
      <div className="overflow-hidden rounded-2xl shadow">
        <div className="bg-white p-6 sm:p-8">
          <div className="space-y-4">
            <h1 className="text-2xl">Мои маршруты</h1>
          </div>
          {(!routes || routes.length === 0) && (
            <div className="flex flex-col items-center justify-center py-12 text-gray-500">
              <p className="text-lg">У вас пока нет созданных маршрутов</p>
              <p className="text-sm">Создавайте заявки на перевозку, чтобы они отобразились тут</p>
            </div>
          )}
          {routes.length > 0 && (
            <div className="mt-4 space-y-4">
              {routes.map(route => (
                <div
                  key={route.id}
                  className="space-y-4 rounded-2xl border bg-white p-6 transition-shadow hover:shadow-md"
                >
                  <div className="flex items-center justify-between">
                    <div className="text-sm text-gray-500">ID маршрута: #{route.id}</div>
                    <div
                      className={`rounded-full px-3 py-1 text-sm ${
                        route.owner_type === 'customer'
                          ? 'bg-blue-100 text-blue-800'
                          : 'bg-green-100 text-green-800'
                      }`}
                    >
                      {route.owner_type === 'customer' ? 'Заказчик' : 'Перевозчик'}
                    </div>
                  </div>

                  <div className="flex flex-col space-y-1">
                    <div className="flex items-center space-x-3">
                      <div className="h-4 w-4 flex-shrink-0 rounded-full bg-blue-500" />
                      <div>
                        <div className="font-medium">
                          {route.from_city_name} / {route.from_country_name}
                        </div>
                        <div className="text-sm text-gray-600">{route.formatted_departure}</div>
                      </div>
                    </div>
                    <div className="ml-[7px] h-6 w-[2px] bg-gray-300" />
                    <div className="flex items-center space-x-3">
                      <div className="h-4 w-4 flex-shrink-0 rounded-full bg-green-500" />
                      <div>
                        <div className="font-medium">
                          {route.to_city_name} / {route.to_country_name}
                        </div>
                        <div className="text-sm text-gray-600">{route.formatted_arrival}</div>
                      </div>
                    </div>
                  </div>

                  <div className="flex flex-wrap gap-4 pt-2">
                    <div className="flex items-center space-x-2">
                      <div className="text-gray-500">Тип груза:</div>
                      <div className="font-medium">{route.formatted_cargo_type}</div>
                    </div>
                    <div className="flex items-center space-x-2">
                      <div className="text-gray-500">Способ перевозки:</div>
                      <div className="font-medium">{route.formatted_transport}</div>
                    </div>
                  </div>

                  {route.comment && (
                    <div className="border-t border-gray-300 pt-2">
                      <div className="text-sm text-gray-500">
                        <span className="text-gray-500">Комментарий:</span> {route.comment}
                      </div>
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
