'use client';

import { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Button } from '@/features/shared/components/ui/button';
import { Input } from '@/features/shared/components/ui/input';
import {
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
} from '@/features/shared/components/ui/card';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/features/shared/components/ui/dialog';
import {
  Key,
  Plus,
  Trash2,
  Copy,
  Check,
  Eye,
  EyeOff,
  AlertCircle,
  CheckCircle2,
} from 'lucide-react';
import { useTranslations } from 'next-intl';
import { useI18n } from '@/features/theme';

/**
 * EN: API Key interface
 * VI: Interface cho API Key
 */
interface ApiKey {
  id: string;
  name: string;
  keyPrefix: string; // EN: First few characters of the key / VI: Một vài ký tự đầu của key
  keySuffix: string; // EN: Last 4 characters of the key / VI: 4 ký tự cuối của key
  createdAt: string;
  lastUsedAt: string | null;
  expiresAt: string | null;
}

/**
 * EN: Create API key schema with translated messages
 * VI: Tạo API key schema với thông báo đã dịch
 */
function createApiKeySchema(
  t: (key: string, values?: Record<string, any>) => string
) {
  return z.object({
    name: z
      .string()
      .min(1, t('settings.apiKeys.nameRequired'))
      .max(100, t('validation.maxLength', { max: 100 })),
    description: z
      .string()
      .max(500, t('validation.maxLength', { max: 500 }))
      .optional(),
  });
}

/**
 * EN: Format timestamp to relative time string
 * VI: Format timestamp thành chuỗi thời gian tương đối
 */
function formatRelativeTime(date: string | null, t: (key: string, values?: any) => string, locale: string): string {
  if (!date) return t('settings.security.never');
  const dateObj = new Date(date);
  const now = new Date();
  const diffMs = now.getTime() - dateObj.getTime();
  const diffMins = Math.floor(diffMs / 60000);
  const diffHours = Math.floor(diffMs / 3600000);
  const diffDays = Math.floor(diffMs / 86400000);

  if (diffMins < 1) return t('chat.justNow');
  if (diffMins < 60) return t('chat.minutesAgo', { minutes: diffMins });
  if (diffHours < 24) return t('chat.hoursAgo', { hours: diffHours });
  if (diffDays < 7) return t('chat.daysAgo', { days: diffDays });
  return dateObj.toLocaleDateString(locale === 'vi' ? 'vi-VN' : 'en-US', {
    month: 'short',
    day: 'numeric',
    year: dateObj.getFullYear() !== now.getFullYear() ? 'numeric' : undefined,
  });
}

/**
 * EN: Format date to readable string
 * VI: Format ngày thành chuỗi dễ đọc
 */
function formatDate(date: string | null, t: (key: string) => string, locale: string): string {
  if (!date) return t('settings.security.never');
  return new Date(date).toLocaleDateString(locale === 'vi' ? 'vi-VN' : 'en-US', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
  });
}

/**
 * EN: API Keys management page component
 * VI: Component trang quản lý API Keys
 *
 * Features:
 * - List all API keys
 * - Create new API keys with name and description
 * - Delete API keys
 * - Show/hide API key values
 * - Copy API key to clipboard
 * - Display creation date, last used date, expiration date
 */
