'use client';

import { useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useRouter, useParams } from 'next/navigation';
import { apiClient } from '@/infrastructure/api/api-client';
import { queryKeys } from '@/infrastructure/api/query-keys';
import { cn } from '@/lib/utils';

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

interface SkillDetail {
  name: string;
  description: string;
  promptTemplate: string;
  allowedTools: string[];
  isBuiltIn: boolean;
  enabled: boolean;
  createdAt: string;
  updatedAt: string;
}

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

const AVAILABLE_TOOLS = [
  'Bash',
  'Read',
  'Write',
  'Glob',
  'Grep',
  'Edit',
  'ssh',
  'kubectl',
  'docker',
  'systemctl',
  'curl',
  'ping',
  'scp',
  'rsync',
  'git',
  'npm',
];

// ---------------------------------------------------------------------------
// Toggle switch
// ---------------------------------------------------------------------------

function ToggleSwitch({
  checked,
  disabled,
  onChange,
  label,
}: {
  checked: boolean;
  disabled?: boolean;
  onChange: (value: boolean) => void;
  label: string;
}) {
  return (
    <button
      type="button"
      onClick={() => onChange(!checked)}
      disabled={disabled}
      className="flex items-center gap-2"
      title={label}
    >
      <span
        className={cn(
          'relative inline-flex h-5 w-9 items-center rounded-full transition-colors',
          checked ? 'bg-primary' : 'bg-muted',
          disabled && 'opacity-50 cursor-not-allowed',
        )}
      >
        <span
          className={cn(
            'inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform',
            checked ? 'translate-x-[18px]' : 'translate-x-[3px]',
          )}
        />
      </span>
      <span className="text-sm">{label}</span>
    </button>
  );
}

// ---------------------------------------------------------------------------
// Delete confirmation dialog
// ---------------------------------------------------------------------------

