'use client';

import { useState } from 'react';
import { Header } from '@/components/layouts/header';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useTenants, useCreateTenant } from '@/lib/hooks/use-tenants';
import { useTenantViewStore } from '@/stores/tenant-view-store';
import { useAuthStore } from '@/stores/auth-store';
import { Building, Plus, Users, Eye, Calendar } from 'lucide-react';

export default function ClientesPage() {
  const { user } = useAuthStore();
  const { data: tenants, isLoading } = useTenants();
  const createTenant = useCreateTenant();
  const { setViewingTenant } = useTenantViewStore();

  const [showForm, setShowForm] = useState(false);
  const [formData, setFormData] = useState({
    nombre: '',
    rfc: '',
    plan: 'starter' as const,
  });

  // Only admins can access this page
  if (user?.role !== 'admin') {
    return (
      <>
        <Header title="Clientes" />
        <main className="p-6">
          <Card>
            <CardContent className="py-12 text-center">
              <p className="text-muted-foreground">
                No tienes permisos para ver esta página.
              </p>
            </CardContent>
          </Card>
        </main>
      </>
    );
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    try {
      await createTenant.mutateAsync(formData);
      setFormData({ nombre: '', rfc: '', plan: 'starter' });
      setShowForm(false);
    } catch (error) {
      console.error('Error creating tenant:', error);
    }
  };

  const handleViewClient = (tenantId: string, tenantName: string) => {
    setViewingTenant(tenantId, tenantName);
    window.location.href = '/dashboard';
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('es-MX', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    });
  };

  const planLabels: Record<string, string> = {
    starter: 'Starter',
    business: 'Business',
    professional: 'Professional',
    enterprise: 'Enterprise',
  };

  const planColors: Record<string, string> = {
    starter: 'bg-muted text-muted-foreground',
    business: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-100',
    professional: 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-100',
    enterprise: 'bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-100',
  };

  return (
    <>
      <Header title="Gestión de Clientes" />
      <main className="p-6 space-y-6">
        {/* Stats */}
        <div className="grid gap-4 md:grid-cols-3">
          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-3 bg-primary/10 rounded-lg">
                  <Building className="h-6 w-6 text-primary" />
                </div>
                <div>
                  <p className="text-2xl font-bold">{tenants?.length || 0}</p>
                  <p className="text-sm text-muted-foreground">Total Clientes</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center gap-4">
                <div className="p-3 bg-success/10 rounded-lg">
                  <Users className="h-6 w-6 text-success" />
                </div>
                <div>
                  <p className="text-2xl font-bold">
                    {tenants?.reduce((acc, t) => acc + (t._count?.users || 0), 0) || 0}
                  </p>
                  <p className="text-sm text-muted-foreground">Total Usuarios</p>
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="pt-6">
              <Button onClick={() => setShowForm(true)} className="w-full h-full min-h-[60px]">
                <Plus className="h-5 w-5 mr-2" />
                Agregar Cliente
              </Button>
            </CardContent>
          </Card>
        </div>

        {/* Add Client Form */}
        {showForm && (
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Nuevo Cliente</CardTitle>
              <CardDescription>
                Registra un nuevo cliente para gestionar su facturación
              </CardDescription>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleSubmit} className="space-y-4">
                <div className="grid gap-4 md:grid-cols-2">
                  <div className="space-y-2">
                    <Label htmlFor="nombre">Nombre de la Empresa</Label>
                    <Input
                      id="nombre"
                      value={formData.nombre}
                      onChange={(e) => setFormData({ ...formData, nombre: e.target.value })}
                      placeholder="Empresa SA de CV"
                      required
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="rfc">RFC</Label>
                    <Input
                      id="rfc"
                      value={formData.rfc}
                      onChange={(e) => setFormData({ ...formData, rfc: e.target.value.toUpperCase() })}
                      placeholder="XAXX010101000"
                      maxLength={13}
                      required
                    />
                  </div>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="plan">Plan</Label>
                  <Select
                    value={formData.plan}
                    onValueChange={(value: 'starter' | 'business' | 'professional' | 'enterprise') =>
                      setFormData({ ...formData, plan: value })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="starter">Starter - 500 CFDIs, 3 usuarios</SelectItem>
                      <SelectItem value="business">Business - 1,000 CFDIs, 5 usuarios</SelectItem>
                      <SelectItem value="professional">Professional - 2,000 CFDIs, 10 usuarios</SelectItem>
                      <SelectItem value="enterprise">Enterprise - Ilimitado</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="flex gap-2 justify-end">
                  <Button type="button" variant="outline" onClick={() => setShowForm(false)}>
                    Cancelar
                  </Button>
                  <Button type="submit" disabled={createTenant.isPending}>
                    {createTenant.isPending ? 'Creando...' : 'Crear Cliente'}
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        )}

        {/* Clients List */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">Lista de Clientes</CardTitle>
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="text-center py-8 text-muted-foreground">Cargando...</div>
            ) : tenants && tenants.length > 0 ? (
              <div className="space-y-3">
                {tenants.map((tenant) => (
                  <div
                    key={tenant.id}
                    className="flex items-center justify-between p-4 rounded-lg border hover:bg-muted/50 transition-colors"
                  >
                    <div className="flex items-center gap-4">
                      <div className="h-12 w-12 rounded-lg bg-primary/10 flex items-center justify-center">
                        <span className="font-bold text-primary">
                          {tenant.nombre.substring(0, 2).toUpperCase()}
                        </span>
                      </div>
                      <div>
                        <p className="font-medium">{tenant.nombre}</p>
                        <div className="flex items-center gap-3 text-sm text-muted-foreground">
                          <span>{tenant.rfc}</span>
                          <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${planColors[tenant.plan]}`}>
                            {planLabels[tenant.plan]}
                          </span>
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center gap-6">
                      <div className="text-right">
                        <div className="flex items-center gap-1 text-sm">
                          <Users className="h-4 w-4 text-muted-foreground" />
                          <span>{tenant._count?.users || 0} usuarios</span>
                        </div>
                        <div className="flex items-center gap-1 text-xs text-muted-foreground">
                          <Calendar className="h-3 w-3" />
                          <span>{formatDate(tenant.createdAt)}</span>
                        </div>
                      </div>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleViewClient(tenant.id, tenant.nombre)}
                      >
                        <Eye className="h-4 w-4 mr-1" />
                        Ver
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center py-8 text-muted-foreground">
                No hay clientes registrados
              </div>
            )}
          </CardContent>
        </Card>
      </main>
    </>
  );
}
