import React, { useState, useCallback, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { FaTimes, FaTrash, FaFileAlt, FaSync, FaEye } from 'react-icons/fa';
import api from '../../../api';
import { ContentPreview } from '../../ContentPreview';
import styles from './ParcelInfoPanel.module.css';

import { useLanguage } from '../../../providers/language/LanguageContext';

export interface SelectionSummary {
  total_area_m2?: number;
  bauzonen?: Array<{ bauzone: string; parcels: any[]; area_m2: number }>;
}

export interface ParcelInfoPanelProps {
  isOpen: boolean;
  onClose: () => void;
  parcels: any[];
  selectionSummary?: SelectionSummary | null;
  onRemoveParcel?: (parcelId: string) => void;
  instanceId?: string;
}

interface ParcelDocument {
  id: string;
  label: string;
  fileId: string;
  fileName: string;
  mimeType: string;
}

interface BzoResult {
  ai_summary?: string;
  relevant_rules?: any[];
  machbarkeitsstudie?: {
    bauzone_rules?: Array<{ parameter: string; value: string; unit: string }>;
    sonderregeln?: { apply: boolean; details: string };
    machbarkeitsstudie?: Record<string, Array<{ item: string; value: string }>>;
    vorschlaege?: string[];
    fakten?: Array<{ item: string; value: string; source?: string }>;
    zusatzinformationen?: Array<{ article_label: string; article_title: string; text: string; source?: string }>;
  };
  errors?: string[];
}

// BZO Information Types
interface BZOGemeinde {
  id: string;
  label: string;
  plz: string;
}

interface BZOZone {
  zone_code: string;
  zone_name: string;
  zone_category: string;
  geschosszahl: number;
  gewerbeerleichterung: boolean;
  source_article: string;
  page: number;
}

interface BZORule {
  rule_type: string;
  value_numeric?: number;
  value_text: string;
  unit?: string;
  condition_text?: string | null;
  is_table_rule: boolean;
  table_zones: string[];
  page: number;
  text_snippet: string;
  zone_raw: string;
  rule_scope: string;
  confidence: number;
}

interface BZOArticle {
  article_label: string;
  article_title: string;
  text: string;
  page_start: number;
  page_end: number;
  section_level_1?: string | null;
  section_level_2?: string | null;
  section_level_3?: string | null;
  zone_raw: string;
}

interface BZOExtractedContent {
  zones: BZOZone[];
  rules: BZORule[];
  articles: BZOArticle[];
  total_zones: number;
  total_rules: number;
  total_articles: number;
}

interface BZODocument {
  id: string;
  label: string;
  dokumentTyp: string;
}

export interface BZOInformationResponse {
  parcel_id: string;
  bauzone: string;
  gemeinde: BZOGemeinde;
  extracted_content: BZOExtractedContent;
  ai_summary: string;
  relevant_rules: BZORule[];
  documents_processed: BZODocument[];
  errors: string[];
  warnings: string[];
}

const ParcelInfoPanel: React.FC<ParcelInfoPanelProps> = ({ isOpen,
  onClose,
  parcels,
  selectionSummary,
  onRemoveParcel,
  instanceId
}) => {
  const { t } = useLanguage();
  const [parcelDocs, setParcelDocs] = useState<Record<string, ParcelDocument[]>>({});
  const [docsLoading, setDocsLoading] = useState<Record<string, boolean>>({});
  const [docsError, setDocsError] = useState<Record<string, string>>({});
  const [extractResults, setExtractResults] = useState<Record<string, BzoResult | null>>({});
  const [extractLoading, setExtractLoading] = useState<Record<string, boolean>>({});
  const [extractError, setExtractError] = useState<Record<string, string>>({});
  const [previewDoc, setPreviewDoc] = useState<{ fileId: string; fileName: string; mimeType: string } | null>(null);

  const fetchParcelDocuments = useCallback(async (parcelId: string, gemeinde: string, bauzone: string) => {
    if (!instanceId || !gemeinde || !bauzone) return;
    setDocsLoading(prev => ({ ...prev, [parcelId]: true }));
    setDocsError(prev => ({ ...prev, [parcelId]: '' }));
    try {
      const res = await api.get(`/api/realestate/${instanceId}/parcel-documents`, {
        params: { gemeinde, bauzone }
      });
      setParcelDocs(prev => ({ ...prev, [parcelId]: res.data?.documents || [] }));
      if (res.data?.error) {
        setDocsError(prev => ({ ...prev, [parcelId]: res.data.error }));
      }
    } catch (e: any) {
      setDocsError(prev => ({
        ...prev,
        [parcelId]: e?.response?.data?.detail || e?.message || t('Fehler beim Laden')
      }));
    } finally {
      setDocsLoading(prev => ({ ...prev, [parcelId]: false }));
    }
  }, [instanceId, t]);

  const runExtraction = useCallback(async (
    parcelId: string,
    gemeinde: string,
    bauzone: string,
    totalAreaM2?: number
  ) => {
    if (!instanceId || !gemeinde || !bauzone) return;
    setExtractLoading(prev => ({ ...prev, [parcelId]: true }));
    setExtractError(prev => ({ ...prev, [parcelId]: '' }));
    setExtractResults(prev => ({ ...prev, [parcelId]: null }));
    try {
      const params: Record<string, string | number> = { gemeinde, bauzone };
      if (totalAreaM2 != null && totalAreaM2 > 0) {
        params.total_area_m2 = totalAreaM2;
      }
      const res = await api.get(`/api/realestate/${instanceId}/bzo-information`, { params });
      setExtractResults(prev => ({ ...prev, [parcelId]: res.data }));
    } catch (e: any) {
      setExtractError(prev => ({
        ...prev,
        [parcelId]: e?.response?.data?.detail || e?.message || t('Fehler bei der Extraktion')
      }));
    } finally {
      setExtractLoading(prev => ({ ...prev, [parcelId]: false }));
    }
  }, [instanceId, t]);

  useEffect(() => {
    if (!isOpen || !instanceId) return;
    parcels.forEach((p) => {
      const g = p?.parcel?.municipality_name;
      const b = p?.parcel?.bauzone;
      const id = p?.parcel?.id;
      if (id && g && b && !parcelDocs[id]?.length && !docsLoading[id]) {
        fetchParcelDocuments(id, g, b);
      }
    });
  }, [isOpen, instanceId, parcels, fetchParcelDocuments]);

  if (!parcels || parcels.length === 0) return null;

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          {/* Backdrop */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.2 }}
            className={styles.backdrop}
            onClick={onClose}
          />
          
          {/* Panel */}
          <motion.div
            initial={{ x: '100%' }}
            animate={{ x: 0 }}
            exit={{ x: '100%' }}
            transition={{ type: 'spring', damping: 30, stiffness: 300 }}
            className={styles.panel}
          >
            <div className={styles.header}>
              <h2 className={styles.title}>{t('Parzellen-Informationen')} ({parcels.length})</h2>
              <button className={styles.closeButton} onClick={onClose}>
                <FaTimes />
              </button>
            </div>

            <div className={styles.content}>
              {selectionSummary?.total_area_m2 != null && (
                <div className={styles.aggregatedSection}>
                  <h3 className={styles.aggregatedTitle}>{t('Gesamtfläche')}</h3>
                  <p className={styles.aggregatedValue}>
                    {selectionSummary.total_area_m2.toFixed(2)} m²
                    {selectionSummary.total_area_m2 >= 10000 && (
                      <span className={styles.subValue}>
                        {' '}({(selectionSummary.total_area_m2 / 10000).toFixed(2)} ha)
                      </span>
                    )}
                  </p>
                </div>
              )}
              {/* Selected Parcels by Bauzone or flat list */}
              <div className={styles.parcelsList}>
                {(selectionSummary?.bauzonen && selectionSummary.bauzonen.length > 0
                  ? selectionSummary.bauzonen.flatMap((bz) => {
                      const parcelsInZone = parcels.filter((p) =>
                        bz.parcels.some((bp: any) => (bp.id || bp.parcel?.id) === p.parcel.id)
                      );
                      return [
                        <section key={`h-${bz.bauzone}`} className={styles.bauzoneSection}>
                          <h4 className={styles.bauzoneTitle}>
                            {t('Bauzone')} {bz.bauzone}
                            {bz.area_m2 != null && (
                              <span className={styles.bauzoneArea}> — {bz.area_m2.toFixed(2)} m²</span>
                            )}
                          </h4>
                        </section>,
                        ...parcelsInZone.map((parcelData, idx) => {
                          const areaForMach = bz?.area_m2 ?? parcelData.parcel.area_m2 ?? selectionSummary?.total_area_m2;
                          return (
                          <section key={parcelData.parcel.id} className={styles.section}>
                    <div className={styles.sectionHeader}>
                      <h3 className={styles.sectionTitle}>
                        {t('Parzelle')} {idx + 1}: {parcelData.parcel.number || parcelData.parcel.id || t('Unbekannt')}
                      </h3>
                      {onRemoveParcel && (
                        <button
                          className={styles.removeButton}
                          onClick={() => onRemoveParcel(parcelData.parcel.id)}
                          title={t('Parzelle entfernen')}
                        >
                          <FaTrash />
                        </button>
                      )}
                    </div>
                    <div className={styles.infoGrid}>
                      {parcelData.parcel.id && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>ID:</span>
                          <span className={styles.value}>{parcelData.parcel.id}</span>
                        </div>
                      )}
                      {parcelData.parcel.egrid && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>EGRID:</span>
                          <span className={styles.value}>{parcelData.parcel.egrid}</span>
                        </div>
                      )}
                      {parcelData.parcel.identnd && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>IdentND:</span>
                          <span className={styles.value}>{parcelData.parcel.identnd}</span>
                        </div>
                      )}
                      {parcelData.parcel.address && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>Adresse:</span>
                          <span className={styles.value}>{parcelData.parcel.address}</span>
                        </div>
                      )}
                      {parcelData.parcel.canton && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>Kanton:</span>
                          <span className={styles.value}>{parcelData.parcel.canton}</span>
                        </div>
                      )}
                      {parcelData.parcel.municipality_name && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>Gemeinde:</span>
                          <span className={styles.value}>{parcelData.parcel.municipality_name}</span>
                        </div>
                      )}
                      {parcelData.parcel.municipality_code && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>Gemeinde-Code:</span>
                          <span className={styles.value}>{parcelData.parcel.municipality_code}</span>
                        </div>
                      )}
                      {parcelData.parcel.area_m2 !== undefined && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>{t('Fläche')}</span>
                          <span className={styles.value}>
                            {parcelData.parcel.area_m2.toFixed(2)} m²
                            {parcelData.parcel.area_m2 >= 10000 && (
                              <span className={styles.subValue}>
                                {' '}({(parcelData.parcel.area_m2 / 10000).toFixed(2)} ha)
                              </span>
                            )}
                          </span>
                        </div>
                      )}
                      {parcelData.parcel.realestate_type && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>{t('Grundstückstyp')}</span>
                          <span className={styles.value}>{parcelData.parcel.realestate_type}</span>
                        </div>
                      )}
                      {parcelData.parcel.bauzone && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>Bauzone:</span>
                          <span className={styles.value}>{parcelData.parcel.bauzone}</span>
                        </div>
                      )}
                      {instanceId && parcelData.parcel.municipality_name && parcelData.parcel.bauzone && (docsLoading[parcelData.parcel.id] || (parcelDocs[parcelData.parcel.id] || []).length > 0) && (
                        <div className={styles.bzoSection}>
                          <h4 className={styles.subSectionTitle}>{t('Bauzonenverordnung')}</h4>
                          {docsLoading[parcelData.parcel.id] && (
                            <p className={styles.bzoHint}>{t('Dokumente werden geladen')}</p>
                          )}
                          {docsError[parcelData.parcel.id] && (
                            <p className={styles.bzoError}>{docsError[parcelData.parcel.id]}</p>
                          )}
                          {(parcelDocs[parcelData.parcel.id] || []).length > 0 && (
                            <div className={styles.docList}>
                              {(parcelDocs[parcelData.parcel.id] || []).map((doc) => (
                                <div key={doc.id} className={styles.docItem}>
                                  <FaFileAlt className={styles.docIcon} />
                                  <span className={styles.docLabel}>{doc.label}</span>
                                  <button
                                    className={styles.docOpenBtn}
                                    onClick={() => setPreviewDoc({
                                      fileId: doc.fileId,
                                      fileName: doc.fileName,
                                      mimeType: doc.mimeType
                                    })}
                                    title={t('Dokument öffnen')}
                                  >
                                    <FaEye /> {t('Öffnen')}
                                  </button>
                                </div>
                              ))}
                            </div>
                          )}
                          {(parcelDocs[parcelData.parcel.id] || []).length > 0 && (
                            <button
                              className={styles.bzoButton}
                              onClick={() => runExtraction(
                                parcelData.parcel.id,
                                parcelData.parcel.municipality_name,
                                parcelData.parcel.bauzone,
                                areaForMach
                              )}
                              disabled={extractLoading[parcelData.parcel.id]}
                              title={t('Inhalt mit Langgraph extrahieren inkl.')}
                            >
                              {extractLoading[parcelData.parcel.id] ? (
                                <FaSync className={styles.spin} />
                              ) : (
                                <FaFileAlt />
                              )}
                              {t('Inhalt extrahieren (LangGraph)')}
                            </button>
                          )}
                          {extractError[parcelData.parcel.id] && (
                            <p className={styles.bzoError}>{extractError[parcelData.parcel.id]}</p>
                          )}
                          {extractResults[parcelData.parcel.id] && (
                            <div className={styles.bzoResult}>
                              {(() => {
                                const m = extractResults[parcelData.parcel.id]?.machbarkeitsstudie;
                                const fakten = m?.fakten ?? [];
                                const vorschlaege = m?.vorschlaege ?? [];
                                const zusatzinfo = m?.zusatzinformationen ?? [];
                                return (
                                  <>
                                    {fakten.length > 0 && (
                                      <div className={styles.bzoFakten}>
                                        <span className={styles.label}>{t('Fakten aus BZO')}</span>
                                        <ul className={styles.rulesList}>
                                          {fakten.map((row: { item: string; value: string; source?: string }, i: number) => (
                                            <li key={i}>
                                              {row.item}: {row.value}
                                              {row.source && (
                                                <span className={styles.sourceHint} title={row.source}>
                                                  {' '}({row.source})
                                                </span>
                                              )}
                                            </li>
                                          ))}
                                        </ul>
                                      </div>
                                    )}
                                    {vorschlaege.length > 0 && (
                                      <div className={styles.bzoSuggestions}>
                                        <span className={styles.label}>{t('Vorschläge')}</span>
                                        <ul className={styles.rulesList}>
                                          {vorschlaege.map((row: { item: string; value: string; is_section?: boolean } | string, i: number) => {
                                            if (typeof row === 'string') return <li key={i}>{row}</li>;
                                            const r = row as { item: string; value: string; is_section?: boolean };
                                            if (r.is_section) {
                                              return <li key={i} className={styles.workflowSection}>{r.item}</li>;
                                            }
                                            return (
                                              <li key={i}>
                                                {r.value ? `${r.item}: ${r.value}` : r.item}
                                              </li>
                                            );
                                          })}
                                        </ul>
                                      </div>
                                    )}
                                    {zusatzinfo.length > 0 && (
                                      <div className={styles.bzoZusatzinfo}>
                                        <span className={styles.label}>{t('Weiterführende Bestimmungen')}</span>
                                        <div className={styles.zusatzinfoList}>
                                          {zusatzinfo.map((art: { article_label: string; article_title: string; text: string; source?: string }, i: number) => (
                                            <details key={i} className={styles.zusatzinfoItem}>
                                              <summary>
                                                {art.article_label} {art.article_title}
                                                {art.source && <span className={styles.sourceHint}> ({art.source})</span>}
                                              </summary>
                                              <p className={styles.zusatzinfoText}>{art.text}</p>
                                            </details>
                                          ))}
                                        </div>
                                      </div>
                                    )}
                                  </>
                                );
                              })()}
                              {(extractResults[parcelData.parcel.id]?.errors?.length ?? 0) > 0 && (
                                <p className={styles.bzoError}>
                                  {(extractResults[parcelData.parcel.id]?.errors || []).join('; ')}
                                </p>
                              )}
                            </div>
                          )}
                        </div>
                      )}
                      {parcelData.parcel.zone && Array.isArray(parcelData.parcel.zone) && parcelData.parcel.zone.length > 0 && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>Zone:</span>
                          <span className={styles.value}>
                            {parcelData.parcel.zone.length !== 1
                              ? t('{n} Zonen gefunden', { n: String(parcelData.parcel.zone.length) })
                              : t('1 Zone gefunden')}
                            {(() => {
                              // Extract zone types from zone array
                              const zoneTypes = parcelData.parcel.zone
                                .map((z: any) => {
                                  const attrs = z.attributes || {};
                                  return attrs.typ || attrs.zone_typ || attrs.bauzone || attrs.zone || attrs.label || null;
                                })
                                .filter((t: string | null) => t !== null);
                              
                              if (zoneTypes.length > 0) {
                                return (
                                  <span className={styles.subValue}>
                                    {' '}({zoneTypes.join(', ')})
                                  </span>
                                );
                              }
                              return null;
                            })()}
                            {import.meta.env.DEV && (
                              <details className={styles.zoneDetails}>
                                <summary className={styles.zoneSummary}>{t('Details anzeigen')}</summary>
                                <pre className={styles.zoneData}>
                                  {JSON.stringify(parcelData.parcel.zone, null, 2)}
                                </pre>
                              </details>
                            )}
                          </span>
                        </div>
                      )}
                      {parcelData.parcel.geoportal_url && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>Geoportal:</span>
                          <a
                            href={parcelData.parcel.geoportal_url}
                            target="_blank"
                            rel="noopener noreferrer"
                            className={styles.link}
                          >
                            {t('Link öffnen')}
                          </a>
                        </div>
                      )}
                    </div>

                  </section>
                        );
                        })
                      ];
                    })
                  : parcels.map((parcelData, index) => {
                    const areaForMachFlat = selectionSummary?.total_area_m2 ?? parcelData.parcel.area_m2;
                    return (
                  <section key={parcelData.parcel.id || index} className={styles.section}>
                    <div className={styles.sectionHeader}>
                      <h3 className={styles.sectionTitle}>
                        {t('Parzelle')} {index + 1}: {parcelData.parcel.number || parcelData.parcel.id || t('Unbekannt')}
                      </h3>
                      {onRemoveParcel && (
                        <button
                          className={styles.removeButton}
                          onClick={() => onRemoveParcel(parcelData.parcel.id)}
                          title={t('Parzelle entfernen')}
                        >
                          <FaTrash />
                        </button>
                      )}
                    </div>
                    <div className={styles.infoGrid}>
                      {parcelData.parcel.id && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>ID:</span>
                          <span className={styles.value}>{parcelData.parcel.id}</span>
                        </div>
                      )}
                      {parcelData.parcel.egrid && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>EGRID:</span>
                          <span className={styles.value}>{parcelData.parcel.egrid}</span>
                        </div>
                      )}
                      {parcelData.parcel.identnd && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>IdentND:</span>
                          <span className={styles.value}>{parcelData.parcel.identnd}</span>
                        </div>
                      )}
                      {parcelData.parcel.address && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>Adresse:</span>
                          <span className={styles.value}>{parcelData.parcel.address}</span>
                        </div>
                      )}
                      {parcelData.parcel.canton && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>Kanton:</span>
                          <span className={styles.value}>{parcelData.parcel.canton}</span>
                        </div>
                      )}
                      {parcelData.parcel.municipality_name && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>Gemeinde:</span>
                          <span className={styles.value}>{parcelData.parcel.municipality_name}</span>
                        </div>
                      )}
                      {parcelData.parcel.municipality_code && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>Gemeinde-Code:</span>
                          <span className={styles.value}>{parcelData.parcel.municipality_code}</span>
                        </div>
                      )}
                      {parcelData.parcel.area_m2 !== undefined && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>{t('Fläche')}</span>
                          <span className={styles.value}>
                            {parcelData.parcel.area_m2.toFixed(2)} m²
                            {parcelData.parcel.area_m2 >= 10000 && (
                              <span className={styles.subValue}>
                                {' '}({(parcelData.parcel.area_m2 / 10000).toFixed(2)} ha)
                              </span>
                            )}
                          </span>
                        </div>
                      )}
                      {parcelData.parcel.realestate_type && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>{t('Grundstückstyp')}</span>
                          <span className={styles.value}>{parcelData.parcel.realestate_type}</span>
                        </div>
                      )}
                      {parcelData.parcel.bauzone && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>Bauzone:</span>
                          <span className={styles.value}>{parcelData.parcel.bauzone}</span>
                        </div>
                      )}
                      {instanceId && parcelData.parcel.municipality_name && parcelData.parcel.bauzone && (docsLoading[parcelData.parcel.id] || (parcelDocs[parcelData.parcel.id] || []).length > 0) && (
                        <div className={styles.bzoSection}>
                          <h4 className={styles.subSectionTitle}>{t('Bauzonenverordnung')}</h4>
                          {docsLoading[parcelData.parcel.id] && (
                            <p className={styles.bzoHint}>{t('Dokumente werden geladen')}</p>
                          )}
                          {docsError[parcelData.parcel.id] && (
                            <p className={styles.bzoError}>{docsError[parcelData.parcel.id]}</p>
                          )}
                          {(parcelDocs[parcelData.parcel.id] || []).length > 0 && (
                            <div className={styles.docList}>
                              {(parcelDocs[parcelData.parcel.id] || []).map((doc) => (
                                <div key={doc.id} className={styles.docItem}>
                                  <FaFileAlt className={styles.docIcon} />
                                  <span className={styles.docLabel}>{doc.label}</span>
                                  <button
                                    className={styles.docOpenBtn}
                                    onClick={() => setPreviewDoc({
                                      fileId: doc.fileId,
                                      fileName: doc.fileName,
                                      mimeType: doc.mimeType
                                    })}
                                    title={t('Dokument öffnen')}
                                  >
                                    <FaEye /> {t('Öffnen')}
                                  </button>
                                </div>
                              ))}
                            </div>
                          )}
                          {(parcelDocs[parcelData.parcel.id] || []).length > 0 && (
                            <button
                              className={styles.bzoButton}
                              onClick={() => runExtraction(
                                parcelData.parcel.id,
                                parcelData.parcel.municipality_name,
                                parcelData.parcel.bauzone,
                                areaForMachFlat
                              )}
                              disabled={extractLoading[parcelData.parcel.id]}
                              title={t('Inhalt mit Langgraph extrahieren inkl.')}
                            >
                              {extractLoading[parcelData.parcel.id] ? (
                                <FaSync className={styles.spin} />
                              ) : (
                                <FaFileAlt />
                              )}
                              {t('Inhalt extrahieren (LangGraph)')}
                            </button>
                          )}
                          {extractError[parcelData.parcel.id] && (
                            <p className={styles.bzoError}>{extractError[parcelData.parcel.id]}</p>
                          )}
                          {extractResults[parcelData.parcel.id] && (
                            <div className={styles.bzoResult}>
                              {(() => {
                                const m = extractResults[parcelData.parcel.id]?.machbarkeitsstudie;
                                const fakten = m?.fakten ?? [];
                                const vorschlaege = m?.vorschlaege ?? [];
                                const zusatzinfo = m?.zusatzinformationen ?? [];
                                return (
                                  <>
                                    {fakten.length > 0 && (
                                      <div className={styles.bzoFakten}>
                                        <span className={styles.label}>{t('Fakten aus BZO')}</span>
                                        <ul className={styles.rulesList}>
                                          {fakten.map((row: { item: string; value: string; source?: string }, i: number) => (
                                            <li key={i}>
                                              {row.item}: {row.value}
                                              {row.source && (
                                                <span className={styles.sourceHint} title={row.source}>
                                                  {' '}({row.source})
                                                </span>
                                              )}
                                            </li>
                                          ))}
                                        </ul>
                                      </div>
                                    )}
                                    {vorschlaege.length > 0 && (
                                      <div className={styles.bzoSuggestions}>
                                        <span className={styles.label}>{t('Vorschläge')}</span>
                                        <ul className={styles.rulesList}>
                                          {vorschlaege.map((row: { item: string; value: string; is_section?: boolean } | string, i: number) => {
                                            if (typeof row === 'string') return <li key={i}>{row}</li>;
                                            const r = row as { item: string; value: string; is_section?: boolean };
                                            if (r.is_section) {
                                              return <li key={i} className={styles.workflowSection}>{r.item}</li>;
                                            }
                                            return (
                                              <li key={i}>
                                                {r.value ? `${r.item}: ${r.value}` : r.item}
                                              </li>
                                            );
                                          })}
                                        </ul>
                                      </div>
                                    )}
                                    {zusatzinfo.length > 0 && (
                                      <div className={styles.bzoZusatzinfo}>
                                        <span className={styles.label}>{t('Weiterführende Bestimmungen')}</span>
                                        <div className={styles.zusatzinfoList}>
                                          {zusatzinfo.map((art: { article_label: string; article_title: string; text: string; source?: string }, i: number) => (
                                            <details key={i} className={styles.zusatzinfoItem}>
                                              <summary>
                                                {art.article_label} {art.article_title}
                                                {art.source && <span className={styles.sourceHint}> ({art.source})</span>}
                                              </summary>
                                              <p className={styles.zusatzinfoText}>{art.text}</p>
                                            </details>
                                          ))}
                                        </div>
                                      </div>
                                    )}
                                  </>
                                );
                              })()}
                              {(extractResults[parcelData.parcel.id]?.errors?.length ?? 0) > 0 && (
                                <p className={styles.bzoError}>
                                  {(extractResults[parcelData.parcel.id]?.errors || []).join('; ')}
                                </p>
                              )}
                            </div>
                          )}
                        </div>
                      )}
                      {parcelData.parcel.zone && Array.isArray(parcelData.parcel.zone) && parcelData.parcel.zone.length > 0 && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>Zone:</span>
                          <span className={styles.value}>
                            {parcelData.parcel.zone.length !== 1
                              ? t('{n} Zonen gefunden', { n: String(parcelData.parcel.zone.length) })
                              : t('1 Zone gefunden')}
                            {(() => {
                              const zoneTypes = parcelData.parcel.zone
                                .map((z: any) => {
                                  const attrs = z.attributes || {};
                                  return attrs.typ || attrs.zone_typ || attrs.bauzone || attrs.zone || attrs.label || null;
                                })
                                .filter((t: string | null) => t !== null);
                              if (zoneTypes.length > 0) {
                                return (
                                  <span className={styles.subValue}>
                                    {' '}({zoneTypes.join(', ')})
                                  </span>
                                );
                              }
                              return null;
                            })()}
                            {import.meta.env.DEV && (
                              <details className={styles.zoneDetails}>
                                <summary className={styles.zoneSummary}>{t('Details anzeigen')}</summary>
                                <pre className={styles.zoneData}>
                                  {JSON.stringify(parcelData.parcel.zone, null, 2)}
                                </pre>
                              </details>
                            )}
                          </span>
                        </div>
                      )}
                      {parcelData.parcel.geoportal_url && (
                        <div className={styles.infoItem}>
                          <span className={styles.label}>Geoportal:</span>
                          <a
                            href={parcelData.parcel.geoportal_url}
                            target="_blank"
                            rel="noopener noreferrer"
                            className={styles.link}
                          >
                            {t('Link öffnen')}
                          </a>
                        </div>
                      )}
                    </div>
                  </section>
                  );
                  })
                )}
              </div>

            </div>
          </motion.div>

          {previewDoc && (
            <ContentPreview
              isOpen={!!previewDoc}
              onClose={() => setPreviewDoc(null)}
              fileId={previewDoc.fileId}
              fileName={previewDoc.fileName}
              mimeType={previewDoc.mimeType}
            />
          )}
        </>
      )}
    </AnimatePresence>
  );
};

