'use client';

import { useState, useEffect, useCallback } from 'react';
import { Box, Group, Text, Button, Stack } from '@tidbcloud/uikit';
import { fetchWithAuth } from '@/lib/auth';
import { useTranslation } from '@/lib/i18n';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL ?? '';

interface FeedbackBannerProps {
  workspaceId: string;
  readOnly: boolean;
  onFailureFeedback: (reason: string) => void;
  onDismiss?: () => void;
  refreshToken?: number;
}

type Rating = 'success' | 'failure' | null;

interface FeedbackState {
  rating: Rating;
  failure_reason: string | null;
  loaded: boolean;
}

export default function FeedbackBanner({ workspaceId, readOnly, onFailureFeedback, onDismiss, refreshToken = 0 }: FeedbackBannerProps) {
  const { t } = useTranslation();
  const [state, setState] = useState<FeedbackState>({ rating: null, failure_reason: null, loaded: false });
  const [reasonInput, setReasonInput] = useState('');
  const [saving, setSaving] = useState(false);
  const [showReasonInput, setShowReasonInput] = useState(false);

  // Load existing feedback on mount
  useEffect(() => {
    let cancelled = false;
    fetchWithAuth(`${API_BASE_URL}/api/workspace/${encodeURIComponent(workspaceId)}/feedback`)
      .then(res => res.ok ? res.json() : null)
      .then(data => {
        if (cancelled || !data?.feedback) return;
        setState({
          rating: data.feedback.rating,
          failure_reason: data.feedback.failure_reason,
          loaded: true,
        });
        if (data.feedback.rating === 'failure' && data.feedback.failure_reason) {
          setReasonInput(data.feedback.failure_reason);
        }
      })
      .catch(() => {})
      .finally(() => {
        if (!cancelled) setState(prev => ({ ...prev, loaded: true }));
      });
    return () => { cancelled = true; };
  }, [workspaceId, refreshToken]);

  const saveFeedback = useCallback(async (rating: Rating, failure_reason: string | null) => {
    if (!rating) return;
    setSaving(true);
    try {
      await fetchWithAuth(`${API_BASE_URL}/api/workspace/${encodeURIComponent(workspaceId)}/feedback`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ rating, failure_reason }),
      });
      setState({ rating, failure_reason, loaded: true });
    } catch {
      // best-effort
    } finally {
      setSaving(false);
    }
  }, [workspaceId]);

  const handleSuccess = () => {
    saveFeedback('success', null);
    setShowReasonInput(false);
  };

  const handleFailure = () => {
    setShowReasonInput(true);
    // Save the failure rating immediately (reason can come later)
    saveFeedback('failure', state.failure_reason);
  };

  const handleSubmitReason = () => {
    const reason = reasonInput.trim();
    if (!reason) return;
    saveFeedback('failure', reason);
    onFailureFeedback(reason);
    setShowReasonInput(false);
  };

  const handleChange = () => {
    setState({ rating: null, failure_reason: null, loaded: true });
    setShowReasonInput(false);
    setReasonInput('');
  };

  if (!state.loaded || readOnly) return null;

  // Success state
  if (state.rating === 'success') {
    return (
      <Box
        px="lg"
        py="sm"
        style={{
          borderTop: '1px solid #d1fae5',
          backgroundColor: '#f0fdf4',
          flexShrink: 0,
        }}
      >
        <Group justify="space-between" align="center">
          <Text size="sm" c="teal.7" fw={500}>
            {t('chat.fb.markedResolved')}
          </Text>
          <Button
            variant="subtle"
            color="gray"
            size="compact-xs"
            onClick={handleChange}
          >
            {t('chat.fb.change')}
          </Button>
        </Group>
      </Box>
    );
  }

  // Failure submitted state (reason already submitted)
  if (state.rating === 'failure' && state.failure_reason && !showReasonInput) {
    return (
      <Box
        px="lg"
        py="sm"
        style={{
          borderTop: '1px solid #fecaca',
          backgroundColor: '#fef2f2',
          flexShrink: 0,
        }}
      >
        <Group justify="space-between" align="center">
          <Text size="sm" c="red.7" fw={500}>
            {t('chat.fb.markedNotResolved')}
          </Text>
          <Group gap="xs">
            <Button
              variant="subtle"
              color="gray"
              size="compact-xs"
              onClick={() => setShowReasonInput(true)}
            >
              {t('chat.fb.update')}
            </Button>
            <Button
              variant="subtle"
              color="gray"
              size="compact-xs"
              onClick={handleChange}
            >
              {t('chat.fb.change')}
            </Button>
          </Group>
        </Group>
      </Box>
    );
  }

  // Failure reason input state
  if (showReasonInput || (state.rating === 'failure' && !state.failure_reason)) {
    return (
      <Box
        px="lg"
        py="sm"
        style={{
          borderTop: '1px solid #fecaca',
          backgroundColor: '#fef2f2',
          flexShrink: 0,
        }}
      >
        <Stack gap="xs">
          <Text size="sm" c="red.7" fw={500}>
            {t('chat.fb.prompt')}
          </Text>
          <textarea
            value={reasonInput}
            onChange={(e) => setReasonInput(e.target.value)}
            placeholder={t('chat.fb.placeholder')}
            rows={2}
            style={{
              width: '100%',
              padding: '8px 12px',
              border: '1px solid #fca5a5',
              borderRadius: '6px',
              fontSize: '13px',
              resize: 'none',
              fontFamily: 'inherit',
              outline: 'none',
              backgroundColor: '#fff',
            }}
          />
          <Group gap="xs" justify="flex-end">
            <Button
              variant="subtle"
              color="gray"
              size="compact-xs"
              onClick={handleChange}
            >
              {t('chat.fb.cancel')}
            </Button>
            <Button
              size="compact-sm"
              color="red"
              disabled={!reasonInput.trim() || saving}
              loading={saving}
              onClick={handleSubmitReason}
            >
              {t('chat.fb.submit')}
            </Button>
          </Group>
        </Stack>
      </Box>
    );
  }

  // Initial ask state — brief highlight animation to draw attention
  return (
    <Box
      px="lg"
      py="sm"
      style={{
        borderTop: '1px solid #e5e7eb',
        backgroundColor: '#fefce8',
        flexShrink: 0,
        animation: 'feedbackHighlight 2s ease-out',
      }}
    >
      <style>{`
        @keyframes feedbackHighlight {
          0% { background-color: #fde047; }
          100% { background-color: #fefce8; }
        }
      `}</style>
      <Group justify="space-between" align="center">
        <Text size="sm" fw={500} c="yellow.9">
          {t('chat.fb.ask')}
        </Text>
        <Group gap="xs">
          <Button
            variant="light"
            color="teal"
            size="compact-sm"
            onClick={handleSuccess}
            disabled={saving}
          >
            {t('chat.fb.resolved')}
          </Button>
          <Button
            variant="light"
            color="red"
            size="compact-sm"
            onClick={handleFailure}
            disabled={saving}
          >
            {t('chat.fb.notResolved')}
          </Button>
          {onDismiss && (
            <Button
              variant="subtle"
              color="gray"
              size="compact-xs"
              onClick={onDismiss}
              style={{ padding: '0 4px', minWidth: 'auto' }}
            >
              ✕
            </Button>
          )}
        </Group>
      </Group>
    </Box>
  );
}
