import React, { useEffect, useMemo, useState } from "react";
import {
  CalendarDays,
  CheckCircle2,
  ChevronLeft,
  ChevronRight,
  Clock3,
  History,
  Loader2,
  RefreshCw,
  Search,
  Sparkles,
  Users,
} from "lucide-react";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Progress } from "@/components/ui/progress";
import { loadTeamHoursRecords, loadTeamHoursRoster, type TeamHoursRecord, type TeamHoursRosterMember } from "@/lib/teamHours";

const RECORDS_PER_PAGE = 8;

type PeriodPreset = "today" | "7d" | "30d" | "month" | "all" | "custom";
type PeopleFilter = "all" | "current" | "historical";
type SortMode = "hours" | "name" | "recent";

type CanonicalPerson = {
  key: string;
  name: string;
  email: string;
  current: boolean;
  records: TeamHoursRecord[];
  totalMinutes: number;
  daysWithEntries: number;
  averageMinutesPerLoggedDay: number;
  lastDate: string;
};

type DailySummary = {
  date: string;
  minutes: number;
  records: number;
  projects: number;
};

function clean(value: unknown): string {
  return String(value ?? "").trim().replace(/\s+/g, " ");
}

function normalizeName(value: string): string {
  return clean(value)
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, " ")
    .replace(/\s+/g, " ")
    .trim();
}

function tokens(value: string): string[] {
  return normalizeName(value).split(" ").filter((token) => token.length >= 3);
}

function findRosterMatch(name: string, email: string, roster: TeamHoursRosterMember[]) {
  const normalizedEmail = clean(email).toLowerCase();
  if (normalizedEmail) {
    const byEmail = roster.find((member) => member.email === normalizedEmail);
    if (byEmail) return byEmail;
  }

  const sourceName = normalizeName(name);
  if (!sourceName) return null;

  const exact = roster.find((member) => normalizeName(member.fullName) === sourceName);
  if (exact) return exact;

  const sourceTokens = new Set(tokens(name));
  if (sourceTokens.size < 2) return null;

  const candidates = roster
    .map((member) => {
      const memberTokens = new Set(tokens(member.fullName));
      const shared = [...sourceTokens].filter((token) => memberTokens.has(token));
      const subset =
        shared.length === sourceTokens.size ||
        shared.length === memberTokens.size;
      return { member, shared: shared.length, subset };
    })
    .filter((candidate) => candidate.shared >= 2)
    .sort((a, b) => Number(b.subset) - Number(a.subset) || b.shared - a.shared);

  if (candidates.length !== 1 && candidates[0]?.shared === candidates[1]?.shared && candidates[0]?.subset === candidates[1]?.subset) {
    return null;
  }

  return candidates[0]?.member || null;
}

function formatMinutes(totalMinutes: number, compact = false): string {
  const safeMinutes = Math.max(0, Math.round(totalMinutes || 0));
  const hours = Math.floor(safeMinutes / 60);
  const minutes = safeMinutes % 60;

  if (compact) {
    if (!minutes) return `${hours} h`;
    if (!hours) return `${minutes} min`;
    return `${hours} h ${minutes} min`;
  }

  if (!minutes) return `${hours} h`;
  return `${hours} h ${minutes.toString().padStart(2, "0")} min`;
}

function formatAverage(minutes: number): string {
  if (!minutes) return "0 h";
  return formatMinutes(minutes, true);
}

function localIsoDate(date: Date): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

function addDays(date: Date, amount: number) {
  const next = new Date(date);
  next.setDate(next.getDate() + amount);
  return next;
}

function presetRange(preset: PeriodPreset): { from?: string; to?: string } {
  const today = new Date();
  const to = localIsoDate(today);

  if (preset === "today") return { from: to, to };
  if (preset === "7d") return { from: localIsoDate(addDays(today, -6)), to };
  if (preset === "30d") return { from: localIsoDate(addDays(today, -29)), to };
  if (preset === "month") return { from: localIsoDate(new Date(today.getFullYear(), today.getMonth(), 1)), to };
  return {};
}

function formatDateLabel(iso: string): string {
  if (!iso) return "—";
  const [year, month, day] = iso.split("-").map(Number);
  if (!year || !month || !day) return iso;
  return new Intl.DateTimeFormat("es", { day: "numeric", month: "short", year: "numeric" }).format(
    new Date(year, month - 1, day),
  );
}

