import React, { useEffect, useState } from "react";
import FamilyTree, { FamilyNode } from "./FamilyTree";
import SaleInfoSection from "./SaleInfoSection";
import LitterOriginSection from "./LitterOriginSection";
import OffspringSection from "./OffspringSection";
import LitterPuppiesModal from "./LitterPuppiesModal";
import AnimalHeroSection from "./AnimalHeroSection";
import AnimalInfo from "./AnimalInfo";
import AnimalAbout from "./AnimalAbout";
import AnimalGallery from "./AnimalGallery";
import AnimalOwner from "./AnimalOwner";
import AnimalAwards from "./AnimalAwards";
import { pedigree } from "@/routes/animals";
import {
  PawPrint,
  Sparkles,
} from "lucide-react";

interface BullyProfileContentProps {
  animal: any;
  species: any[];
  breeds: any[];
}

export default function BullyProfileContent({ animal }: BullyProfileContentProps) {

  console.log(animal);

  // Estado para el árbol genealógico
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [pedigreeData, setPedigreeData] = useState<FamilyNode[] | null>(null);
  
  // Estado para el modal de cachorros
  const [selectedLitterId, setSelectedLitterId] = useState<number | null>(null);
  const [isPuppiesModalOpen, setIsPuppiesModalOpen] = useState(false);

  const handleViewPuppies = (litterId: number) => {
    setSelectedLitterId(litterId);
    setIsPuppiesModalOpen(true);
  };

  const handleClosePuppiesModal = () => {
    setIsPuppiesModalOpen(false);
    setSelectedLitterId(null);
  };

  // Cargar datos del pedigree
  useEffect(() => {
    if (!animal?.id) {
      setLoading(false);
      return;
    }
    setLoading(true);
    setError(null);
    fetch(pedigree(animal.id).url, {
      headers: {
        'Accept': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
      },
      credentials: 'same-origin',
    })
      .then((res) => {
        if (!res.ok) throw new Error('No se encontró el pedigrí');
        return res.json();
      })
      .then((json) => {
        let pedigreeArr = null;
        if (Array.isArray(json?.pedigree)) {
          pedigreeArr = json.pedigree;
        } else if (json?.pedigree?.pedigree && Array.isArray(json.pedigree.pedigree)) {
          pedigreeArr = json.pedigree.pedigree;
        }
        setPedigreeData(pedigreeArr ?? null);
        setLoading(false);
      })
      .catch((err) => {
        setError(err.message);
        setLoading(false);
      });
  }, [animal?.id]);

  const calculateAge = (birthDate: string) => {
    if (!birthDate) return null;
    const birth = new Date(birthDate);
    const today = new Date();
    const years = today.getFullYear() - birth.getFullYear();
    const months = today.getMonth() - birth.getMonth();
    if (years > 0) return `${years} ${years === 1 ? 'año' : 'años'}`;
    return `${months} ${months === 1 ? 'mes' : 'meses'}`;
  };

  const allImages = [animal?.main_photo, ...(animal?.gallery ?? [])].filter(Boolean);

  const isInHeat = animal?.alerts?.some((alert: any) => 
    alert.type === 'celo' || alert.alert_type === 'celo' || 
    (alert.description && alert.description.toLowerCase().includes('celo'))
  );

  return (
    <div className="flex-1 w-full max-w-[1440px] mx-auto pb-20">
      {/* Hero Section con información destacada */}
      <AnimalHeroSection animal={animal} calculateAge={calculateAge} />

      {/* Layout Principal: 2 columnas */}
      <div className="px-4 md:px-10 lg:px-40 mb-10 mt-8">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-8 items-start">
          {/* COLUMNA IZQUIERDA: Contenido Principal (2/3) */}
          <div className="md:col-span-2 space-y-6">
            
            {/* Información del Ejemplar */}
            <AnimalInfo animal={animal} />

            {/* About Section */}
            <AnimalAbout animal={animal} />

            {/* Gallery Section */}
            <AnimalGallery allImages={allImages} />

            {/* Sale Information Section */}
            {animal?.for_sale && animal?.sale_price && (
              <div>
                <SaleInfoSection animal={animal} />
              </div>
            )}

            {/* Pedigree Section */}
            <div>
              <h3 className="text-xl font-bold text-slate-900 dark:text-white mb-4 flex items-center gap-2">
                <span className="w-1.5 h-6 bg-primary rounded-full" />
                Árbol Genealógico
              </h3>
              <div style={{ width: '100%', minHeight: 400, height: 420 }}>
                {loading && <div className="text-center text-muted-foreground py-8">Cargando pedigrí...</div>}
                {!loading && error && (
                  <div className="text-center text-muted-foreground py-8">No se encontró el pedigrí</div>
                )}
                {!loading && !error && pedigreeData && (
                  <FamilyTree
                    data={pedigreeData}
                    className="h-100 rounded-xl"
                    mainId={pedigreeData.find(n => n.main)?.id || pedigreeData[0]?.id}
                  />
                )}
                {!loading && !error && !pedigreeData && (
                  <div className="p-8 rounded-xl bg-surface-light dark:bg-surface-dark border border-slate-200 dark:border-[#392e28] flex flex-col items-center justify-center text-center gap-3">
                    <PawPrint className="w-12 h-12 text-muted-foreground/50" />
                    <p className="text-muted-foreground font-medium">Sin pedigree registrado</p>
                    <p className="text-sm text-muted-foreground/70">No hay información de ancestros disponible</p>
                  </div>
                )}
              </div>
            </div>

            {/* Litter Information Section se movió a la columna derecha */}
          </div>

          {/* COLUMNA DERECHA: Sidebar Sticky (1/3) */}
          <div className="hidden md:block md:col-span-1">
            <div className="space-y-6 sticky top-4">
              {/* Owner Card */}
              <AnimalOwner owner={animal?.owner} />

              {/* Awards Section */}
              <AnimalAwards animal={animal} />

              {/* Quick Stats Card */}
              <div className="p-6 rounded-xl bg-gradient-to-br from-primary/5 to-primary/10 border border-primary/20">
                <h3 className="text-lg font-bold text-slate-900 dark:text-white mb-4 flex items-center gap-2">
                  <Sparkles className="text-primary w-5 h-5" />
                  Estadísticas Rápidas
                </h3>
                <div className="space-y-3">
                  {animal?.weight && (
                    <div className="flex items-center justify-between py-2 border-b border-primary/10">
                      <span className="text-sm text-slate-600 dark:text-slate-400">Peso</span>
                      <span className="text-sm font-bold text-slate-900 dark:text-white">{animal.weight} lbs</span>
                    </div>
                  )}
                  {animal?.height && (
                    <div className="flex items-center justify-between py-2 border-b border-primary/10">
                      <span className="text-sm text-slate-600 dark:text-slate-400">Altura</span>
                      <span className="text-sm font-bold text-slate-900 dark:text-white">{animal.height} in</span>
                    </div>
                  )}
                  {animal?.color && (
                    <div className="flex items-center justify-between py-2 border-b border-primary/10">
                      <span className="text-sm text-slate-600 dark:text-slate-400">Color</span>
                      <span className="text-sm font-bold text-slate-900 dark:text-white capitalize">{animal.color}</span>
                    </div>
                  )}
                  {animal?.sex && (
                    <div className="flex items-center justify-between py-2">
                      <span className="text-sm text-slate-600 dark:text-slate-400">Sexo</span>
                      <span className="text-sm font-bold text-slate-900 dark:text-white">{animal.sex === 'M' ? 'Macho' : 'Hembra'}</span>
                    </div>
                  )}
                </div>
              </div>

              {/* Camadas y Legado */}
              {(animal?.litter || (animal?.father_litters?.length > 0 || animal?.mother_litters?.length > 0)) && (
                <div className="p-6 rounded-xl bg-surface-light dark:bg-surface-dark border border-slate-200 dark:border-[#392e28]">
                  <div className="flex items-center justify-between mb-6">
                    <h3 className="text-lg font-bold text-slate-900 dark:text-white flex items-center gap-2">
                      <span className="w-1.5 h-6 bg-primary rounded-full" />
                      Camadas y Legado
                    </h3>
                  </div>
                  <div className="space-y-6">
                    <LitterOriginSection 
                      animal={animal} 
                      onViewSiblings={handleViewPuppies}
                    />
                    <OffspringSection 
                      animal={animal}
                      onViewPuppies={handleViewPuppies}
                    />
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Modal para ver cachorros */}
      <LitterPuppiesModal 
        litterId={selectedLitterId}
        isOpen={isPuppiesModalOpen}
        onClose={handleClosePuppiesModal}
      />
    </div>
  );
} 