"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { LuX, LuFileText, LuExternalLink, LuCalendar } from "react-icons/lu";

interface Document {
  id: string;
  fileName: string;
  fileUrl: string;
  createdAt: string;
  extractedData: any;
}

interface Employee {
  id: string;
  name: string | null;
  username: string;
}

interface EmployeeDocumentsModalProps {
  employeeId: string;
  employeeName: string;
  onClose: () => void;
}

export default function EmployeeDocumentsModal({
  employeeId,
  employeeName,
  onClose,
}: EmployeeDocumentsModalProps) {
  const [documents, setDocuments] = useState<Document[]>([]);
  const [employee, setEmployee] = useState<Employee | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    fetchDocuments();
  }, [employeeId]);

  const fetchDocuments = async () => {
    try {
      setLoading(true);
      const response = await fetch(`/api/employees/${employeeId}/documents`);
      const data = await response.json();

      if (data.success) {
        setDocuments(data.documents);
        setEmployee(data.employee);
      } else {
        setError(data.error || "Error al cargar documentos");
      }
    } catch (error) {
      setError("Error de conexión al cargar documentos");
    } finally {
      setLoading(false);
    }
  };

  const formatValue = (value: unknown): string => {
    if (value === null || value === undefined) return "—";
    if (
      typeof value === "string" ||
      typeof value === "number" ||
      typeof value === "boolean"
    ) {
      return String(value);
    }
    if (Array.isArray(value)) {
      return value
        .map((item) =>
          typeof item === "object" && item !== null
            ? `{ ${Object.entries(item)
                .map(([k, v]) => `${k}: ${v}`)
                .join(", ")} }`
            : String(item)
        )
        .join("; ");
    }
    if (typeof value === "object") {
      return `{ ${Object.entries(value as Record<string, unknown>)
        .map(([k, v]) => `${k}: ${v}`)
        .join(", ")} }`;
    }
    return String(value);
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-background border border-border rounded-lg max-w-4xl w-full max-h-[80vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-border">
          <div>
            <h2 className="text-xl font-bold text-text">
              Documentos de {employeeName}
            </h2>
            <p className="text-sm text-text-muted mt-1">
              {employee && `@${employee.username}`}
            </p>
          </div>
          <button
            onClick={onClose}
            className="text-text-muted hover:text-text"
          >
            <LuX className="h-6 w-6" />
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6">
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
            </div>
          ) : error ? (
            <div className="bg-destructive/10 border border-destructive/20 text-destructive px-4 py-3 rounded">
              {error}
            </div>
          ) : documents.length === 0 ? (
            <div className="text-center py-12">
              <LuFileText className="h-16 w-16 text-text-subtle mx-auto mb-4" />
              <p className="text-text-muted">
                Este empleado no tiene documentos registrados
              </p>
            </div>
          ) : (
            <div className="space-y-3">
              {documents.map((doc) => (
                <div
                  key={doc.id}
                  className="bg-background border border-border rounded-lg p-4 hover:shadow-md transition-shadow"
                >
                  <div className="flex items-start justify-between">
                    <div className="flex items-start gap-3 flex-1 min-w-0">
                      <div className="bg-primary/10 p-2 rounded-lg flex-shrink-0">
                        <LuFileText className="h-5 w-5 text-primary" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <h3 className="font-medium text-text truncate">
                          {doc.fileName}
                        </h3>
                        <div className="flex items-center gap-2 mt-1 text-sm text-text-muted">
                          <LuCalendar className="h-4 w-4 flex-shrink-0" />
                          <span className="truncate">
                            {new Date(doc.createdAt).toLocaleDateString(
                              "es-ES",
                              {
                                year: "numeric",
                                month: "long",
                                day: "numeric",
                                hour: "2-digit",
                                minute: "2-digit",
                              }
                            )}
                          </span>
                        </div>
                        {doc.extractedData && (
                          <div className="mt-2 text-xs text-text-muted">
                            <span className="font-medium text-text">
                              Datos extraídos:
                            </span>
                            <div className="mt-1 max-h-24 overflow-y-auto overflow-x-hidden">
                              {Object.entries(doc.extractedData).map(
                                ([key, value]) => (
                                  <div key={key} className="mt-1">
                                    <span className="font-medium text-text">{key}:</span>
                                    <span className="ml-1 break-words whitespace-pre-wrap max-w-full text-text-muted">
                                      {formatValue(value)}
                                    </span>
                                  </div>
                                )
                              )}
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                    <Link
                      href={`/documents/${doc.id}`}
                      className="ml-4 flex items-center gap-2 px-3 py-2 text-sm text-primary hover:bg-primary/10 rounded-lg transition-colors flex-shrink-0"
                      title="Ver documento"
                    >
                      <LuExternalLink className="h-4 w-4" />
                      Ver
                    </Link>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="border-t border-border p-4 bg-background-alt">
          <div className="flex items-center justify-between text-sm text-text-muted">
            <span>
              Total: <strong className="text-text">{documents.length}</strong> documento(s)
            </span>
            <button
              onClick={onClose}
              className="px-4 py-2 bg-background border border-border text-text rounded-lg hover:bg-background-alt focus:outline-none focus:ring-2 focus:ring-border"
            >
              Cerrar
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