// BZO Information Display Component
interface BZOInformationDisplayProps {
  data: BZOInformationResponse;
}

type MdComponentProps = { node?: unknown; [key: string]: unknown };

const bzoMarkdownComponents: Record<string, React.ComponentType<MdComponentProps> | React.ComponentType<MdComponentProps & { inline?: boolean }>> = {
  h1: ({ node, ...props }: MdComponentProps) => <h1 className={styles.bzoMarkdownH1} {...props} />,
  h2: ({ node, ...props }: MdComponentProps) => <h2 className={styles.bzoMarkdownH2} {...props} />,
  h3: ({ node, ...props }: MdComponentProps) => <h3 className={styles.bzoMarkdownH3} {...props} />,
  h4: ({ node, ...props }: MdComponentProps) => <h4 className={styles.bzoMarkdownH4} {...props} />,
  h5: ({ node, ...props }: MdComponentProps) => <h5 className={styles.bzoMarkdownH5} {...props} />,
  h6: ({ node, ...props }: MdComponentProps) => <h6 className={styles.bzoMarkdownH6} {...props} />,
  p: ({ node, ...props }: MdComponentProps) => <p className={styles.bzoMarkdownP} {...props} />,
  ul: ({ node, ...props }: MdComponentProps) => <ul className={styles.bzoMarkdownUl} {...props} />,
  ol: ({ node, ...props }: MdComponentProps) => <ol className={styles.bzoMarkdownOl} {...props} />,
  li: ({ node, ...props }: MdComponentProps) => <li className={styles.bzoMarkdownLi} {...props} />,
  table: ({ node, ...props }: MdComponentProps) => <div className={styles.bzoMarkdownTableWrapper}><table className={styles.bzoMarkdownTable} {...props} /></div>,
  thead: ({ node, ...props }: MdComponentProps) => <thead className={styles.bzoMarkdownThead} {...props} />,
  tbody: ({ node, ...props }: MdComponentProps) => <tbody className={styles.bzoMarkdownTbody} {...props} />,
  tr: ({ node, ...props }: MdComponentProps) => <tr className={styles.bzoMarkdownTr} {...props} />,
  th: ({ node, ...props }: MdComponentProps) => <th className={styles.bzoMarkdownTh} {...props} />,
  td: ({ node, ...props }: MdComponentProps) => <td className={styles.bzoMarkdownTd} {...props} />,
  code: ({ node, inline, ...props }: MdComponentProps & { inline?: boolean }) =>
    inline ? <code className={styles.bzoMarkdownCodeInline} {...props} /> : <code className={styles.bzoMarkdownCodeBlock} {...props} />,
  pre: ({ node, ...props }: MdComponentProps) => <pre className={styles.bzoMarkdownPre} {...props} />,
  blockquote: ({ node, ...props }: MdComponentProps) => <blockquote className={styles.bzoMarkdownBlockquote} {...props} />,
  strong: ({ node, ...props }: MdComponentProps) => <strong className={styles.bzoMarkdownStrong} {...props} />,
  em: ({ node, ...props }: MdComponentProps) => <em className={styles.bzoMarkdownEm} {...props} />,
  a: ({ node, ...props }: MdComponentProps) => <a className={styles.bzoMarkdownLink} {...props} />,
  hr: ({ node, ...props }: MdComponentProps) => <hr className={styles.bzoMarkdownHr} {...props} />,
};

