'use client'
import React, { useEffect, useState } from 'react'
import Loader from '@/components/ui/Loader'
import { LeadPageProps } from '@/app/types'

const ResponsesPage = () => {
  const [leads, setLeads] = useState<LeadPageProps[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const fetchLeads = async () => {
      try {
        const response = await fetch('/api/account/requests')
        if (!response.ok) {
          throw new Error('Failed to fetch leads')
        }
        const data = await response.json()

        setLeads(data)
      } catch (err) {
        console.error('Component error:', err)
        setError(err instanceof Error ? err.message : 'Failed to load leads')
      } finally {
        setIsLoading(false)
      }
    }

    fetchLeads()
  }, [])

  if (isLoading) {
    return <Loader />
  }

  if (error) {
    return <div className="p-8 text-center text-red-500">{error}</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">
            <div className="flex items-center justify-between">
              <h1 className="text-2xl">Мои отклики</h1>
            </div>
          </div>

          {leads.length > 0 && (
            <div className="mt-4 space-y-4">
              {leads.map(lead => (
                <div
                  key={lead.id}
                  className="space-y-4 rounded-2xl border bg-white p-6 transition-shadow hover:shadow-md"
                >
                  <div className="flex flex-col space-y-4">
                    <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between">
                      <div>
                        <div className="text-sm text-gray-500">Маршрут</div>
                        <div className="font-medium">#{lead.route.id}</div>
                        <div className="mt-1 text-sm text-gray-600">
                          {lead.route.from_city_name}, {lead.route.from_country_name} →{' '}
                          {lead.route.to_city_name}, {lead.route.to_country_name}
                        </div>
                        <div className="mt-1 text-xs text-gray-500">
                          {lead.route.formatted_departure} - {lead.route.formatted_arrival}
                        </div>
                        <div className="mt-1 text-xs text-gray-500">
                          <span className="font-medium">Тип груза:</span>{' '}
                          {lead.route.formatted_cargo_type} •{' '}
                          <span className="font-medium">Транспорт:</span>{' '}
                          {lead.route.formatted_transport}
                        </div>
                        {lead.route.comment && (
                          <div className="mt-1 text-xs text-gray-500">
                            <span className="font-medium">Комментарий к маршруту:</span>{' '}
                            {lead.route.comment}
                          </div>
                        )}
                        <div className="mt-2 flex items-center text-xs text-gray-500">
                          <svg
                            className="mr-1 h-4 w-4 text-gray-400"
                            fill="none"
                            viewBox="0 0 24 24"
                            stroke="currentColor"
                          >
                            <path
                              strokeLinecap="round"
                              strokeLinejoin="round"
                              strokeWidth={2}
                              d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
                            />
                          </svg>
                          {lead.owner_name}
                          <span className="mx-1">•</span>
                          <a
                            href={`mailto:${lead.owner_email}`}
                            className="text-blue-600 hover:text-blue-800"
                          >
                            {lead.owner_email}
                          </a>
                        </div>
                      </div>
                      <div className="mt-4 sm:mt-0 sm:text-right">
                        <div className="text-sm text-gray-500">Предложенная цена</div>
                        <div className="text-lg font-medium">{lead.moving_price} тенге</div>
                      </div>
                    </div>

                    {lead.comment && (
                      <div className="rounded-lg bg-gray-50 p-3">
                        <div className="text-sm text-gray-500">Комментарий к отклику:</div>
                        <div className="mt-1">{lead.comment}</div>
                      </div>
                    )}

                    <div className="text-sm text-gray-500">
                      Отправлено:{' '}
                      {new Date(lead.created_at).toLocaleString('ru-RU', {
                        year: 'numeric',
                        month: 'long',
                        day: 'numeric',
                        hour: '2-digit',
                        minute: '2-digit',
                      })}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

export default ResponsesPage
