import { useCallback, useState } from 'react';
import {
  Alert,
  StyleSheet,
  Text,
  TextInput,
  View,
} from 'react-native';
import * as DocumentPicker from 'expo-document-picker';
import { ScreenLayout } from '../../components/ui/ScreenLayout';
import { AppButton } from '../../components/ui/AppButton';
import { MatchedAnswerCard } from '../../components/askDrAi/MatchedAnswerCard';
import { UploadedFileAnalysisCard } from '../../components/askDrAi/UploadedFileAnalysisCard';
import { askDrAi, AskDrAiAnswer, UploadedFileContextItem } from '../../services/askDrAi';
import { uploadFiles } from '../../services/uploads';
import { colors, spacing } from '../../constants/theme';

export function AskDrAiScreen() {
  const [question, setQuestion] = useState('');
  const [symptomInput, setSymptomInput] = useState('');
  const [symptoms, setSymptoms] = useState<string[]>([]);
  const [uploadedUrls, setUploadedUrls] = useState<string[]>([]);
  const [uploadedNames, setUploadedNames] = useState<string[]>([]);
  const [uploading, setUploading] = useState(false);
  const [showSymptomInput, setShowSymptomInput] = useState(false);
  const [loading, setLoading] = useState(false);
  const [answers, setAnswers] = useState<AskDrAiAnswer[]>([]);
  const [uploadedFileContext, setUploadedFileContext] = useState<UploadedFileContextItem[]>([]);

  const appendSymptom = useCallback(() => {
    const value = symptomInput.trim();
    if (!value) return;
    setSymptoms((prev) => [...prev, value]);
    setSymptomInput('');
  }, [symptomInput]);

  const removeSymptom = useCallback((index: number) => {
    setSymptoms((prev) => prev.filter((_, i) => i !== index));
  }, []);

  const pickFiles = useCallback(async () => {
    try {
      const result = await DocumentPicker.getDocumentAsync({
        multiple: true,
        copyToCacheDirectory: true,
        type: [
          'application/pdf',
          'image/*',
          'text/plain',
          'text/csv',
          'application/msword',
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          'application/vnd.ms-excel',
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        ],
      });

      if (result.canceled || !result.assets?.length) {
        return;
      }

      setUploading(true);
      const payload = result.assets.map((asset) => ({
        uri: asset.uri,
        name: asset.name || 'upload.bin',
        mimeType: asset.mimeType,
      }));
      const { urls, files } = await uploadFiles(payload);
      setUploadedUrls((prev) => [...prev, ...urls]);
      setUploadedNames((prev) => [
        ...prev,
        ...files.map((f) => f.original_filename || f.filename || 'file'),
      ]);
    } catch {
      Alert.alert('Upload', 'Unable to upload files. Check your connection and try again.');
    } finally {
      setUploading(false);
    }
  }, []);

  const removeUploaded = useCallback((index: number) => {
    setUploadedUrls((prev) => prev.filter((_, i) => i !== index));
    setUploadedNames((prev) => prev.filter((_, i) => i !== index));
  }, []);

  const resetForm = useCallback(() => {
    setQuestion('');
    setSymptomInput('');
    setSymptoms([]);
    setUploadedUrls([]);
    setUploadedNames([]);
    setUploadedFileContext([]);
    setAnswers([]);
    setShowSymptomInput(false);
  }, []);

  const submit = useCallback(async () => {
    if (!question.trim()) {
      Alert.alert('Ask Dr. Ai', 'Please enter your question first.');
      return;
    }

    setLoading(true);
    try {
      const response = await askDrAi({
        question: question.trim(),
        symptoms,
        uploaded_files: uploadedUrls,
        providers: ['database', 'global_search', 'ai'],
      });
      setUploadedFileContext(response.uploaded_file_context || []);
      setAnswers(
        [...(response.answers || [])].sort((a, b) => (b.fit_percentage || 0) - (a.fit_percentage || 0)),
      );
    } catch (error: unknown) {
      setAnswers([]);
      setUploadedFileContext([]);
      const message =
        (error as { response?: { data?: { message?: string } } })?.response?.data?.message
        || 'Unable to generate Ask Dr. Ai answers right now.';
      Alert.alert('Ask Dr. Ai', message);
    } finally {
      setLoading(false);
    }
  }, [question, symptoms, uploadedUrls]);

  return (
    <ScreenLayout
      title="Ask Dr. Ai"
      subtitle="Upload lab PDFs, images, or documents — content is read and used in matching."
    >
      <View style={styles.formCard}>
        <Text style={styles.label}>Search / Ask your question</Text>
        <TextInput
          value={question}
          onChangeText={setQuestion}
          placeholder="Example: Interpret my CBC results"
          multiline
          style={[styles.input, styles.textArea]}
          textAlignVertical="top"
        />

        <AppButton
          label={showSymptomInput ? 'Close symptom input' : 'Add symptoms'}
          variant="secondary"
          onPress={() => setShowSymptomInput((v) => !v)}
        />

        {showSymptomInput ? (
          <View style={styles.symptomRow}>
            <TextInput
              value={symptomInput}
              onChangeText={setSymptomInput}
              placeholder="e.g. resting hand tremor, stiffness"
              style={[styles.input, styles.symptomField]}
              onSubmitEditing={appendSymptom}
            />
            <AppButton label="Save" onPress={appendSymptom} />
          </View>
        ) : null}

        {symptoms.length > 0 ? (
          <View style={styles.pillWrap}>
            {symptoms.map((symptom, index) => (
              <View key={`${symptom}-${index}`} style={styles.pill}>
                <Text style={styles.pillText}>{symptom}</Text>
                <Text style={styles.pillRemove} onPress={() => removeSymptom(index)}>
                  {' \u00d7'}
                </Text>
              </View>
            ))}
          </View>
        ) : null}

        <Text style={styles.label}>Lab results (PDF/DOC/Image)</Text>
        <AppButton
          label={uploading ? 'Uploading...' : 'Upload files'}
          variant="secondary"
          onPress={pickFiles}
          disabled={uploading || loading}
          loading={uploading}
        />
        {uploadedNames.length > 0 ? (
          <View style={styles.pillWrap}>
            {uploadedNames.map((name, index) => (
              <View key={`${name}-${index}`} style={styles.pill}>
                <Text style={styles.pillText}>{name}</Text>
                <Text style={styles.pillRemove} onPress={() => removeUploaded(index)}>
                  {' \u00d7'}
                </Text>
              </View>
            ))}
          </View>
        ) : null}

        <View style={styles.actions}>
          <AppButton label={loading ? 'Analyzing...' : 'Ask Dr. Ai'} onPress={submit} disabled={loading} loading={loading} />
          <AppButton label="Reset" variant="secondary" onPress={resetForm} disabled={loading} />
        </View>
      </View>

      <View style={styles.resultsHeader}>
        <Text style={styles.resultsTitle}>Matched Answers</Text>
        <Text style={styles.resultsHint}>Sorted by best fit percentage</Text>
      </View>

      {uploadedFileContext.length > 0 ? (
        <View style={styles.uploadContext}>
          <Text style={styles.uploadContextTitle}>Uploaded document analysis</Text>
          <Text style={styles.uploadContextHint}>Parsed content from your files</Text>
          {uploadedFileContext.map((file, index) => (
            <UploadedFileAnalysisCard key={`${file.url}-${index}`} file={file} />
          ))}
        </View>
      ) : null}

      {loading ? (
        <Text style={styles.hint}>Reading files and generating matches...</Text>
      ) : answers.length === 0 ? (
        <Text style={styles.hint}>
          Submit your question to get ranked answers from clinic records, global references, and AI analysis.
        </Text>
      ) : (
        <View style={styles.resultsList}>
          {answers.map((item, index) => (
            <MatchedAnswerCard key={`${item.title}-${index}`} item={item} />
          ))}
        </View>
      )}
    </ScreenLayout>
  );
}