function initials(name: string): string {
  const parts = clean(name).split(" ").filter(Boolean);
  if (parts.length >= 2) return `${parts[0][0]}${parts[1][0]}`.toUpperCase();
  return (parts[0] || "?").slice(0, 2).toUpperCase();
}

function buildPeople(records: TeamHoursRecord[], roster: TeamHoursRosterMember[]): CanonicalPerson[] {
  const map = new Map<string, CanonicalPerson>();

  for (const member of roster) {
    map.set(`email:${member.email}`, {
      key: `email:${member.email}`,
      name: member.fullName,
      email: member.email,
      current: true,
      records: [],
      totalMinutes: 0,
      daysWithEntries: 0,
      averageMinutesPerLoggedDay: 0,
      lastDate: "",
    });
  }

  for (const record of records) {
    const rosterMatch = findRosterMatch(record.workedByName, record.workedByEmail, roster);
    const name = rosterMatch?.fullName || record.workedByName || "Sin nombre";
    const email = rosterMatch?.email || record.workedByEmail;
    const normalized = normalizeName(name) || "sin-nombre";
    const key = rosterMatch ? `email:${rosterMatch.email}` : `name:${normalized}`;
    const person = map.get(key) || {
      key,
      name,
      email,
      current: Boolean(rosterMatch),
      records: [],
      totalMinutes: 0,
      daysWithEntries: 0,
      averageMinutesPerLoggedDay: 0,
      lastDate: "",
    };

    person.records.push(record);
    person.totalMinutes += record.durationMinutes;
    if (!person.lastDate || record.workDate > person.lastDate) person.lastDate = record.workDate;
    map.set(key, person);
  }

  for (const person of map.values()) {
    const days = new Set(person.records.map((record) => record.workDate));
    person.daysWithEntries = days.size;
    person.averageMinutesPerLoggedDay = days.size ? Math.round(person.totalMinutes / days.size) : 0;
    person.records.sort((a, b) => b.workDate.localeCompare(a.workDate) || b.sourceKey.localeCompare(a.sourceKey));
  }

  return Array.from(map.values());
}

function buildDailySummaries(records: TeamHoursRecord[]): DailySummary[] {
  const map = new Map<string, { minutes: number; records: number; projects: Set<string> }>();

  for (const record of records) {
    const current = map.get(record.workDate) || { minutes: 0, records: 0, projects: new Set<string>() };
    current.minutes += record.durationMinutes;
    current.records += 1;
    current.projects.add(record.projectName);
    map.set(record.workDate, current);
  }

  return Array.from(map.entries())
    .map(([date, value]) => ({
      date,
      minutes: value.minutes,
      records: value.records,
      projects: value.projects.size,
    }))
    .sort((a, b) => b.date.localeCompare(a.date));
}

function SummaryCard({ icon, label, value, hint }: { icon: React.ReactNode; label: string; value: string; hint: string }) {
  return (
    <div className="rounded-2xl border border-border bg-card px-4 py-4 shadow-sm">
      <div className="flex items-center gap-2 text-xs font-medium text-muted-foreground">
        <span className="flex h-8 w-8 items-center justify-center rounded-xl bg-primary/8 text-primary">{icon}</span>
        {label}
      </div>
      <div className="mt-3 text-2xl font-semibold tracking-tight text-foreground">{value}</div>
      <p className="mt-1 text-[11px] text-muted-foreground">{hint}</p>
    </div>
  );
}