export default function ApiKeysPage() {
  // EN: Translation hook / VI: Hook translation
  const t = useTranslations();
  const { locale } = useI18n();

  // EN: Create schema with translations / VI: Tạo schema với translations
  const apiKeySchema = createApiKeySchema(t);
  type CreateApiKeyFormData = z.infer<typeof apiKeySchema>;

  // EN: State management / VI: Quản lý state
  const [apiKeys, setApiKeys] = useState<ApiKey[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [showCreateDialog, setShowCreateDialog] = useState(false);
  const [showNewKeyDialog, setShowNewKeyDialog] = useState(false);
  const [newApiKey, setNewApiKey] = useState<string>('');
  const [newApiKeyName, setNewApiKeyName] = useState<string>('');
  const [visibleKeys, setVisibleKeys] = useState<Set<string>>(new Set());
  const [copiedKeyId, setCopiedKeyId] = useState<string | null>(null);
  const [deletingKeyId, setDeletingKeyId] = useState<string | null>(null);
  const [error, setError] = useState<string>('');
  const [success, setSuccess] = useState<string>('');

  // EN: React Hook Form setup for creating API key / VI: Setup React Hook Form cho tạo API key
  const {
    register,
    handleSubmit,
    watch,
    setValue,
    formState: { errors, isSubmitting },
    reset,
  } = useForm<CreateApiKeyFormData>({
    resolver: zodResolver(apiKeySchema),
    defaultValues: {
      name: '',
      description: '',
    },
  });

  // EN: Load API keys on mount / VI: Tải API keys khi mount
  useEffect(() => {
    loadApiKeys();
  }, []);

  /**
   * EN: Load API keys from API
   * VI: Tải API keys từ API
   */
  const loadApiKeys = async () => {
    setIsLoading(true);
    setError('');
    try {
      // EN: TODO: Replace with actual API call
      // VI: TODO: Thay thế bằng API call thực tế
      // const response = await apiKeysApi.list();
      // if (response.success && response.data) {
      //   setApiKeys(response.data);
      // }

      // EN: Mock data for now / VI: Dữ liệu mock tạm thời
      // In a real implementation, the API would return keys with masked values
      // Trong implementation thực tế, API sẽ trả về keys với giá trị đã được che
      await new Promise((resolve) => setTimeout(resolve, 500));
      setApiKeys([]);
    } catch (err: any) {
      setError(err.message || t('settings.apiKeys.failedToLoad'));
    } finally {
      setIsLoading(false);
    }
  };

  /**
   * EN: Handle create API key form submission
   * VI: Xử lý submit form tạo API key
   */
  const onCreateSubmit = async (data: CreateApiKeyFormData) => {
    setError('');
    setSuccess('');
    try {
      // EN: TODO: Replace with actual API call
      // VI: TODO: Thay thế bằng API call thực tế
      // const response = await apiKeysApi.create({
      //   name: data.name,
      //   description: data.description,
      // });
      // if (response.success && response.data) {
      //   setNewApiKey(response.data.key); // EN: Full key shown only once / VI: Key đầy đủ chỉ hiển thị một lần
      //   setNewApiKeyName(data.name);
      //   setShowCreateDialog(false);
      //   setShowNewKeyDialog(true);
      //   reset();
      //   await loadApiKeys();
      // }

      // EN: Mock implementation / VI: Implementation mock
      await new Promise((resolve) => setTimeout(resolve, 500));
      
      // EN: Generate mock API key / VI: Tạo API key mock
      const mockKey = `gk_${Math.random().toString(36).substring(2, 15)}${Math.random().toString(36).substring(2, 15)}`;
      setNewApiKey(mockKey);
      setNewApiKeyName(data.name);
      setShowCreateDialog(false);
      setShowNewKeyDialog(true);
      reset();

      // EN: Add to list with masked value / VI: Thêm vào danh sách với giá trị đã che
      const newKey: ApiKey = {
        id: `key_${Date.now()}`,
        name: data.name,
        keyPrefix: mockKey.substring(0, 8),
        keySuffix: mockKey.slice(-4),
        createdAt: new Date().toISOString(),
        lastUsedAt: null,
        expiresAt: null,
      };
      setApiKeys((prev) => [newKey, ...prev]);
    } catch (err: any) {
      setError(err.message || t('settings.apiKeys.failedToCreate'));
    }
  };

  /**
   * EN: Handle delete API key
   * VI: Xử lý xóa API key
   */
  const handleDeleteKey = async (keyId: string, keyName: string) => {
    if (!confirm(t('settings.apiKeys.confirmDelete', { name: keyName }))) {
      return;
    }

    setDeletingKeyId(keyId);
    setError('');
    try {
      // EN: TODO: Replace with actual API call
      // VI: TODO: Thay thế bằng API call thực tế
      // const response = await apiKeysApi.delete(keyId);
      // if (response.success) {
      //   setSuccess('API key deleted successfully / API key đã được xóa thành công');
      //   await loadApiKeys();
      // }

      // EN: Mock implementation / VI: Implementation mock
      await new Promise((resolve) => setTimeout(resolve, 500));
      setApiKeys((prev) => prev.filter((key) => key.id !== keyId));
      setSuccess(t('settings.apiKeys.deletedSuccessfully'));
      setTimeout(() => setSuccess(''), 3000);
    } catch (err: any) {
      setError(err.message || t('settings.apiKeys.failedToDelete'));
    } finally {
      setDeletingKeyId(null);
    }
  };

  /**
   * EN: Handle copy API key to clipboard
   * VI: Xử lý sao chép API key vào clipboard
   */
  const handleCopyKey = async (keyId: string, fullKey?: string) => {
    try {
      // EN: If full key is provided (from new key dialog), copy it / VI: Nếu có full key (từ dialog key mới), copy nó
      if (fullKey) {
        await navigator.clipboard.writeText(fullKey);
      } else {
        // EN: In real implementation, fetch full key from API / VI: Trong implementation thực tế, lấy full key từ API
        // const response = await apiKeysApi.getFullKey(keyId);
        // if (response.success && response.data) {
        //   await navigator.clipboard.writeText(response.data.key);
        // }
        
        // EN: For now, show masked key / VI: Tạm thời, hiển thị key đã che
        const key = apiKeys.find((k) => k.id === keyId);
        if (key) {
          await navigator.clipboard.writeText(`${key.keyPrefix}...${key.keySuffix}`);
        }
      }
      
      setCopiedKeyId(keyId);
      setTimeout(() => setCopiedKeyId(null), 2000);
    } catch (err) {
      console.error('Failed to copy to clipboard:', err);
    }
  };

  /**
   * EN: Toggle visibility of API key
   * VI: Bật/tắt hiển thị API key
   */
  const toggleKeyVisibility = (keyId: string) => {
    setVisibleKeys((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(keyId)) {
        newSet.delete(keyId);
      } else {
        newSet.add(keyId);
      }
      return newSet;
    });
  };

  return (
    <div className="space-y-6">
      {/* EN: Page header / VI: Header trang */}
      <div>
        <h2 className="text-2xl font-semibold text-text-primary">
          {t('settings.apiKeys.title')}
        </h2>
        <p className="mt-1 text-sm text-text-tertiary">
          {t('settings.apiKeys.manageKeys')}
        </p>
      </div>

      {/* EN: Success message / VI: Thông báo thành công */}
      {success && (
        <div className="rounded-lg bg-accent-success/10 border border-accent-success p-3 flex items-center gap-2 text-sm text-accent-success">
          <CheckCircle2 className="h-4 w-4 flex-shrink-0" />
          <span>{success}</span>
        </div>
      )}

      {/* EN: Error message / VI: Thông báo lỗi */}
      {error && (
        <div className="rounded-lg bg-accent-error/10 border border-accent-error p-3 flex items-center gap-2 text-sm text-accent-error">
          <AlertCircle className="h-4 w-4 flex-shrink-0" />
          <span>{error}</span>
        </div>
      )}

      {/* EN: API Keys list card / VI: Card danh sách API Keys */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="flex items-center gap-2">
                <Key className="h-5 w-5 text-accent-primary" />
                {t('settings.apiKeys.yourApiKeys')}
              </CardTitle>
              <CardDescription className="mt-1">
                {t('settings.apiKeys.createAndManage')}
              </CardDescription>
            </div>
            <Button
              variant="primary"
              onClick={() => setShowCreateDialog(true)}
              className="flex items-center gap-2"
            >
              <Plus className="h-4 w-4" />
              {t('settings.apiKeys.createApiKey')}
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="text-center py-12 text-text-tertiary">
              <div className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-solid border-accent-primary border-r-transparent mb-4"></div>
              <p>{t('common.loading')}</p>
            </div>
          ) : apiKeys.length === 0 ? (
            <div className="text-center py-12">
              <Key className="h-12 w-12 text-text-tertiary mx-auto mb-4" />
              <p className="text-text-secondary font-medium mb-2">
                {t('settings.apiKeys.noApiKeys')}
              </p>
              <p className="text-sm text-text-tertiary mb-6">
                {t('settings.apiKeys.createFirstKey')}
              </p>
              <Button
                variant="primary"
                onClick={() => setShowCreateDialog(true)}
                className="flex items-center gap-2"
              >
                <Plus className="h-4 w-4" />
                {t('settings.apiKeys.createApiKey')}
              </Button>
            </div>
          ) : (
            <div className="space-y-3">
              {apiKeys.map((apiKey) => (
                <div
                  key={apiKey.id}
                  className="flex items-center justify-between p-4 rounded-lg bg-bg-tertiary border border-border-primary hover:border-border-secondary transition-colors"
                >
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-3 mb-2">
                      <h3 className="text-sm font-semibold text-text-primary">
                        {apiKey.name}
                      </h3>
                    </div>
                    <div className="flex items-center gap-2 mb-2">
                      {/* EN: API Key display / VI: Hiển thị API Key */}
                      <code className="text-sm font-mono bg-bg-primary px-2 py-1 rounded border border-border-primary text-text-secondary">
                        {visibleKeys.has(apiKey.id)
                          ? `${apiKey.keyPrefix}...${apiKey.keySuffix}`
                          : `${apiKey.keyPrefix}${'•'.repeat(20)}${apiKey.keySuffix}`}
                      </code>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => toggleKeyVisibility(apiKey.id)}
                        className="h-7 w-7 p-0"
                        aria-label={visibleKeys.has(apiKey.id) ? t('settings.apiKeys.hide') : t('settings.apiKeys.show')}
                      >
                        {visibleKeys.has(apiKey.id) ? (
                          <EyeOff className="h-4 w-4 text-text-tertiary" />
                        ) : (
                          <Eye className="h-4 w-4 text-text-tertiary" />
                        )}
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleCopyKey(apiKey.id)}
                        className="h-7 w-7 p-0"
                        aria-label={t('settings.apiKeys.copy')}
                      >
                        {copiedKeyId === apiKey.id ? (
                          <Check className="h-4 w-4 text-accent-success" />
                        ) : (
                          <Copy className="h-4 w-4 text-text-tertiary" />
                        )}
                      </Button>
                    </div>
                    <div className="flex items-center gap-4 text-xs text-text-tertiary">
                      <span>
                        {t('settings.apiKeys.created')}: {formatDate(apiKey.createdAt, t, locale)}
                      </span>
                      {apiKey.lastUsedAt && (
                        <span>
                          {t('settings.apiKeys.lastUsed')}: {formatRelativeTime(apiKey.lastUsedAt, t, locale)}
                        </span>
                      )}
                      {apiKey.expiresAt && (
                        <span className={new Date(apiKey.expiresAt) < new Date() ? 'text-accent-error' : ''}>
                          {t('settings.apiKeys.expires')}: {formatDate(apiKey.expiresAt, t, locale)}
                        </span>
                      )}
                    </div>
                  </div>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => handleDeleteKey(apiKey.id, apiKey.name)}
                    isLoading={deletingKeyId === apiKey.id}
                    className="text-accent-error hover:brightness-110 hover:bg-accent-error/10 ml-4"
                    aria-label={`${t('settings.apiKeys.delete')} ${apiKey.name}`}
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* EN: Security notice card / VI: Card thông báo bảo mật */}
      <Card hover={false} bordered>
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-base">
            <AlertCircle className="h-5 w-5 text-accent-warning" />
            {t('settings.apiKeys.securityBestPractices', { defaultValue: 'Security Best Practices' })}
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-2 text-sm text-text-secondary">
          <ul className="list-disc list-inside space-y-1 ml-2">
            <li>{t('settings.apiKeys.practice1', { defaultValue: 'Keep your API keys secure and never share them publicly' })}</li>
            <li>{t('settings.apiKeys.practice2', { defaultValue: 'Use environment variables or secure secret management tools' })}</li>
            <li>{t('settings.apiKeys.practice3', { defaultValue: 'Rotate your API keys regularly' })}</li>
            <li>{t('settings.apiKeys.practice4', { defaultValue: 'Delete unused API keys immediately' })}</li>
            <li>{t('settings.apiKeys.practice5', { defaultValue: 'If a key is compromised, revoke it immediately and create a new one' })}</li>
          </ul>
        </CardContent>
      </Card>

      {/* EN: Create API Key Dialog / VI: Dialog tạo API Key */}
      <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>{t('settings.apiKeys.createApiKey')}</DialogTitle>
            <DialogDescription>
              {t('settings.apiKeys.createForAccess', { defaultValue: 'Create a new API key for programmatic access' })}
            </DialogDescription>
          </DialogHeader>

          <form onSubmit={handleSubmit(onCreateSubmit)} className="space-y-4">
            {/* EN: Error message / VI: Thông báo lỗi */}
            {error && (
              <div className="p-3 rounded-md bg-bg-tertiary border border-accent-error text-accent-error text-sm flex items-center gap-2">
                <AlertCircle className="h-4 w-4 flex-shrink-0" />
                <span>{error}</span>
              </div>
            )}

            <Input
              label={t('settings.apiKeys.name')}
              placeholder={t('settings.apiKeys.namePlaceholder', { defaultValue: 'e.g., Production Key, Development Key' })}
              name="name"
              value={watch('name')}
              onChange={(value) => setValue('name', value)}
              onBlur={register('name').onBlur}
              errorMessage={errors.name?.message}
              isInvalid={!!errors.name}
              autoFocus
            />

            <div>
              <label
                htmlFor="description"
                className="block text-sm font-medium text-text-secondary mb-2"
              >
                {t('settings.apiKeys.description')} ({t('common.optional', { defaultValue: 'Optional' })})
              </label>
              <textarea
                id="description"
                rows={3}
                placeholder={t('settings.apiKeys.descriptionPlaceholder', { defaultValue: 'Optional description for this API key' })}
                {...register('description')}
                className="flex w-full rounded-md border border-border-primary bg-bg-secondary px-3 py-2 text-base text-text-primary placeholder:text-text-tertiary transition-all duration-[150ms] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:border-accent-primary focus-visible:ring-accent-primary focus-visible:shadow-[0_0_20px_rgba(59,130,246,0.3)] disabled:cursor-not-allowed disabled:opacity-50 disabled:bg-bg-tertiary"
              />
              {errors.description && (
                <p className="mt-1.5 text-sm text-accent-error flex items-center gap-1">
                  <AlertCircle className="h-4 w-4" />
                  {errors.description.message}
                </p>
              )}
            </div>

            <DialogFooter>
              <Button
                type="button"
                variant="secondary"
                onClick={() => {
                  setShowCreateDialog(false);
                  reset();
                  setError('');
                }}
              >
                {t('common.cancel')}
              </Button>
              <Button type="submit" isLoading={isSubmitting}>
                {t('settings.apiKeys.createApiKey')}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      {/* EN: New API Key Dialog (shown once after creation) / VI: Dialog API Key mới (hiển thị một lần sau khi tạo) */}
      <Dialog open={showNewKeyDialog} onOpenChange={setShowNewKeyDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <CheckCircle2 className="h-5 w-5 text-accent-success" />
              {t('settings.apiKeys.newApiKeyCreated')}
            </DialogTitle>
            <DialogDescription>
              {t('settings.apiKeys.newKeyFor', { name: newApiKeyName, defaultValue: `Your new API key for "${newApiKeyName}"` })}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {/* EN: Warning message / VI: Thông báo cảnh báo */}
            <div className="p-3 rounded-md bg-accent-warning/10 border border-accent-warning text-accent-warning text-sm">
              <p className="font-medium mb-1">
                {t('settings.apiKeys.important', { defaultValue: 'Important' })}
              </p>
              <p>
                {t('settings.apiKeys.saveKeySecurely')}
              </p>
            </div>

            {/* EN: API Key display / VI: Hiển thị API Key */}
            <div className="p-4 rounded-lg bg-bg-primary border border-border-primary">
              <code className="text-sm font-mono text-text-primary break-all select-all">
                {newApiKey}
              </code>
            </div>

            {/* EN: Copy button / VI: Nút sao chép */}
            <Button
              variant="primary"
              onClick={() => handleCopyKey('new', newApiKey)}
              className="w-full flex items-center justify-center gap-2"
            >
              {copiedKeyId === 'new' ? (
                <>
                  <Check className="h-4 w-4" />
                  Copied! / Đã sao chép!
                </>
              ) : (
                <>
                  <Copy className="h-4 w-4" />
                  {t('settings.apiKeys.copyApiKey', { defaultValue: 'Copy API Key' })}
                </>
              )}
            </Button>
          </div>

          <DialogFooter>
            <Button
              variant="primary"
              onClick={() => {
                setShowNewKeyDialog(false);
                setNewApiKey('');
                setNewApiKeyName('');
              }}
              className="w-full"
            >
              {t('settings.apiKeys.iveCopied', { defaultValue: 'I\'ve copied the key' })}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}