const styles = StyleSheet.create({
  formCard: {
    backgroundColor: colors.surface,
    borderColor: colors.border,
    borderRadius: 12,
    borderWidth: 1,
    gap: spacing.md,
    marginBottom: spacing.lg,
    padding: spacing.md,
  },
  label: {
    color: colors.text,
    fontSize: 14,
    fontWeight: '700',
  },
  input: {
    backgroundColor: colors.background,
    borderColor: colors.border,
    borderRadius: 8,
    borderWidth: 1,
    color: colors.text,
    fontSize: 14,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.sm,
  },
  textArea: {
    minHeight: 110,
  },
  symptomRow: {
    gap: spacing.sm,
  },
  symptomField: {
    flex: 1,
  },
  pillWrap: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: spacing.xs,
  },
  pill: {
    alignItems: 'center',
    backgroundColor: colors.background,
    borderColor: colors.border,
    borderRadius: 999,
    borderWidth: 1,
    flexDirection: 'row',
    paddingHorizontal: 10,
    paddingVertical: 4,
  },
  pillText: {
    color: colors.text,
    fontSize: 12,
  },
  pillRemove: {
    color: colors.textMuted,
    fontSize: 14,
    fontWeight: '700',
  },
  actions: {
    gap: spacing.sm,
  },
  resultsHeader: {
    gap: 2,
    marginBottom: spacing.sm,
  },
  resultsTitle: {
    color: colors.text,
    fontSize: 18,
    fontWeight: '700',
  },
  resultsHint: {
    color: colors.textMuted,
    fontSize: 12,
  },
  uploadContext: {
    gap: spacing.sm,
    marginBottom: spacing.md,
  },
  uploadContextTitle: {
    color: colors.text,
    fontSize: 14,
    fontWeight: '700',
  },
  uploadContextHint: {
    color: colors.textMuted,
    fontSize: 12,
    marginBottom: spacing.xs,
  },
  hint: {
    color: colors.textMuted,
    fontSize: 14,
    lineHeight: 20,
  },
  resultsList: {
    gap: spacing.md,
    paddingBottom: spacing.xl,
  },
});
