"use client";

import { useState, useEffect } from 'react';
// import { useAuth } from '@/contexts/AuthContext';
import { apiClient } from '@/lib/api';
import ProtectedRoute from '@/components/ProtectedRoute';
import Link from 'next/link';

interface Report {
  id: string;
  name: string;
  title: string;
  createdAt: string;
  updatedAt: string;
}

export default function MyReportsPage() {
  // const { user } = useAuth();
  const [reports, setReports] = useState<Report[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchReports = async () => {
      try {
        const token = localStorage.getItem('auth_token');
        if (!token) {
          setError('Nu sunteți autentificat');
          return;
        }

        const response = await apiClient.getReports(token);
        if (response.data && typeof response.data === 'object' && 'reports' in response.data) {
          setReports((response.data as { reports: Report[] }).reports);
        } else {
          setError(response.error || 'A apărut o eroare la încărcarea rapoartelor');
        }
      } catch (error) {
        console.error('Error fetching reports:', error);
        setError('A apărut o eroare de rețea');
      } finally {
        setLoading(false);
      }
    };

    fetchReports();
  }, []);

  const handleDeleteReport = async (reportId: string) => {
    if (!confirm('Sunteți sigur că doriți să ștergeți acest raport?')) {
      return;
    }

    try {
      const token = localStorage.getItem('auth_token');
      if (!token) return;

      const response = await apiClient.deleteReport(reportId, token);
      if (response.data) {
        setReports(reports.filter(report => report.id !== reportId));
      } else {
        alert(response.error || 'A apărut o eroare la ștergerea raportului');
      }
    } catch (error) {
      console.error('Error deleting report:', error);
      alert('A apărut o eroare de rețea');
    }
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('ro-RO', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  return (
    <ProtectedRoute>
      <div className="mx-auto max-w-6xl p-6">
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-emerald-800 mb-2">
            Rapoartele mele
          </h1>
          <p className="text-gray-600">
            Gestionați și vizualizați toate rapoartele de emisii pe care le-ați generat.
          </p>
        </div>

        <div className="mb-6">
          <Link
            href="/wizard"
            className="inline-flex items-center px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors"
          >
            <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
            </svg>
            Creează raport nou
          </Link>
        </div>

        {loading && (
          <div className="flex justify-center items-center py-12">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-emerald-600"></div>
            <span className="ml-3 text-gray-600">Se încarcă rapoartele...</span>
          </div>
        )}

        {error && (
          <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
            <div className="flex">
              <svg className="w-5 h-5 text-red-400 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              <p className="text-red-700">{error}</p>
            </div>
          </div>
        )}

        {!loading && !error && reports.length === 0 && (
          <div className="text-center py-12">
            <svg className="mx-auto h-12 w-12 text-gray-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
            </svg>
            <h3 className="text-lg font-medium text-gray-900 mb-2">Nu aveți rapoarte</h3>
            <p className="text-gray-500 mb-4">
              Încă nu ați generat niciun raport de emisii. Creați primul raport pentru a începe.
            </p>
            <Link
              href="/wizard"
              className="inline-flex items-center px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors"
            >
              <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
              </svg>
              Creează primul raport
            </Link>
          </div>
        )}

        {!loading && !error && reports.length > 0 && (
          <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
            {reports.map((report) => (
              <div key={report.id} className="bg-white rounded-lg border border-gray-200 shadow-sm hover:shadow-md transition-shadow">
                <div className="p-6">
                  <div className="flex items-start justify-between mb-4">
                    <div className="flex-1">
                      <h3 className="text-lg font-semibold text-gray-900 mb-1">
                        {report.name}
                      </h3>
                      <p className="text-sm text-gray-600 line-clamp-2">
                        {report.title}
                      </p>
                    </div>
                    <button
                      onClick={() => handleDeleteReport(report.id)}
                      className="ml-2 p-1 text-gray-400 hover:text-red-600 transition-colors"
                      title="Șterge raportul"
                    >
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                      </svg>
                    </button>
                  </div>
                  
                  <div className="text-xs text-gray-500 mb-4">
                    <p>Creat: {formatDate(report.createdAt)}</p>
                    {report.updatedAt !== report.createdAt && (
                      <p>Actualizat: {formatDate(report.updatedAt)}</p>
                    )}
                  </div>

                  <div className="flex space-x-2">
                    <Link
                      href={`/reports/${report.id}`}
                      className="flex-1 bg-emerald-600 text-white text-center py-2 px-3 rounded-md text-sm font-medium hover:bg-emerald-700 transition-colors"
                    >
                      Vizualizează
                    </Link>
                    <Link
                      href={`/wizard?edit=${report.id}`}
                      className="flex-1 bg-gray-100 text-gray-700 text-center py-2 px-3 rounded-md text-sm font-medium hover:bg-gray-200 transition-colors"
                    >
                      Editează
                    </Link>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </ProtectedRoute>
  );
}