function PersonRow({ person, selected, maxMinutes, onSelect }: { person: CanonicalPerson; selected: boolean; maxMinutes: number; onSelect: () => void }) {
  const progress = maxMinutes > 0 ? Math.max(0, Math.min(100, (person.totalMinutes / maxMinutes) * 100)) : 0;

  return (
    <button
      type="button"
      onClick={onSelect}
      className={`w-full rounded-2xl border p-3.5 text-left transition-all ${
        selected
          ? "border-primary/35 bg-primary/[0.055] shadow-sm"
          : "border-border bg-card hover:border-primary/20 hover:bg-muted/20"
      }`}
    >
      <div className="flex items-start gap-3">
        <Avatar className="h-10 w-10 flex-shrink-0">
          <AvatarFallback className="bg-primary/10 text-xs font-semibold text-primary">{initials(person.name)}</AvatarFallback>
        </Avatar>
        <div className="min-w-0 flex-1">
          <div className="flex items-start justify-between gap-3">
            <div className="min-w-0">
              <div className="truncate text-sm font-semibold text-foreground">{person.name}</div>
              <div className="mt-1 flex flex-wrap items-center gap-1.5">
                <Badge variant="secondary" className="h-5 rounded-full px-2 text-[10px] font-medium">
                  {person.current ? "Equipo actual" : "Histórico"}
                </Badge>
                {person.daysWithEntries > 0 && (
                  <span className="text-[10px] text-muted-foreground">{person.daysWithEntries} {person.daysWithEntries === 1 ? "día" : "días"}</span>
                )}
              </div>
            </div>
            <div className="text-right">
              <div className="text-sm font-semibold text-foreground">{formatMinutes(person.totalMinutes, true)}</div>
              <div className="mt-0.5 text-[10px] text-muted-foreground">{formatAverage(person.averageMinutesPerLoggedDay)} / día</div>
            </div>
          </div>
          <Progress value={progress} className="mt-3 h-1.5" />
        </div>
      </div>
    </button>
  );
}

