'use client';

import { useCallback, useEffect, useState } from 'react';
import { Search, Plus, Clock, Phone, User } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { api } from '@/lib/api';
import { CreateVptDialog } from './create-vpt-dialog';

interface TrainingClient {
  id: string;
  firstName: string;
  lastName: string;
  phone: string;
}

interface TrainingTrainer {
  id: string;
  firstName: string;
  lastName: string;
}

interface TrainingService {
  id: string;
  name: string;
  duration: number;
}

interface Training {
  id: string;
  scheduledAt: string;
  duration: number;
  status: string;
  client: TrainingClient;
  trainer: TrainingTrainer;
  service: TrainingService | null;
}

interface Appointment {
  id: string;
  clientName: string;
  clientPhone: string;
  time: string;
  trainer: string;
  type: string;
  status: 'planned' | 'confirmed' | 'completed' | 'cancelled';
}

const statusLabels: Record<Appointment['status'], string> = {
  planned: 'Запланировано',
  confirmed: 'Подтверждено',
  completed: 'Проведено',
  cancelled: 'Отменено',
};

const statusVariants: Record<
  Appointment['status'],
  'warning' | 'success' | 'default' | 'error'
> = {
  planned: 'warning',
  confirmed: 'success',
  completed: 'default',
  cancelled: 'error',
};

function mapTrainingStatus(status: string): Appointment['status'] {
  const statusMap: Record<string, Appointment['status']> = {
    PLANNED: 'planned',
    CONFIRMED: 'confirmed',
    COMPLETED: 'completed',
    CANCELLED: 'cancelled',
  };
  return statusMap[status] ?? 'planned';
}

function formatTime(isoString: string): string {
  const date = new Date(isoString);
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
}

function mapTrainingToAppointment(training: Training): Appointment {
  return {
    id: training.id,
    clientName: `${training.client.lastName} ${training.client.firstName}`,
    clientPhone: training.client.phone,
    time: formatTime(training.scheduledAt),
    trainer: `${training.trainer.lastName} ${training.trainer.firstName.charAt(0)}.`,
    type: training.service?.name ?? 'Тренировка',
    status: mapTrainingStatus(training.status),
  };
}

export default function ReceptionPage() {
  const [search, setSearch] = useState('');
  const [appointments, setAppointments] = useState<Appointment[]>([]);
  const [loading, setLoading] = useState(true);
  const [vptDialogOpen, setVptDialogOpen] = useState(false);

  const loadTrainings = useCallback(() => {
    setLoading(true);
    api
      .get<{ data: Training[]; hasMore: boolean; nextCursor: string | null }>(
        '/trainings?limit=50',
      )
      .then((res) => {
        setAppointments(res.data.map(mapTrainingToAppointment));
      })
      .catch(() => {
        setAppointments([]);
      })
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    loadTrainings();
  }, [loadTrainings]);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#FF6B00]" />
      </div>
    );
  }

  const filteredAppointments = appointments.filter(
    (a) =>
      a.clientName.toLowerCase().includes(search.toLowerCase()) ||
      a.clientPhone.includes(search),
  );

  return (
    <div className="space-y-6">
      {/* Actions bar */}
      <div className="flex items-center justify-between gap-4">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
          <input
            type="text"
            placeholder="Поиск по имени или телефону..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="h-10 w-full rounded-xl border border-[#E5E7EB] bg-white pl-9 pr-3 text-sm text-gray-900 placeholder:text-gray-400 focus:border-[#FF6B00] focus:outline-none focus:ring-2 focus:ring-[#FF6B00]/20"
          />
        </div>
        <Button onClick={() => setVptDialogOpen(true)}>
          <Plus className="mr-2 h-4 w-4" />
          Записать на ВПТ
        </Button>
      </div>

      <CreateVptDialog
        open={vptDialogOpen}
        onOpenChange={setVptDialogOpen}
        onCreated={loadTrainings}
      />

      {/* Stats cards */}
      <div className="grid grid-cols-4 gap-4">
        <Card>
          <CardContent className="p-4">
            <p className="text-sm text-[#6B7280]">Всего записей</p>
            <p className="text-2xl font-bold text-gray-900">
              {appointments.length}
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <p className="text-sm text-[#6B7280]">Подтверждено</p>
            <p className="text-2xl font-bold text-[#43A047]">
              {appointments.filter((a) => a.status === 'confirmed').length}
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <p className="text-sm text-[#6B7280]">Ожидает</p>
            <p className="text-2xl font-bold text-[#FF9800]">
              {appointments.filter((a) => a.status === 'planned').length}
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <p className="text-sm text-[#6B7280]">Отменено</p>
            <p className="text-2xl font-bold text-[#E53935]">
              {appointments.filter((a) => a.status === 'cancelled').length}
            </p>
          </CardContent>
        </Card>
      </div>

      {/* Appointments table */}
      <Card>
        <CardHeader>
          <CardTitle>Записи на сегодня</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-[#E5E7EB]">
                  <th className="pb-3 text-left font-medium text-[#6B7280]">
                    Время
                  </th>
                  <th className="pb-3 text-left font-medium text-[#6B7280]">
                    Клиент
                  </th>
                  <th className="pb-3 text-left font-medium text-[#6B7280]">
                    Телефон
                  </th>
                  <th className="pb-3 text-left font-medium text-[#6B7280]">
                    Тренер
                  </th>
                  <th className="pb-3 text-left font-medium text-[#6B7280]">
                    Тип
                  </th>
                  <th className="pb-3 text-left font-medium text-[#6B7280]">
                    Статус
                  </th>
                </tr>
              </thead>
              <tbody>
                {filteredAppointments.map((appointment) => (
                  <tr
                    key={appointment.id}
                    className="border-b border-[#E5E7EB] last:border-0"
                  >
                    <td className="py-3">
                      <div className="flex items-center gap-2">
                        <Clock className="h-4 w-4 text-gray-400" />
                        {appointment.time}
                      </div>
                    </td>
                    <td className="py-3">
                      <div className="flex items-center gap-2">
                        <User className="h-4 w-4 text-gray-400" />
                        {appointment.clientName}
                      </div>
                    </td>
                    <td className="py-3">
                      <div className="flex items-center gap-2">
                        <Phone className="h-4 w-4 text-gray-400" />
                        {appointment.clientPhone}
                      </div>
                    </td>
                    <td className="py-3">{appointment.trainer}</td>
                    <td className="py-3">{appointment.type}</td>
                    <td className="py-3">
                      <Badge variant={statusVariants[appointment.status]}>
                        {statusLabels[appointment.status]}
                      </Badge>
                    </td>
                  </tr>
                ))}
                {filteredAppointments.length === 0 && (
                  <tr>
                    <td
                      colSpan={6}
                      className="py-8 text-center text-[#6B7280]"
                    >
                      Записи не найдены
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
