'use client'

import React, { useEffect, useState } from 'react'
import { useSession } from 'next-auth/react'
import Link from 'next/link'
import Cookies from 'js-cookie'

interface Address {
  id: string
  street: string
  city: string
  postcode: string
}

interface Route {
  id: string
  name: string | null
  status: string
}

interface HistoryRecord {
  id: string
  action: string
  createdAt: string
  route: Route
  address: Address
}

export default function HistoryPage() {
  const { data: session, status } = useSession()
  const [history, setHistory] = useState<HistoryRecord[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [messages, setMessages] = useState<any>(null)

  useEffect(() => {
    const loadMessages = async () => {
      const lang = Cookies.get('NEXT_LOCALE') || 'de'
      const messages = await import(`@/messages/${lang}.json`)
      setMessages(messages.default)
    }
    loadMessages()
  }, [])

  useEffect(() => {
    fetchHistory()
  }, [session])

  const fetchHistory = async () => {
    try {
      const response = await fetch('/api/history', {
        credentials: 'include'
      })

      if (!response.ok) {
        throw new Error(messages?.history?.error)
      }

      const data = await response.json()
      setHistory(data)
    } catch (err) {
      console.error('Geçmiş kayıtları getirme hatası:', err)
      setError(err instanceof Error ? err.message : messages?.history?.error)
    } finally {
      setLoading(false)
    }
  }

  if (!messages || status === 'loading' || loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-32 w-32 border-t-2 border-b-2 border-indigo-500"></div>
      </div>
    )
  }

  if (status === 'unauthenticated') {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <h2 className="text-2xl font-bold mb-4">{messages.common.accessDenied}</h2>
          <p className="mb-4">{messages.common.loginRequired}</p>
          <Link
            href="/auth/login"
            className="text-indigo-600 hover:text-indigo-800"
          >
            {messages.common.login}
          </Link>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-100 py-6">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex justify-between items-center">
          <div className="flex items-center space-x-4">
            <Link
              href="/dashboard"
              className="bg-gray-500 text-white px-4 py-2 rounded-md hover:bg-gray-600"
            >
              {messages.common.back}
            </Link>
            <h1 className="text-3xl font-bold text-gray-900">{messages.history.title}</h1>
          </div>
        </div>

        <div className="mt-8">
          {error && (
            <div className="bg-red-50 border-l-4 border-red-400 p-4 mb-4">
              <div className="flex">
                <div className="flex-shrink-0">
                  <svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
                    <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                  </svg>
                </div>
                <div className="ml-3">
                  <p className="text-sm text-red-700">{error}</p>
                </div>
              </div>
            </div>
          )}

          {history.length === 0 ? (
            <div className="text-center py-12">
              <p className="text-gray-500">{messages.history.noRecords}</p>
            </div>
          ) : (
            <div className="bg-white shadow overflow-hidden sm:rounded-lg">
              <ul className="divide-y divide-gray-200">
                {history.map((record) => (
                  <li key={record.id} className="p-4">
                    <div className="flex justify-between items-start">
                      <div>
                        <p className="text-sm font-medium text-indigo-600">
                          {record.address.street}, {record.address.city} {record.address.postcode}
                        </p>
                        <p className="mt-1 text-sm text-gray-500">
                          {messages.history.routeStatus}: {messages.history.status[record.route.status.toLowerCase()] || record.route.status}
                        </p>
                      </div>
                      <div className="text-right">
                        <p className="text-sm text-gray-500">
                          {new Date(record.createdAt).toLocaleString()}
                        </p>
                        <p className="mt-1 text-xs text-gray-400">
                          {record.action === 'ADDRESS_VIEWED' ? messages.history.addressViewed : record.action}
                        </p>
                      </div>
                    </div>
                  </li>
                ))}
              </ul>
            </div>
          )}
        </div>
      </div>
    </div>
  )
} 