'use client';

import { useEffect, useState } from 'react';
import { UserPlus, ChevronRight } 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';

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

interface FunnelEntry {
  id: string;
  stage: string;
  createdAt: string;
  comment: string | null;
  client: FunnelClient;
}

interface TrainerUser {
  id: string;
  firstName: string;
  lastName: string;
  phone: string;
  role: string;
  isActive: boolean;
}

interface UnassignedClient {
  id: string;
  name: string;
  phone: string;
  registeredAt: string;
  source: string;
}

interface Trainer {
  id: string;
  name: string;
  department: string;
  activeClients: number;
  capacity: number;
}

function mapFunnelEntryToClient(entry: FunnelEntry): UnassignedClient {
  return {
    id: entry.client.id,
    name: `${entry.client.lastName} ${entry.client.firstName}`,
    phone: entry.client.phone,
    registeredAt: new Date(entry.createdAt).toISOString().split('T')[0] ?? '',
    source: 'Воронка',
  };
}

function mapUserToTrainer(user: TrainerUser): Trainer {
  return {
    id: user.id,
    name: `${user.lastName} ${user.firstName.charAt(0)}.`,
    department: '',
    activeClients: 0,
    capacity: 20,
  };
}

export default function DistributionPage() {
  const [selectedClient, setSelectedClient] = useState<string | null>(null);
  const [selectedTrainer, setSelectedTrainer] = useState<string | null>(null);
  const [clients, setClients] = useState<UnassignedClient[]>([]);
  const [trainers, setTrainers] = useState<Trainer[]>([]);
  const [loading, setLoading] = useState(true);
  const [assigning, setAssigning] = useState(false);

  const fetchData = () => {
    setLoading(true);
    void Promise.all([
      api
        .get<{ data: FunnelEntry[]; hasMore: boolean; nextCursor: string | null }>(
          '/funnel?stage=NEW&limit=50',
        )
        .then((res) => res.data.map(mapFunnelEntryToClient))
        .catch(() => [] as UnassignedClient[]),
      api
        .get<TrainerUser[]>('/users/trainers')
        .then((res) => res.map(mapUserToTrainer))
        .catch(() => [] as Trainer[]),
    ])
      .then(([clientsData, trainersData]) => {
        setClients(clientsData);
        setTrainers(trainersData);
      })
      .finally(() => setLoading(false));
  };

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

  const handleAssign = () => {
    if (selectedClient && selectedTrainer) {
      setAssigning(true);
      api
        .post('/funnel/assign', {
          clientId: selectedClient,
          trainerId: selectedTrainer,
        })
        .then(() => {
          setSelectedClient(null);
          setSelectedTrainer(null);
          fetchData();
        })
        .catch(() => {
          alert('Ошибка при назначении тренера');
        })
        .finally(() => setAssigning(false));
    }
  };

  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>
    );
  }

  return (
    <div className="space-y-6">
      {/* Stats */}
      <div className="grid grid-cols-3 gap-4">
        <Card>
          <CardContent className="p-4">
            <p className="text-sm text-[#6B7280]">Нераспределённые</p>
            <p className="text-2xl font-bold text-[#FF6B00]">
              {clients.length}
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <p className="text-sm text-[#6B7280]">Тренеров доступно</p>
            <p className="text-2xl font-bold text-gray-900">
              {trainers.length}
            </p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <p className="text-sm text-[#6B7280]">Распределено сегодня</p>
            <p className="text-2xl font-bold text-[#43A047]">--</p>
          </CardContent>
        </Card>
      </div>

      <div className="grid grid-cols-2 gap-6">
        {/* Unassigned clients */}
        <Card>
          <CardHeader>
            <CardTitle>Нераспределённые клиенты</CardTitle>
          </CardHeader>
          <CardContent className="space-y-2">
            {clients.map((client) => (
              <button
                key={client.id}
                onClick={() => setSelectedClient(client.id)}
                className={`flex w-full items-center justify-between rounded-xl border p-3 text-left transition-colors ${
                  selectedClient === client.id
                    ? 'border-[#FF6B00] bg-[#FF6B00]/5'
                    : 'border-[#E5E7EB] hover:border-gray-300'
                }`}
              >
                <div>
                  <p className="font-medium text-gray-900">{client.name}</p>
                  <p className="text-sm text-[#6B7280]">{client.phone}</p>
                  <p className="text-xs text-[#6B7280]">
                    Зарегистрирован: {client.registeredAt}
                  </p>
                </div>
                <div className="flex items-center gap-2">
                  <Badge>{client.source}</Badge>
                  <ChevronRight className="h-4 w-4 text-gray-400" />
                </div>
              </button>
            ))}
            {clients.length === 0 && (
              <p className="py-8 text-center text-[#6B7280]">
                Все клиенты распределены
              </p>
            )}
          </CardContent>
        </Card>

        {/* Trainers */}
        <Card>
          <CardHeader>
            <CardTitle>Выберите тренера</CardTitle>
          </CardHeader>
          <CardContent className="space-y-2">
            {trainers.map((trainer) => (
              <button
                key={trainer.id}
                onClick={() => setSelectedTrainer(trainer.id)}
                className={`flex w-full items-center justify-between rounded-xl border p-3 text-left transition-colors ${
                  selectedTrainer === trainer.id
                    ? 'border-[#FF6B00] bg-[#FF6B00]/5'
                    : 'border-[#E5E7EB] hover:border-gray-300'
                }`}
              >
                <div>
                  <p className="font-medium text-gray-900">{trainer.name}</p>
                  <p className="text-sm text-[#6B7280]">
                    {trainer.department || 'Тренер'}
                  </p>
                </div>
                <div className="text-right">
                  <p className="text-sm font-medium text-gray-900">
                    {trainer.activeClients}/{trainer.capacity}
                  </p>
                  <p className="text-xs text-[#6B7280]">клиентов</p>
                </div>
              </button>
            ))}
            {trainers.length === 0 && (
              <p className="py-8 text-center text-[#6B7280]">
                Тренеры не найдены
              </p>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Assign button */}
      {selectedClient && selectedTrainer && (
        <div className="flex justify-end">
          <Button onClick={handleAssign} size="lg" disabled={assigning}>
            <UserPlus className="mr-2 h-5 w-5" />
            {assigning ? 'Назначение...' : 'Назначить тренера'}
          </Button>
        </div>
      )}
    </div>
  );
}
