import { useState } from 'react';
import { Layout } from '@/components/Layout';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { useToast } from '@/hooks/use-toast';
import { Plus, Trash2, Key, Copy } from 'lucide-react';
import { mockApiKeys, ApiKey, ApiKeyCreateAnswere, ApiKeyCreateResponse, useKeyApiUpdater} from '@/data/mockData';
import api from '@/lib/axios';

const ApiKeys = () => {
  const [apiKeys, setApiKeys] = useState<ApiKey[]>([]);
  const { isLoading, error, fetchAndApplyApiKey } = useKeyApiUpdater(setApiKeys);
  const [newKeyName, setNewKeyName] = useState('');
  const { toast } = useToast();

  const handleCreateKey = () => {

    const currentName = newKeyName.trim();

    if (!currentName) {
      toast({
        title: 'Erreur',
        description: 'Le nom de la clé API est requis.',
        variant: 'destructive',
      });
      return;
    }

    const createApiKey = async () => {
      try {
        const response = await api.post<ApiKeyCreateResponse>(`/createApiKey`, {
          key_name: currentName
        });

        const newKey: ApiKey = {
          id: response.data.id,
          key_name: response.data.key_name,
          key: response.data.key,
        };

        setApiKeys([...apiKeys, newKey]);
        setNewKeyName('');

        toast({
          title: 'Clé API créée',
          description: `La clé "${currentName}" a été créée avec succès.`,
        });

      } catch (err: any) {
          console.error("Erreur lors de la mise à jour: Ajouter /api devant toutes tes routes dans ton routeur Go.", err);
      }
    }

    createApiKey();
  };

  const handleDeleteKey = (id: number, name: string) => {
    setApiKeys(apiKeys.filter((key) => key.id !== id));

    toast({
      title: 'Clé API supprimée',
      description: `La clé "${name}" a été supprimée.`,
      variant: 'destructive',
    });
  };

  const handleCopyKey = (key: string) => {
    navigator.clipboard.writeText(key);
    toast({
      title: 'Copié',
      description: 'La clé API a été copiée dans le presse-papier.',
    });
  };

  return (
    <Layout>
      <div className="space-y-6">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold tracking-tight">Clés API</h1>
          <p className="text-sm sm:text-base text-muted-foreground mt-1">
            Gérez les clés API pour les services tiers
          </p>
        </div>

        {/* Create new API key */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-lg">
              <Key className="h-5 w-5" />
              Créer une nouvelle clé API
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex flex-col sm:flex-row gap-3">
              <div className="flex-1 space-y-2">
                <Label htmlFor="keyName">Nom de la clé</Label>
                <Input
                  id="keyName"
                  placeholder="Ex: Service de monitoring"
                  value={newKeyName}
                  onChange={(e) => setNewKeyName(e.target.value)}
                  onKeyDown={(e) => e.key === 'Enter' && handleCreateKey()}
                />
              </div>
              <div className="flex items-end">
                <Button onClick={handleCreateKey} className="w-full sm:w-auto">
                  <Plus className="h-4 w-4 mr-2" />
                  Créer la clé
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* API keys list */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">Clés API existantes</CardTitle>
          </CardHeader>
          <CardContent>
            {apiKeys.length === 0 ? (
              <p className="text-muted-foreground text-center py-8">
                Aucune clé API n'a été créée.
              </p>
            ) : (
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Nom</TableHead>
                      <TableHead>Clé</TableHead>
                      <TableHead className="w-[100px]">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {apiKeys.map((apiKey) => (
                      <TableRow key={apiKey.id}>
                        <TableCell className="font-medium">{apiKey.key_name}</TableCell>
                        <TableCell>
                          <div className="flex items-center gap-2">
                            <code className="text-xs sm:text-sm bg-muted px-2 py-1 rounded font-mono truncate max-w-[150px] sm:max-w-[300px]">
                              {apiKey.key}
                            </code>
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={() => handleCopyKey(apiKey.key)}
                              className="h-8 w-8 shrink-0"
                            >
                              <Copy className="h-4 w-4" />
                            </Button>
                          </div>
                        </TableCell>
                        <TableCell>
                          <Button
                            variant="destructive"
                            size="icon"
                            onClick={() => handleDeleteKey(apiKey.id, apiKey.key_name)}
                            className="h-8 w-8"
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </Layout>
  );
};

export default ApiKeys;