export const BZOInformationDisplay: React.FC<BZOInformationDisplayProps> = ({ data }) => {
  const { t } = useLanguage();
  return (
    <div className={styles.bzoContent}>
      {/* Summary Section */}
      {data.ai_summary && (
        <div className={styles.bzoSubSection}>
          <h5 className={styles.bzoSubTitle}>{t('Zusammenfassung')}</h5>
          <div className={styles.bzoSummary}>
            <ReactMarkdown
              remarkPlugins={[remarkGfm]}
              className={styles.bzoMarkdown}
              components={bzoMarkdownComponents}
            >
              {data.ai_summary}
            </ReactMarkdown>
          </div>
        </div>
      )}

      {/* Gemeinde Info */}
      {data.gemeinde && (
        <div className={styles.bzoSubSection}>
          <h5 className={styles.bzoSubTitle}>Gemeinde</h5>
          <div className={styles.bzoInfoGrid}>
            <div className={styles.bzoInfoItem}>
              <span className={styles.bzoLabel}>Name:</span>
              <span className={styles.bzoValue}>{data.gemeinde.label}</span>
            </div>
            {data.gemeinde.plz && (
              <div className={styles.bzoInfoItem}>
                <span className={styles.bzoLabel}>PLZ:</span>
                <span className={styles.bzoValue}>{data.gemeinde.plz}</span>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Zones */}
      {data.extracted_content?.zones && data.extracted_content.zones.length > 0 && (
        <div className={styles.bzoSubSection}>
          <h5 className={styles.bzoSubTitle}>
            Zonen ({data.extracted_content.zones.length})
          </h5>
          <div className={styles.bzoZonesList}>
            {data.extracted_content.zones.map((zone, idx) => (
              <div key={idx} className={styles.bzoZoneCard}>
                <div className={styles.bzoZoneHeader}>
                  <span className={styles.bzoZoneCode}>{zone.zone_code}</span>
                  <span className={styles.bzoZoneName}>{zone.zone_name}</span>
                </div>
                <div className={styles.bzoZoneDetails}>
                  <div className={styles.bzoZoneDetailItem}>
                    <span className={styles.bzoDetailLabel}>Kategorie:</span>
                    <span className={styles.bzoDetailValue}>{zone.zone_category}</span>
                  </div>
                  {zone.geschosszahl !== undefined && (
                    <div className={styles.bzoZoneDetailItem}>
                      <span className={styles.bzoDetailLabel}>Geschosszahl:</span>
                      <span className={styles.bzoDetailValue}>{zone.geschosszahl}</span>
                    </div>
                  )}
                  <div className={styles.bzoZoneDetailItem}>
                    <span className={styles.bzoDetailLabel}>Gewerbeerleichterung:</span>
                    <span className={styles.bzoDetailValue}>
                      {zone.gewerbeerleichterung ? 'Ja' : 'Nein'}
                    </span>
                  </div>
                  {zone.source_article && (
                    <div className={styles.bzoZoneDetailItem}>
                      <span className={styles.bzoDetailLabel}>Quelle:</span>
                      <span className={styles.bzoDetailValue}>
                        {zone.source_article} (Seite {zone.page})
                      </span>
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Relevant Rules */}
      {data.relevant_rules && data.relevant_rules.length > 0 && (
        <div className={styles.bzoSubSection}>
          <h5 className={styles.bzoSubTitle}>
            Relevante Regeln ({data.relevant_rules.length})
          </h5>
          <div className={styles.bzoRulesList}>
            {data.relevant_rules.map((rule, idx) => (
              <div key={idx} className={styles.bzoRuleCard}>
                <div className={styles.bzoRuleHeader}>
                  <span className={styles.bzoRuleType}>{rule.rule_type}</span>
                  {rule.confidence && (
                    <span className={styles.bzoConfidence}>
                      {Math.round(rule.confidence * 100)}% Vertrauen
                    </span>
                  )}
                </div>
                <div className={styles.bzoRuleValue}>
                  {rule.value_numeric !== undefined && rule.unit ? (
                    <span className={styles.bzoRuleNumeric}>
                      {rule.value_numeric} {rule.unit}
                    </span>
                  ) : (
                    <span className={styles.bzoRuleText}>{rule.value_text}</span>
                  )}
                </div>
                {rule.zone_raw && (
                  <div className={styles.bzoRuleZone}>
                    Zone: {rule.zone_raw}
                  </div>
                )}
                {rule.page && (
                  <div className={styles.bzoRulePage}>
                    Seite {rule.page}
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* All Rules */}
      {data.extracted_content?.rules && data.extracted_content.rules.length > 0 && (
        <div className={styles.bzoSubSection}>
          <h5 className={styles.bzoSubTitle}>
            Alle Regeln ({data.extracted_content.rules.length})
          </h5>
          <div className={styles.bzoRulesList}>
            {data.extracted_content.rules.map((rule, idx) => (
              <div key={idx} className={styles.bzoRuleCard}>
                <div className={styles.bzoRuleHeader}>
                  <span className={styles.bzoRuleType}>{rule.rule_type}</span>
                  {rule.confidence && (
                    <span className={styles.bzoConfidence}>
                      {Math.round(rule.confidence * 100)}%
                    </span>
                  )}
                </div>
                <div className={styles.bzoRuleValue}>
                  {rule.value_numeric !== undefined && rule.unit ? (
                    <span className={styles.bzoRuleNumeric}>
                      {rule.value_numeric} {rule.unit}
                    </span>
                  ) : (
                    <span className={styles.bzoRuleText}>{rule.value_text}</span>
                  )}
                </div>
                {rule.text_snippet && (
                  <div className={styles.bzoRuleSnippet}>
                    "{rule.text_snippet}"
                  </div>
                )}
                <div className={styles.bzoRuleMeta}>
                  {rule.zone_raw && <span>Zone: {rule.zone_raw}</span>}
                  {rule.page && <span>Seite {rule.page}</span>}
                  {rule.rule_scope && <span>Bereich: {rule.rule_scope}</span>}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Articles */}
      {data.extracted_content?.articles && data.extracted_content.articles.length > 0 && (
        <div className={styles.bzoSubSection}>
          <h5 className={styles.bzoSubTitle}>
            Artikel ({data.extracted_content.articles.length})
          </h5>
          <div className={styles.bzoArticlesList}>
            {data.extracted_content.articles.map((article, idx) => (
              <div key={idx} className={styles.bzoArticleCard}>
                <div className={styles.bzoArticleHeader}>
                  <span className={styles.bzoArticleLabel}>{article.article_label}</span>
                  <span className={styles.bzoArticleTitle}>{article.article_title}</span>
                </div>
                <div className={styles.bzoArticleText}>
                  <ReactMarkdown
                    remarkPlugins={[remarkGfm]}
                    className={styles.bzoMarkdown}
                    components={bzoMarkdownComponents}
                  >
                    {article.text}
                  </ReactMarkdown>
                </div>
                <div className={styles.bzoArticleMeta}>
                  {article.zone_raw && <span>Zone: {article.zone_raw}</span>}
                  <span>Seiten {article.page_start}-{article.page_end}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Documents Processed */}
      {data.documents_processed && data.documents_processed.length > 0 && (
        <div className={styles.bzoSubSection}>
          <h5 className={styles.bzoSubTitle}>
            Verarbeitete Dokumente ({data.documents_processed.length})
          </h5>
          <div className={styles.bzoDocumentsList}>
            {data.documents_processed.map((doc, idx) => (
              <div key={idx} className={styles.bzoDocumentItem}>
                <span className={styles.bzoDocumentLabel}>{doc.label}</span>
                <span className={styles.bzoDocumentType}>{doc.dokumentTyp}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Errors and Warnings */}
      {(data.errors?.length > 0 || data.warnings?.length > 0) && (
        <div className={styles.bzoSubSection}>
          {(data.errors?.length > 0) && (
            <div className={styles.bzoErrors}>
              <h5 className={styles.bzoErrorTitle}>Fehler ({data.errors.length})</h5>
              <ul className={styles.bzoErrorList}>
                {data.errors.map((error, idx) => (
                  <li key={idx}>{error}</li>
                ))}
              </ul>
            </div>
          )}
          {(data.warnings?.length > 0) && (
            <div className={styles.bzoWarnings}>
              <h5 className={styles.bzoWarningTitle}>Warnungen ({data.warnings.length})</h5>
              <ul className={styles.bzoWarningList}>
                {data.warnings.map((warning, idx) => (
                  <li key={idx}>{warning}</li>
                ))}
              </ul>
            </div>
          )}
        </div>
      )}

      {/* Statistics */}
      {data.extracted_content && (
        <div className={styles.bzoSubSection}>
          <h5 className={styles.bzoSubTitle}>{t('Statistiken')}</h5>
          <div className={styles.bzoStats}>
            <div className={styles.bzoStatItem}>
              <span className={styles.bzoStatLabel}>Zonen:</span>
              <span className={styles.bzoStatValue}>{data.extracted_content.total_zones}</span>
            </div>
            <div className={styles.bzoStatItem}>
              <span className={styles.bzoStatLabel}>Regeln:</span>
              <span className={styles.bzoStatValue}>{data.extracted_content.total_rules}</span>
            </div>
            <div className={styles.bzoStatItem}>
              <span className={styles.bzoStatLabel}>Artikel:</span>
              <span className={styles.bzoStatValue}>{data.extracted_content.total_articles}</span>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ParcelInfoPanel;