export function TeamHoursDialog({ open, onOpenChange }: { open: boolean; onOpenChange: (open: boolean) => void }) {
  const initialRange = useMemo(() => presetRange("7d"), []);
  const [preset, setPreset] = useState<PeriodPreset>("7d");
  const [from, setFrom] = useState(initialRange.from || "");
  const [to, setTo] = useState(initialRange.to || "");
  const [query, setQuery] = useState("");
  const [peopleFilter, setPeopleFilter] = useState<PeopleFilter>("current");
  const [sortMode, setSortMode] = useState<SortMode>("hours");
  const [records, setRecords] = useState<TeamHoursRecord[]>([]);
  const [roster, setRoster] = useState<TeamHoursRosterMember[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [selectedKey, setSelectedKey] = useState<string>("");
  const [selectedDay, setSelectedDay] = useState<string>("");
  const [recordPage, setRecordPage] = useState(1);

  const load = async () => {
    if (!open) return;

    try {
      setLoading(true);
      setError(null);
      const [nextRecords, nextRoster] = await Promise.all([
        loadTeamHoursRecords({ from: from || undefined, to: to || undefined }),
        loadTeamHoursRoster(),
      ]);
      setRecords(nextRecords);
      setRoster(nextRoster);
    } catch (loadError) {
      console.error("No se pudieron cargar las horas del equipo:", loadError);
      setError(loadError instanceof Error ? loadError.message : "No pudimos cargar las horas ahora. Intenta nuevamente.");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (!open) return;
    void load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, from, to]);

  const people = useMemo(() => buildPeople(records, roster), [records, roster]);

  const filteredPeople = useMemo(() => {
    const q = normalizeName(query);
    const next = people.filter((person) => {
      if (peopleFilter === "current" && !person.current) return false;
      if (peopleFilter === "historical" && person.current) return false;
      if (!q) return true;
      return normalizeName(person.name).includes(q) || normalizeName(person.email).includes(q);
    });

    return next.sort((a, b) => {
      if (sortMode === "name") return a.name.localeCompare(b.name, "es", { sensitivity: "base" });
      if (sortMode === "recent") return (b.lastDate || "").localeCompare(a.lastDate || "") || b.totalMinutes - a.totalMinutes;
      return b.totalMinutes - a.totalMinutes || a.name.localeCompare(b.name, "es", { sensitivity: "base" });
    });
  }, [people, peopleFilter, query, sortMode]);

  useEffect(() => {
    if (!filteredPeople.length) {
      setSelectedKey("");
      return;
    }
    if (!filteredPeople.some((person) => person.key === selectedKey)) {
      setSelectedKey(filteredPeople[0].key);
    }
  }, [filteredPeople, selectedKey]);

  const selectedPerson = filteredPeople.find((person) => person.key === selectedKey) || null;
  const daily = useMemo(() => buildDailySummaries(selectedPerson?.records || []), [selectedPerson]);

  useEffect(() => {
    setSelectedDay("");
    setRecordPage(1);
  }, [selectedKey, from, to]);

  const detailRecords = useMemo(() => {
    const base = selectedPerson?.records || [];
    return selectedDay ? base.filter((record) => record.workDate === selectedDay) : base;
  }, [selectedDay, selectedPerson]);

  const totalRecordPages = Math.max(1, Math.ceil(detailRecords.length / RECORDS_PER_PAGE));
  const safeRecordPage = Math.min(recordPage, totalRecordPages);
  const pagedRecords = detailRecords.slice((safeRecordPage - 1) * RECORDS_PER_PAGE, safeRecordPage * RECORDS_PER_PAGE);

  const visibleRecords = filteredPeople.flatMap((person) => person.records);
  const totalMinutes = filteredPeople.reduce((sum, person) => sum + person.totalMinutes, 0);
  const peopleWithHours = filteredPeople.filter((person) => person.totalMinutes > 0).length;
  const activityDays = new Set(visibleRecords.map((record) => record.workDate)).size;
  const teamPersonDays = filteredPeople.reduce((sum, person) => sum + person.daysWithEntries, 0);
  const averagePersonDay = teamPersonDays ? Math.round(totalMinutes / teamPersonDays) : 0;
  const maxPersonMinutes = Math.max(0, ...filteredPeople.map((person) => person.totalMinutes));
  const maxDailyMinutes = Math.max(0, ...daily.map((day) => day.minutes));

  const applyPreset = (nextPreset: PeriodPreset) => {
    setPreset(nextPreset);
    const range = presetRange(nextPreset);
    setFrom(range.from || "");
    setTo(range.to || "");
  };

  const setCustomFrom = (value: string) => {
    setPreset("custom");
    setFrom(value);
    if (value && to && value > to) setTo(value);
  };

  const setCustomTo = (value: string) => {
    setPreset("custom");
    setTo(value);
    if (value && from && value < from) setFrom(value);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[94vh] max-w-[1380px] overflow-hidden p-0 gap-0">
        <div className="border-b border-border bg-gradient-to-r from-primary/[0.06] via-background to-background px-6 py-5 sm:px-7">
          <DialogHeader>
            <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
              <div className="flex items-start gap-3">
                <span className="mt-0.5 flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-2xl bg-primary/10 text-primary shadow-sm">
                  <Users className="h-5 w-5" />
                </span>
                <div className="min-w-0">
                  <DialogTitle className="text-xl tracking-tight">Horas del equipo</DialogTitle>
                  <DialogDescription className="mt-1 max-w-2xl">
                    Consulta el tiempo registrado por persona, cuánto lleva por día y el detalle de sus actividades.
                  </DialogDescription>
                </div>
              </div>

              <Button type="button" variant="outline" size="sm" className="h-9 self-start rounded-full px-3.5 shadow-sm lg:mr-6" onClick={() => void load()} disabled={loading}>
                {loading ? <Loader2 className="mr-1.5 h-4 w-4 animate-spin" /> : <RefreshCw className="mr-1.5 h-4 w-4" />}
                Actualizar
              </Button>
            </div>
          </DialogHeader>
        </div>

        <div className="max-h-[calc(94vh-92px)] overflow-y-auto bg-muted/[0.12] px-5 py-5 sm:px-7 sm:py-6">
          <div className="space-y-5">
            <section className="rounded-2xl border border-border bg-card p-4 shadow-sm">
              <div className="flex flex-col gap-4 xl:flex-row xl:items-end xl:justify-between">
                <div className="flex flex-wrap gap-2">
                  {([
                    ["today", "Hoy"],
                    ["7d", "7 días"],
                    ["30d", "30 días"],
                    ["month", "Este mes"],
                    ["all", "Todo"],
                  ] as const).map(([value, label]) => (
                    <Button
                      key={value}
                      type="button"
                      size="sm"
                      variant={preset === value ? "default" : "outline"}
                      className="h-8 rounded-full px-3 text-xs"
                      onClick={() => applyPreset(value)}
                    >
                      {label}
                    </Button>
                  ))}
                </div>

                <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:w-[430px]">
                  <label className="space-y-1">
                    <span className="text-[11px] font-medium text-muted-foreground">Desde</span>
                    <Input type="date" value={from} onChange={(event) => setCustomFrom(event.target.value)} className="h-9" />
                  </label>
                  <label className="space-y-1">
                    <span className="text-[11px] font-medium text-muted-foreground">Hasta</span>
                    <Input type="date" value={to} onChange={(event) => setCustomTo(event.target.value)} className="h-9" />
                  </label>
                </div>
              </div>
            </section>

            {error ? (
              <div className="rounded-2xl border border-destructive/25 bg-destructive/5 px-5 py-7 text-center">
                <div className="text-sm font-semibold text-foreground">No pudimos cargar las horas</div>
                <p className="mt-1 text-xs text-muted-foreground">Intenta nuevamente en unos segundos.</p>
                <Button type="button" variant="outline" size="sm" className="mt-4 rounded-full" onClick={() => void load()}>
                  <RefreshCw className="mr-1.5 h-4 w-4" /> Reintentar
                </Button>
              </div>
            ) : (
              <>
                <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
                  <SummaryCard icon={<Clock3 className="h-4 w-4" />} label="Horas registradas" value={formatMinutes(totalMinutes, true)} hint={`${visibleRecords.length.toLocaleString("es")} registros en el periodo`} />
                  <SummaryCard icon={<Users className="h-4 w-4" />} label="Personas con horas" value={String(peopleWithHours)} hint={`${filteredPeople.length} personas visibles`} />
                  <SummaryCard icon={<CalendarDays className="h-4 w-4" />} label="Días con actividad" value={String(activityDays)} hint="Días con al menos un registro" />
                  <SummaryCard icon={<Sparkles className="h-4 w-4" />} label="Promedio por persona/día" value={formatAverage(averagePersonDay)} hint="Sobre días que tienen registros" />
                </div>

                <div className="grid grid-cols-1 gap-4 xl:grid-cols-[360px_minmax(0,1fr)]">
                  <section className="rounded-2xl border border-border bg-card shadow-sm">
                    <div className="border-b border-border p-4">
                      <div className="relative">
                        <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                        <Input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Buscar persona…" className="h-9 pl-9" />
                      </div>

                      <div className="mt-3 flex flex-wrap gap-1.5">
                        {([
                          ["all", "Todos"],
                          ["current", "Equipo actual"],
                          ["historical", "Histórico"],
                        ] as const).map(([value, label]) => (
                          <button
                            key={value}
                            type="button"
                            onClick={() => setPeopleFilter(value)}
                            className={`rounded-full px-2.5 py-1 text-[11px] font-medium transition-colors ${
                              peopleFilter === value ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground hover:text-foreground"
                            }`}
                          >
                            {label}
                          </button>
                        ))}
                      </div>

                      <div className="mt-3 flex items-center justify-between gap-2">
                        <span className="text-[11px] text-muted-foreground">{filteredPeople.length} personas</span>
                        <select
                          value={sortMode}
                          onChange={(event) => setSortMode(event.target.value as SortMode)}
                          className="h-8 rounded-lg border border-border bg-background px-2 text-[11px] text-foreground outline-none focus:border-primary/40"
                        >
                          <option value="hours">Más horas</option>
                          <option value="recent">Más recientes</option>
                          <option value="name">Nombre</option>
                        </select>
                      </div>
                    </div>

                    <div className="max-h-[620px] space-y-2 overflow-y-auto p-3">
                      {loading && !records.length ? (
                        Array.from({ length: 6 }).map((_, index) => <div key={index} className="h-[92px] animate-pulse rounded-2xl bg-muted" />)
                      ) : filteredPeople.length ? (
                        filteredPeople.map((person) => (
                          <PersonRow key={person.key} person={person} selected={person.key === selectedKey} maxMinutes={maxPersonMinutes} onSelect={() => setSelectedKey(person.key)} />
                        ))
                      ) : (
                        <div className="px-4 py-12 text-center">
                          <Users className="mx-auto h-7 w-7 text-muted-foreground/50" />
                          <p className="mt-2 text-sm font-medium">No hay personas para mostrar</p>
                          <p className="mt-1 text-xs text-muted-foreground">Prueba cambiando la búsqueda o el filtro.</p>
                        </div>
                      )}
                    </div>
                  </section>

                  <section className="min-w-0 rounded-2xl border border-border bg-card shadow-sm">
                    {selectedPerson ? (
                      <div>
                        <div className="border-b border-border p-5 sm:p-6">
                          <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
                            <div className="flex items-center gap-3">
                              <Avatar className="h-12 w-12">
                                <AvatarFallback className="bg-primary/10 text-sm font-semibold text-primary">{initials(selectedPerson.name)}</AvatarFallback>
                              </Avatar>
                              <div>
                                <div className="flex flex-wrap items-center gap-2">
                                  <h3 className="text-lg font-semibold tracking-tight">{selectedPerson.name}</h3>
                                  <Badge variant="secondary" className="rounded-full text-[10px]">
                                    {selectedPerson.current ? "Equipo actual" : "Histórico"}
                                  </Badge>
                                </div>
                                <p className="mt-1 text-xs text-muted-foreground">
                                  {selectedPerson.lastDate ? `Último registro: ${formatDateLabel(selectedPerson.lastDate)}` : "Sin registros en este periodo"}
                                </p>
                              </div>
                            </div>

                            <div className="grid grid-cols-3 gap-2 text-center lg:min-w-[390px]">
                              <div className="rounded-xl bg-muted/50 px-3 py-2.5">
                                <div className="text-[10px] font-medium uppercase tracking-wide text-muted-foreground">Total</div>
                                <div className="mt-1 text-sm font-semibold">{formatMinutes(selectedPerson.totalMinutes, true)}</div>
                              </div>
                              <div className="rounded-xl bg-muted/50 px-3 py-2.5">
                                <div className="text-[10px] font-medium uppercase tracking-wide text-muted-foreground">Promedio / día</div>
                                <div className="mt-1 text-sm font-semibold">{formatAverage(selectedPerson.averageMinutesPerLoggedDay)}</div>
                              </div>
                              <div className="rounded-xl bg-muted/50 px-3 py-2.5">
                                <div className="text-[10px] font-medium uppercase tracking-wide text-muted-foreground">Días</div>
                                <div className="mt-1 text-sm font-semibold">{selectedPerson.daysWithEntries}</div>
                              </div>
                            </div>
                          </div>
                        </div>

                        <div className="grid grid-cols-1 gap-5 p-5 sm:p-6 lg:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]">
                          <div>
                            <div className="mb-3 flex items-center justify-between gap-3">
                              <div>
                                <h4 className="text-sm font-semibold">Horas por día</h4>
                                <p className="mt-0.5 text-[11px] text-muted-foreground">Selecciona un día para ver únicamente sus actividades.</p>
                              </div>
                              {selectedDay && (
                                <Button type="button" variant="ghost" size="sm" className="h-7 rounded-full px-2 text-[11px]" onClick={() => setSelectedDay("")}>
                                  Ver todos
                                </Button>
                              )}
                            </div>

                            <div className="max-h-[430px] space-y-2 overflow-y-auto pr-1">
                              {daily.length ? (
                                daily.map((day) => {
                                  const width = maxDailyMinutes ? Math.max(5, (day.minutes / maxDailyMinutes) * 100) : 0;
                                  const active = selectedDay === day.date;
                                  return (
                                    <button
                                      key={day.date}
                                      type="button"
                                      onClick={() => setSelectedDay(active ? "" : day.date)}
                                      className={`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${
                                        active ? "border-primary/35 bg-primary/[0.055]" : "border-border bg-background hover:bg-muted/30"
                                      }`}
                                    >
                                      <div className="flex items-center justify-between gap-3">
                                        <div>
                                          <div className="text-xs font-semibold">{formatDateLabel(day.date)}</div>
                                          <div className="mt-0.5 text-[10px] text-muted-foreground">{day.projects} {day.projects === 1 ? "proyecto" : "proyectos"} · {day.records} {day.records === 1 ? "registro" : "registros"}</div>
                                        </div>
                                        <div className="text-sm font-semibold text-primary">{formatMinutes(day.minutes, true)}</div>
                                      </div>
                                      <div className="mt-2 h-1.5 overflow-hidden rounded-full bg-muted">
                                        <div className="h-full rounded-full bg-primary/75 transition-all" style={{ width: `${width}%` }} />
                                      </div>
                                    </button>
                                  );
                                })
                              ) : (
                                <div className="rounded-xl border border-dashed border-border px-4 py-12 text-center">
                                  <CalendarDays className="mx-auto h-7 w-7 text-muted-foreground/50" />
                                  <p className="mt-2 text-sm font-medium">Sin horas en este periodo</p>
                                  <p className="mt-1 text-xs text-muted-foreground">Cuando registre tiempo, aparecerá aquí.</p>
                                </div>
                              )}
                            </div>
                          </div>

                          <div className="min-w-0">
                            <div className="mb-3 flex items-center justify-between gap-3">
                              <div>
                                <h4 className="text-sm font-semibold">{selectedDay ? `Actividades · ${formatDateLabel(selectedDay)}` : "Actividades registradas"}</h4>
                                <p className="mt-0.5 text-[11px] text-muted-foreground">Proyecto, tarea, país y duración.</p>
                              </div>
                              <Badge variant="outline" className="rounded-full text-[10px]">{detailRecords.length} registros</Badge>
                            </div>

                            <div className="space-y-2">
                              {pagedRecords.length ? (
                                pagedRecords.map((record) => (
                                  <div key={`${record.recordSource}:${record.id}:${record.sourceKey}`} className="rounded-xl border border-border bg-background px-3.5 py-3">
                                    <div className="flex items-start justify-between gap-3">
                                      <div className="min-w-0">
                                        <div className="truncate text-xs font-semibold text-foreground">{record.projectName}</div>
                                        <div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-[10px] text-muted-foreground">
                                          <span>{record.taskName}</span>
                                          {record.country && <span>· {record.country}</span>}
                                          {!selectedDay && <span>· {formatDateLabel(record.workDate)}</span>}
                                        </div>
                                      </div>
                                      <span className="flex-shrink-0 rounded-full bg-primary/10 px-2.5 py-1 text-[11px] font-semibold text-primary">{formatMinutes(record.durationMinutes, true)}</span>
                                    </div>
                                    {record.notes && record.notes.toLowerCase() !== "sin comentarios" && (
                                      <p className="mt-2 line-clamp-2 text-[10px] leading-relaxed text-muted-foreground">{record.notes}</p>
                                    )}
                                  </div>
                                ))
                              ) : (
                                <div className="rounded-xl border border-dashed border-border px-4 py-12 text-center">
                                  <CheckCircle2 className="mx-auto h-7 w-7 text-muted-foreground/50" />
                                  <p className="mt-2 text-sm font-medium">No hay actividades para mostrar</p>
                                </div>
                              )}
                            </div>

                            {detailRecords.length > RECORDS_PER_PAGE && (
                              <div className="mt-4 flex items-center justify-between rounded-xl bg-muted/35 px-3 py-2">
                                <span className="text-[10px] text-muted-foreground">Página {safeRecordPage} de {totalRecordPages}</span>
                                <div className="flex items-center gap-1">
                                  <Button type="button" variant="ghost" size="icon" className="h-7 w-7 rounded-full" disabled={safeRecordPage <= 1} onClick={() => setRecordPage((page) => Math.max(1, page - 1))}>
                                    <ChevronLeft className="h-3.5 w-3.5" />
                                  </Button>
                                  <Button type="button" variant="ghost" size="icon" className="h-7 w-7 rounded-full" disabled={safeRecordPage >= totalRecordPages} onClick={() => setRecordPage((page) => Math.min(totalRecordPages, page + 1))}>
                                    <ChevronRight className="h-3.5 w-3.5" />
                                  </Button>
                                </div>
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                    ) : (
                      <div className="flex min-h-[440px] items-center justify-center px-6 text-center">
                        <div>
                          <History className="mx-auto h-9 w-9 text-muted-foreground/40" />
                          <h3 className="mt-3 text-sm font-semibold">Selecciona una persona</h3>
                          <p className="mt-1 text-xs text-muted-foreground">Aquí verás su resumen diario y las actividades registradas.</p>
                        </div>
                      </div>
                    )}
                  </section>
                </div>
              </>
            )}
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