function DeleteDialog({
  open,
  name,
  deleting,
  onClose,
  onConfirm,
}: {
  open: boolean;
  name: string;
  deleting: boolean;
  onClose: () => void;
  onConfirm: () => void;
}) {
  const { t } = useTranslation('agent-config');
  const { t: tc } = useTranslation('common');

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      <div className="relative z-10 w-full max-w-sm bg-card border rounded-lg shadow-lg p-6 mx-4">
        <h2 className="text-lg font-semibold mb-2">{t('skills.detail.deleteSkill')}</h2>
        <p className="text-sm text-muted-foreground mb-6">
          {tc('confirmDelete')} <strong>{name}</strong>
        </p>
        <div className="flex justify-end gap-3">
          <button
            onClick={onClose}
            className="px-4 py-2 text-sm rounded-md border border-input hover:bg-accent"
            disabled={deleting}
          >
            {tc('cancel')}
          </button>
          <button
            onClick={onConfirm}
            disabled={deleting}
            className="px-4 py-2 text-sm rounded-md bg-destructive text-destructive-foreground hover:bg-destructive/90 disabled:opacity-50"
          >
            {deleting ? tc('deleting') : tc('delete')}
          </button>
        </div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Helper: format date
// ---------------------------------------------------------------------------

function formatDate(dateStr: string): string {
  try {
    return new Date(dateStr).toLocaleString();
  } catch {
    return dateStr;
  }
}

// ---------------------------------------------------------------------------
// Main page component
// ---------------------------------------------------------------------------

export default function SkillDetailPage() {
  const { t } = useTranslation('agent-config');
  const { t: tc } = useTranslation('common');
  const router = useRouter();
  const params = useParams();
  const queryClient = useQueryClient();
  const name = params.name as string;
  const decodedName = decodeURIComponent(name);

  // State ----------------------------------------------------------------
  const [isEditingPrompt, setIsEditingPrompt] = useState(false);
  const [promptDraft, setPromptDraft] = useState('');
  const [isEditingTools, setIsEditingTools] = useState(false);
  const [toolsDraft, setToolsDraft] = useState<string[]>([]);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);

  // Queries --------------------------------------------------------------
  const {
    data: skill,
    isLoading,
    error,
  } = useQuery<SkillDetail>({
    queryKey: queryKeys.skills.detail(decodedName),
    queryFn: () => apiClient<SkillDetail>(`/api/v1/agent/skills/${encodeURIComponent(decodedName)}`),
    enabled: !!decodedName,
  });

  // Mutations ------------------------------------------------------------
  const updateMutation = useMutation({
    mutationFn: (body: Partial<SkillDetail>) =>
      apiClient<SkillDetail>(`/api/v1/agent/skills/${encodeURIComponent(decodedName)}`, {
        method: 'PUT',
        body,
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.skills.detail(decodedName) });
      queryClient.invalidateQueries({ queryKey: queryKeys.skills.all });
    },
  });

  const deleteMutation = useMutation({
    mutationFn: () =>
      apiClient<void>(`/api/v1/agent/skills/${encodeURIComponent(decodedName)}`, {
        method: 'DELETE',
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: queryKeys.skills.all });
      router.push('/agent-config/skills');
    },
  });

  const duplicateMutation = useMutation({
    mutationFn: () => {
      if (!skill) throw new Error('Skill not loaded');
      return apiClient<SkillDetail>('/api/v1/agent/skills', {
        method: 'POST',
        body: {
          name: `${skill.name} (Copy)`,
          description: skill.description,
          promptTemplate: skill.promptTemplate,
          allowedTools: skill.allowedTools,
          enabled: false,
        },
      });
    },
    onSuccess: (newSkill) => {
      queryClient.invalidateQueries({ queryKey: queryKeys.skills.all });
      router.push(`/agent-config/skills/${encodeURIComponent(newSkill.name)}`);
    },
  });

  // Handlers ---------------------------------------------------------------
  const handleStartEditPrompt = useCallback(() => {
    if (!skill) return;
    setPromptDraft(skill.promptTemplate);
    setIsEditingPrompt(true);
  }, [skill]);

  const handleSavePrompt = useCallback(() => {
    updateMutation.mutate(
      { promptTemplate: promptDraft },
      {
        onSuccess: () => {
          setIsEditingPrompt(false);
        },
      },
    );
  }, [promptDraft, updateMutation]);

  const handleCancelEditPrompt = useCallback(() => {
    setIsEditingPrompt(false);
    setPromptDraft('');
  }, []);

  const handleStartEditTools = useCallback(() => {
    if (!skill) return;
    setToolsDraft([...skill.allowedTools]);
    setIsEditingTools(true);
  }, [skill]);

  const handleToggleTool = useCallback((tool: string) => {
    setToolsDraft((prev) =>
      prev.includes(tool) ? prev.filter((t) => t !== tool) : [...prev, tool],
    );
  }, []);

  const handleSaveTools = useCallback(() => {
    updateMutation.mutate(
      { allowedTools: toolsDraft },
      {
        onSuccess: () => {
          setIsEditingTools(false);
        },
      },
    );
  }, [toolsDraft, updateMutation]);

  const handleCancelEditTools = useCallback(() => {
    setIsEditingTools(false);
    setToolsDraft([]);
  }, []);

  const handleToggleEnabled = useCallback(
    (value: boolean) => {
      updateMutation.mutate({ enabled: value });
    },
    [updateMutation],
  );

  // Render: Loading --------------------------------------------------------
  if (isLoading) {
    return (
      <div>
        <button
          onClick={() => router.push('/agent-config/skills')}
          className="text-sm text-muted-foreground hover:text-foreground mb-4 inline-flex items-center gap-1"
        >
          &larr; {t('skills.detail.backToSkills')}
        </button>
        <div className="text-sm text-muted-foreground py-12 text-center">
          {t('skills.detail.loading')}
        </div>
      </div>
    );
  }

  // Render: Error ----------------------------------------------------------
  if (error) {
    return (
      <div>
        <button
          onClick={() => router.push('/agent-config/skills')}
          className="text-sm text-muted-foreground hover:text-foreground mb-4 inline-flex items-center gap-1"
        >
          &larr; {t('skills.detail.backToSkills')}
        </button>
        <div className="p-4 rounded-md border border-destructive/50 bg-destructive/10 text-destructive text-sm">
          {t('skills.loadError')} {(error as Error).message}
        </div>
      </div>
    );
  }

  // Render: Not found ------------------------------------------------------
  if (!skill) {
    return (
      <div>
        <button
          onClick={() => router.push('/agent-config/skills')}
          className="text-sm text-muted-foreground hover:text-foreground mb-4 inline-flex items-center gap-1"
        >
          &larr; {t('skills.detail.backToSkills')}
        </button>
        <div className="text-sm text-muted-foreground py-12 text-center">
          {t('skills.detail.notFound')}
        </div>
      </div>
    );
  }

  // Render: Main -----------------------------------------------------------
  return (
    <div>
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <div className="flex items-center gap-3">
          <button
            onClick={() => router.push('/agent-config/skills')}
            className="text-sm text-muted-foreground hover:text-foreground inline-flex items-center gap-1"
          >
            &larr; {tc('back')}
          </button>
          <div className="h-6 w-px bg-border" />
          <div>
            <h1 className="text-2xl font-bold">{skill.name}</h1>
            <p className="text-sm text-muted-foreground mt-0.5">
              {skill.description || tc('noData')}
            </p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          {skill.isBuiltIn && (
            <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400">
              {t('skills.detail.builtIn')}
            </span>
          )}
          <span
            className={cn(
              'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium',
              skill.enabled
                ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400'
                : 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300',
            )}
          >
            {skill.enabled ? t('skills.detail.enabled') : t('skills.detail.disabled')}
          </span>
        </div>
      </div>

      {/* Mutation error banner */}
      {(updateMutation.error || duplicateMutation.error) && (
        <div className="p-4 mb-4 rounded-md border border-destructive/50 bg-destructive/10 text-destructive text-sm">
          {((updateMutation.error || duplicateMutation.error) as Error).message}
        </div>
      )}

      {/* Two-column layout */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left column */}
        <div className="lg:col-span-2 space-y-6">
          {/* Overview card */}
          <div className="border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">{t('skills.detail.overview')}</h2>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
                  {tc('name')}
                </label>
                <p className="text-sm mt-1 font-mono">{skill.name}</p>
              </div>
              <div>
                <label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
                  {tc('type')}
                </label>
                <p className="mt-1">
                  {skill.isBuiltIn ? (
                    <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400">
                      Built-in
                    </span>
                  ) : (
                    <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300">
                      {t('skills.detail.custom')}
                    </span>
                  )}
                </p>
              </div>
              <div className="sm:col-span-2">
                <label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
                  {tc('description')}
                </label>
                <p className="text-sm mt-1 text-muted-foreground">
                  {skill.description || tc('noData')}
                </p>
              </div>
              <div>
                <label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
                  {tc('created')}
                </label>
                <p className="text-sm mt-1 text-muted-foreground">
                  {formatDate(skill.createdAt)}
                </p>
              </div>
              <div>
                <label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
                  {tc('updated')}
                </label>
                <p className="text-sm mt-1 text-muted-foreground">
                  {formatDate(skill.updatedAt)}
                </p>
              </div>
            </div>
          </div>

          {/* Prompt Template section */}
          <div className="border rounded-lg p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold">{t('skills.detail.promptTemplate')}</h2>
              <div className="flex items-center gap-2">
                {isEditingPrompt ? (
                  <>
                    <button
                      onClick={handleCancelEditPrompt}
                      className="px-3 py-1.5 text-xs rounded-md border border-input hover:bg-accent transition-colors"
                    >
                      {tc('cancel')}
                    </button>
                    <button
                      onClick={handleSavePrompt}
                      disabled={updateMutation.isPending}
                      className="px-3 py-1.5 text-xs rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors"
                    >
                      {updateMutation.isPending ? tc('saving') : tc('save')}
                    </button>
                  </>
                ) : (
                  <button
                    onClick={handleStartEditPrompt}
                    className="px-3 py-1.5 text-xs rounded-md border border-input hover:bg-accent transition-colors"
                  >
                    {tc('edit')}
                  </button>
                )}
              </div>
            </div>

            {isEditingPrompt ? (
              <textarea
                value={promptDraft}
                onChange={(e) => setPromptDraft(e.target.value)}
                className="w-full bg-gray-950 text-green-400 font-mono text-sm p-4 rounded-md min-h-[300px] resize-y border-0 focus:outline-none focus:ring-2 focus:ring-ring"
                spellCheck={false}
              />
            ) : (
              <div className="bg-gray-950 text-gray-200 font-mono text-sm p-4 rounded-md whitespace-pre-wrap min-h-[300px]">
                {skill.promptTemplate || t('skills.detail.noPrompt')}
              </div>
            )}
          </div>

          {/* Allowed Tools section */}
          <div className="border rounded-lg p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold">{t('skills.detail.allowedTools')}</h2>
              <div className="flex items-center gap-2">
                {isEditingTools ? (
                  <>
                    <button
                      onClick={handleCancelEditTools}
                      className="px-3 py-1.5 text-xs rounded-md border border-input hover:bg-accent transition-colors"
                    >
                      {tc('cancel')}
                    </button>
                    <button
                      onClick={handleSaveTools}
                      disabled={updateMutation.isPending}
                      className="px-3 py-1.5 text-xs rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors"
                    >
                      {updateMutation.isPending ? tc('saving') : tc('save')}
                    </button>
                  </>
                ) : (
                  <button
                    onClick={handleStartEditTools}
                    className="px-3 py-1.5 text-xs rounded-md border border-input hover:bg-accent transition-colors"
                  >
                    {tc('edit')}
                  </button>
                )}
              </div>
            </div>

            {isEditingTools ? (
              <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
                {AVAILABLE_TOOLS.map((tool) => (
                  <label
                    key={tool}
                    className="flex items-center gap-2 text-sm cursor-pointer"
                  >
                    <input
                      type="checkbox"
                      checked={toolsDraft.includes(tool)}
                      onChange={() => handleToggleTool(tool)}
                      className="accent-primary h-4 w-4"
                    />
                    <span className="font-mono text-xs">{tool}</span>
                  </label>
                ))}
              </div>
            ) : (
              <div className="flex flex-wrap gap-2">
                {skill.allowedTools.length === 0 ? (
                  <p className="text-sm text-muted-foreground">
                    {t('skills.detail.noTools')}
                  </p>
                ) : (
                  skill.allowedTools.map((tool) => (
                    <span
                      key={tool}
                      className="inline-flex items-center px-2.5 py-1 rounded-md bg-muted text-xs font-mono"
                    >
                      {tool}
                    </span>
                  ))
                )}
              </div>
            )}
          </div>
        </div>

        {/* Right column */}
        <div className="lg:col-span-1 space-y-6">
          {/* Configuration card */}
          <div className="border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">{t('skills.detail.configuration')}</h2>
            <div className="space-y-5">
              {/* Type */}
              <div>
                <label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
                  {tc('type')}
                </label>
                <p className="mt-1.5">
                  {skill.isBuiltIn ? (
                    <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400">
                      Built-in
                    </span>
                  ) : (
                    <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300">
                      {t('skills.detail.custom')}
                    </span>
                  )}
                </p>
              </div>

              {/* Enabled toggle */}
              <div>
                <label className="text-xs font-medium text-muted-foreground uppercase tracking-wide block mb-1.5">
                  {tc('status')}
                </label>
                <ToggleSwitch
                  checked={skill.enabled}
                  disabled={updateMutation.isPending}
                  onChange={handleToggleEnabled}
                  label={skill.enabled ? tc('enabled') : tc('disabled')}
                />
              </div>

              {/* Allowed Tools count */}
              <div>
                <label className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
                  {t('skills.detail.allowedTools')}
                </label>
                <p className="text-sm mt-1 font-medium">
                  {skill.allowedTools.length} tool{skill.allowedTools.length !== 1 ? 's' : ''} configured
                </p>
              </div>
            </div>
          </div>

          {/* Quick Actions card */}
          <div className="border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">{t('skills.detail.quickActions')}</h2>
            <div className="space-y-3">
              {/* Duplicate */}
              <button
                onClick={() => duplicateMutation.mutate()}
                disabled={duplicateMutation.isPending}
                className="w-full px-4 py-2 text-sm rounded-md border border-input hover:bg-accent font-medium transition-colors disabled:opacity-50"
              >
                {duplicateMutation.isPending ? tc('loading') : t('skills.detail.duplicateSkill')}
              </button>

              {/* Delete (only for non-built-in) */}
              {!skill.isBuiltIn && (
                <button
                  onClick={() => setShowDeleteDialog(true)}
                  disabled={deleteMutation.isPending}
                  className="w-full px-4 py-2 text-sm rounded-md border border-destructive/50 text-destructive hover:bg-destructive/10 font-medium transition-colors disabled:opacity-50"
                >
                  {t('skills.detail.deleteSkill')}
                </button>
              )}

              {skill.isBuiltIn && (
                <p className="text-xs text-muted-foreground">
                  {t('skills.detail.builtIn')}
                </p>
              )}
            </div>
          </div>

          {/* Metadata */}
          <div className="border rounded-lg p-6">
            <h2 className="text-lg font-semibold mb-4">{t('skills.detail.metadata')}</h2>
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{tc('name')}</span>
                <code className="text-xs font-mono text-muted-foreground bg-muted px-1.5 py-0.5 rounded">
                  {skill.name}
                </code>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{tc('created')}</span>
                <span className="text-xs text-muted-foreground">
                  {formatDate(skill.createdAt)}
                </span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">{tc('updated')}</span>
                <span className="text-xs text-muted-foreground">
                  {formatDate(skill.updatedAt)}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Delete confirmation dialog */}
      <DeleteDialog
        open={showDeleteDialog}
        name={skill.name}
        deleting={deleteMutation.isPending}
        onClose={() => setShowDeleteDialog(false)}
        onConfirm={() => deleteMutation.mutate()}
      />
    </div>
  );
}
