import React, { useState, useEffect } from 'react';
import { PagerComponent } from '@syncfusion/ej2-react-grids';

interface ProgramInfo {
  appName: string;
  version: string;
  copyright: string;
  supportContact: string;
  description: string;
  techStack: Record<string, string>;
  openSourceComponents: {
    frontend: { name: string; license: string }[];
    backend: { name: string; license: string }[];
  };
  buildInfo: {
    buildDate: string;
    commitId: string;
  };
  changelog: {
    version: string;
    date: string;
    changes: string[];
  }[];
}

const Programminfo: React.FC = () => {
  const [info, setInfo] = useState<ProgramInfo | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const pageSize = 5;

  useEffect(() => {
    let isMounted = true;
    fetch('/program-info.json')
      .then(res => {
        if (!res.ok) throw new Error('Netzwerk-Antwort war nicht ok');
        return res.json();
      })
      .then((data: ProgramInfo) => {
        if (isMounted) setInfo(data);
      })
      .catch(err => {
        console.error('Fehler beim Laden der Programminformationen:', err);
        if (isMounted) setError('Informationen konnten nicht geladen werden.');
      });
    return () => {
      isMounted = false;
    };
  }, []);

  if (error) {
    return (
      <div>
        <h2 style={{ fontSize: '1.25rem', fontWeight: 700, marginBottom: '1rem', color: '#dc2626' }}>Fehler</h2>
        <p>{error}</p>
      </div>
    );
  }

  if (!info) {
    return (
      <div>
        <h2 style={{ fontSize: '1.25rem', fontWeight: 700, marginBottom: '1rem' }}>Programminfo</h2>
        <p>Lade Informationen...</p>
      </div>
    );
  }

  const monoFont = 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace';

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '2rem' }}>
      <div>
        <h2 style={{ fontSize: '1.75rem', fontWeight: 700, marginBottom: '0.5rem' }}>{info.appName}</h2>
        <p style={{ color: '#4b5563' }}>{info.description}</p>
      </div>

      <div style={{ display: 'flex', flexWrap: 'wrap', gap: '2rem' }}>
        {/* Allgemeine Infos & Build */}
        <div style={{ flex: '1 1 360px', minWidth: '320px' }}>
          <div className="e-card">
            <div className="e-card-header">
              <div className="e-card-header-caption">
                <div className="e-card-title">Allgemein</div>
              </div>
            </div>
            <div className="e-card-content">
              <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
                <p>
                  <strong>Version:</strong> {info.version}
                </p>
                <p>
                  <strong>Copyright:</strong> {info.copyright}
                </p>
                <p>
                  <strong>Support:</strong>{' '}
                  <a href={`mailto:${info.supportContact}`} style={{ color: '#2563eb', textDecoration: 'none' }}>
                    {info.supportContact}
                  </a>
                </p>
                <hr style={{ margin: '1rem 0' }} />
                <h4 style={{ fontWeight: 600 }}>Build-Informationen</h4>
                <p>
                  <strong>Build-Datum:</strong> {new Date(info.buildInfo.buildDate).toLocaleString('de-DE')}
                </p>
                <p>
                  <strong>Commit-ID:</strong>{' '}
                  <span style={{ fontFamily: monoFont, fontSize: '0.875rem', background: '#f3f4f6', padding: '0.125rem 0.25rem', borderRadius: '0.25rem' }}>
                    {info.buildInfo.commitId}
                  </span>
                </p>
              </div>
            </div>
          </div>
        </div>

        {/* Technischer Stack */}
        <div style={{ flex: '1 1 360px', minWidth: '320px' }}>
          <div className="e-card">
            <div className="e-card-header">
              <div className="e-card-header-caption">
                <div className="e-card-title">Technologie-Stack</div>
              </div>
            </div>
            <div className="e-card-content">
              <ul style={{ paddingLeft: '1rem', margin: 0, display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
                {Object.entries(info.techStack).map(([key, value]) => (
                  <li key={key}>
                    <span style={{ fontWeight: 600, textTransform: 'capitalize' }}>{key}:</span> {value}
                  </li>
                ))}
              </ul>
            </div>
          </div>
        </div>
      </div>

      {/* Changelog */}
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '0.5rem' }}>
          <h3 style={{ fontSize: '1.25rem', fontWeight: 600, margin: 0 }}>Änderungsprotokoll (Changelog)</h3>
          <div style={{ marginLeft: 'auto' }}>
            <span style={{ color: '#6b7280', fontSize: '0.875rem' }}>
              Insgesamt {info.changelog.length} Einträge
            </span>
          </div>
        </div>
        <div style={{ marginBottom: '0.75rem' }}>
          <PagerComponent
            totalRecordsCount={info.changelog.length}
            pageSize={pageSize}
            pageCount={5}
            currentPage={currentPage}
            click={(args: { currentPage: number }) => setCurrentPage(args.currentPage)}
          />
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: '1.5rem' }}>
          {info.changelog
            .slice((currentPage - 1) * pageSize, (currentPage - 1) * pageSize + pageSize)
            .map(log => (
              <div key={log.version} className="e-card">
                <div className="e-card-header">
                  <div className="e-card-header-caption">
                    <div className="e-card-title">
                      Version {log.version}{' '}
                      <span style={{ fontSize: '0.875rem', fontWeight: 400, color: '#6b7280' }}>
                        - {new Date(log.date).toLocaleDateString('de-DE')}
                      </span>
                    </div>
                  </div>
                </div>
                <div className="e-card-content">
                  <ul style={{ color: '#374151', paddingLeft: '1rem', margin: 0, display: 'flex', flexDirection: 'column', gap: '0.25rem' }}>
                    {log.changes.map((change, index) => (
                      <li key={index}>{change}</li>
                    ))}
                  </ul>
                </div>
              </div>
            ))}
        </div>
        <div style={{ marginTop: '0.75rem' }}>
          <PagerComponent
            totalRecordsCount={info.changelog.length}
            pageSize={pageSize}
            pageCount={5}
            currentPage={currentPage}
            click={(args: { currentPage: number }) => setCurrentPage(args.currentPage)}
          />
        </div>
      </div>

      {/* Open Source Komponenten */}
      <div>
        <h3 style={{ fontSize: '1.25rem', fontWeight: 600, marginBottom: '1rem' }}>Verwendete Open-Source-Komponenten</h3>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '2rem' }}>
          {info.openSourceComponents.frontend && (
            <div style={{ flex: '1 1 360px', minWidth: '320px' }}>
              <div className="e-card">
                <div className="e-card-header">
                  <div className="e-card-header-caption">
                    <div className="e-card-title">Frontend</div>
                  </div>
                </div>
                <div className="e-card-content">
                  <ul style={{ paddingLeft: '1rem', margin: 0, display: 'flex', flexDirection: 'column', gap: '0.25rem' }}>
                    {info.openSourceComponents.frontend.map(item => (
                      <li key={item.name}>
                        {item.name} ({item.license}-Lizenz)
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            </div>
          )}
          {info.openSourceComponents.backend && (
            <div style={{ flex: '1 1 360px', minWidth: '320px' }}>
              <div className="e-card">
                <div className="e-card-header">
                  <div className="e-card-header-caption">
                    <div className="e-card-title">Backend</div>
                  </div>
                </div>
                <div className="e-card-content">
                  <ul style={{ paddingLeft: '1rem', margin: 0, display: 'flex', flexDirection: 'column', gap: '0.25rem' }}>
                    {info.openSourceComponents.backend.map(item => (
                      <li key={item.name}>
                        {item.name} ({item.license}-Lizenz)
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default Programminfo;
