import { useState } from "react";
import { Plus, RefreshCw, Search, Trash2 } from "lucide-react";

// Tipo estendido para incluir campos adicionais
interface ConsultaExtended {
  id: string;
  dataHora?: string;
  pacienteNome?: string;
  medicoNome?: string;
  tipo?: string;
  status?: string;
}

interface ConsultasSectionProps {
  consultas: ConsultaExtended[];
  loading: boolean;
  onRefresh: () => void;
  onNovaConsulta: () => void;
  onDeleteConsulta: (id: string) => void;
  onAlterarStatus: (id: string, status: string) => void;
}

export default function ConsultasSection({
  consultas,
  loading,
  onRefresh,
  onNovaConsulta,
  onDeleteConsulta,
  onAlterarStatus,
}: ConsultasSectionProps) {
  const [searchTerm, setSearchTerm] = useState("");
  const [filtroDataDe, setFiltroDataDe] = useState("");
  const [filtroDataAte, setFiltroDataAte] = useState("");
  const [filtroStatus, setFiltroStatus] = useState("");
  const [filtroPaciente, setFiltroPaciente] = useState("");
  const [filtroMedico, setFiltroMedico] = useState("");

  const formatDateTimeLocal = (dateStr: string | undefined) => {
    if (!dateStr) return "-";
    try {
      const date = new Date(dateStr);
      return date.toLocaleString("pt-BR", {
        day: "2-digit",
        month: "2-digit",
        year: "numeric",
        hour: "2-digit",
        minute: "2-digit",
      });
    } catch {
      return dateStr;
    }
  };

  // Filtrar consultas
  const consultasFiltradas = consultas.filter((c) => {
    // Filtro de busca rápida
    if (searchTerm) {
      const search = searchTerm.toLowerCase();
      const matchPaciente = c.pacienteNome?.toLowerCase().includes(search);
      const matchMedico = c.medicoNome?.toLowerCase().includes(search);
      const matchTipo = c.tipo?.toLowerCase().includes(search);
      if (!matchPaciente && !matchMedico && !matchTipo) return false;
    }

    // Filtro por data de
    if (filtroDataDe && c.dataHora) {
      const consultaDate = new Date(c.dataHora).toISOString().split("T")[0];
      if (consultaDate < filtroDataDe) return false;
    }

    // Filtro por data até
    if (filtroDataAte && c.dataHora) {
      const consultaDate = new Date(c.dataHora).toISOString().split("T")[0];
      if (consultaDate > filtroDataAte) return false;
    }

    // Filtro por status
    if (filtroStatus && c.status !== filtroStatus) return false;

    // Filtro por paciente
    if (
      filtroPaciente &&
      !c.pacienteNome?.toLowerCase().includes(filtroPaciente.toLowerCase())
    ) {
      return false;
    }

    // Filtro por médico
    if (
      filtroMedico &&
      !c.medicoNome?.toLowerCase().includes(filtroMedico.toLowerCase())
    ) {
      return false;
    }

    return true;
  });

  return (
    <section className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Consultas</h1>
          <p className="text-muted-foreground">
            Gerencie todas as consultas agendadas
          </p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={onRefresh}
            className="inline-flex items-center gap-2 border border-input hover:bg-accent text-foreground px-4 py-2 rounded-md transition-colors"
          >
            <RefreshCw className="w-4 h-4" />
            <span className="hidden md:inline">Atualizar</span>
          </button>
          <button
            onClick={onNovaConsulta}
            className="inline-flex items-center gap-2 bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-md transition-all"
          >
            <Plus className="w-4 h-4" />
            Nova Consulta
          </button>
        </div>
      </div>

      {/* Search and Filters */}
      <div className="bg-card rounded-lg border border-border p-4 space-y-4">
        <div className="flex gap-3">
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <input
              type="text"
              placeholder="Busca rápida (paciente, médico ou tipo)"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10 w-full h-10 px-3 rounded-md border border-input bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-ring"
            />
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-5 gap-3">
          <div>
            <label className="block text-xs font-medium text-muted-foreground mb-1">
              Data de
            </label>
            <input
              type="date"
              value={filtroDataDe}
              onChange={(e) => setFiltroDataDe(e.target.value)}
              className="w-full h-9 px-3 rounded-md border border-input bg-background text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-ring"
            />
          </div>
          <div>
            <label className="block text-xs font-medium text-muted-foreground mb-1">
              Data até
            </label>
            <input
              type="date"
              value={filtroDataAte}
              onChange={(e) => setFiltroDataAte(e.target.value)}
              className="w-full h-9 px-3 rounded-md border border-input bg-background text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-ring"
            />
          </div>
          <div>
            <label className="block text-xs font-medium text-muted-foreground mb-1">
              Status
            </label>
            <select
              value={filtroStatus}
              onChange={(e) => setFiltroStatus(e.target.value)}
              className="w-full h-9 px-3 rounded-md border border-input bg-background text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-ring"
            >
              <option value="">Todos</option>
              <option value="agendada">Agendada</option>
              <option value="confirmada">Confirmada</option>
              <option value="cancelada">Cancelada</option>
              <option value="realizada">Realizada</option>
            </select>
          </div>
          <div>
            <label className="block text-xs font-medium text-muted-foreground mb-1">
              Paciente
            </label>
            <input
              value={filtroPaciente}
              onChange={(e) => setFiltroPaciente(e.target.value)}
              className="w-full h-9 px-3 rounded-md border border-input bg-background text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-ring"
              placeholder="Filtrar paciente"
            />
          </div>
          <div>
            <label className="block text-xs font-medium text-muted-foreground mb-1">
              Médico
            </label>
            <input
              value={filtroMedico}
              onChange={(e) => setFiltroMedico(e.target.value)}
              className="w-full h-9 px-3 rounded-md border border-input bg-background text-foreground text-sm focus:outline-none focus:ring-2 focus:ring-ring"
              placeholder="Filtrar médico"
            />
          </div>
        </div>
      </div>

      {/* Appointments Table */}
      <div className="bg-card rounded-lg border border-border overflow-hidden">
        {loading ? (
          <div className="flex justify-center py-12">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
          </div>
        ) : consultasFiltradas.length === 0 ? (
          <div className="text-center py-12">
            <p className="text-muted-foreground">
              Nenhum agendamento encontrado. Use a aba "Agenda" para gerenciar
              horários dos médicos.
            </p>
          </div>
        ) : (
          <table className="w-full">
            <thead className="bg-muted/50 border-b border-border">
              <tr>
                <th className="text-left p-4 text-sm font-medium text-muted-foreground uppercase">
                  Data/Hora
                </th>
                <th className="text-left p-4 text-sm font-medium text-muted-foreground uppercase">
                  Paciente
                </th>
                <th className="text-left p-4 text-sm font-medium text-muted-foreground uppercase">
                  Médico
                </th>
                <th className="text-left p-4 text-sm font-medium text-muted-foreground uppercase">
                  Tipo
                </th>
                <th className="text-left p-4 text-sm font-medium text-muted-foreground uppercase">
                  Status
                </th>
                <th className="text-left p-4 text-sm font-medium text-muted-foreground uppercase w-[140px]">
                  Ações
                </th>
              </tr>
            </thead>
            <tbody>
              {consultasFiltradas.map((consulta) => (
                <tr
                  key={consulta.id}
                  className="border-b border-border hover:bg-muted/30 transition-colors"
                >
                  <td className="p-4 text-sm text-foreground whitespace-nowrap">
                    {formatDateTimeLocal(consulta.dataHora)}
                  </td>
                  <td className="p-4 text-sm text-foreground">
                    {consulta.pacienteNome}
                  </td>
                  <td className="p-4 text-sm text-foreground">
                    {consulta.medicoNome}
                  </td>
                  <td className="p-4 text-sm text-foreground">
                    {consulta.tipo}
                  </td>
                  <td className="p-4">
                    <select
                      value={consulta.status}
                      onChange={(e) =>
                        consulta.id &&
                        onAlterarStatus(consulta.id, e.target.value)
                      }
                      className="text-sm border border-input rounded-md px-2 py-1 bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-ring"
                    >
                      <option value="agendada">Agendada</option>
                      <option value="confirmada">Confirmada</option>
                      <option value="cancelada">Cancelada</option>
                      <option value="realizada">Realizada</option>
                      <option value="faltou">Faltou</option>
                    </select>
                  </td>
                  <td className="p-4">
                    <button
                      onClick={() =>
                        consulta.id && onDeleteConsulta(consulta.id)
                      }
                      className="inline-flex items-center gap-1 px-3 py-1.5 rounded-md text-sm bg-destructive/10 text-destructive hover:bg-destructive/20 transition-colors"
                    >
                      <Trash2 className="h-4 w-4" />
                      Excluir
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </section>
  );
}


