'use client';

import React, { useState, useEffect } from 'react';
import { Search, Send, Loader2, CheckCircle2, Clock } from 'lucide-react';
import { Button } from '../../components/ui/Button';
import { ForumQuestion, ForumAnswer, QuestionSubmission } from '@/types/forum';

export const QuestionsPageContent: React.FC = () => {
  const [questions, setQuestions] = useState<ForumQuestion[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedModule, setSelectedModule] = useState('All');
  const [showForm, setShowForm] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [formData, setFormData] = useState<QuestionSubmission>({
    firstName: '',
    lastName: '',
    email: '',
    company: '',
    module: '',
    question: '',
    source: ''
  });
  const [submitted, setSubmitted] = useState(false);

  const modules = ['All', 'General', 'Inbound Sales', 'Sales', 'Dispatch', 'Warehousing', 'Finance', 'Procurement', 'Tendering', 'Service Support', 'Analytics', 'Administration'];

  // Fetch questions from API
  useEffect(() => {
    fetchQuestions();
  }, []);

  const fetchQuestions = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await fetch('/api/forum/questions');
      const result = await response.json();
      
      if (result.success && result.data) {
        setQuestions(result.data);
      } else {
        setError(result.error || 'Failed to load questions');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load questions');
    } finally {
      setLoading(false);
    }
  };

  // Client-side filtering (can be moved to API with query params)
  const filteredQuestions = questions.filter(q => {
    const matchesSearch = searchQuery === '' || 
      q.question.toLowerCase().includes(searchQuery.toLowerCase()) ||
      q.answer?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      q.tags.some(tag => tag.toLowerCase().includes(searchQuery.toLowerCase()));
    const matchesModule = selectedModule === 'All' || q.module === selectedModule;
    return matchesSearch && matchesModule;
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    setError(null);

    try {
      const response = await fetch('/api/forum/questions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      });

      const result = await response.json();

      if (result.success) {
        setSubmitted(true);
        // Reset form
        setFormData({ firstName: '', lastName: '', email: '', company: '', module: '', question: '', source: '' });
        // Refresh questions list
        await fetchQuestions();
        // Hide form after 3 seconds
        setTimeout(() => {
          setShowForm(false);
          setSubmitted(false);
        }, 3000);
      } else {
        setError(result.error || 'Failed to submit question');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to submit question');
    } finally {
      setSubmitting(false);
    }
  };

  // Update structured data for SEO
  const structuredData = {
    "@context": "https://schema.org",
    "@type": "FAQPage",
    "mainEntity": filteredQuestions
      .filter(q => q.status === 'answered' && q.answer)
      .map(qa => ({
        "@type": "Question",
        "name": qa.question,
        "acceptedAnswer": {
          "@type": "Answer",
          "text": qa.answer || ''
        }
      }))
  };

  useEffect(() => {
    const script = document.createElement('script');
    script.type = 'application/ld+json';
    script.id = 'faq-structured-data';
    script.text = JSON.stringify(structuredData);
    document.head.appendChild(script);
    return () => {
      const existingScript = document.getElementById('faq-structured-data');
      if (existingScript) {
        document.head.removeChild(existingScript);
      }
    };
  }, [filteredQuestions]);

  return (
    <>
      <section className="relative pt-40 pb-20 md:pt-48 md:pb-32 bg-slate-50 dark:bg-[#0B1220]">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-16">
            <h1 className="text-5xl md:text-7xl font-bold text-brand-navy dark:text-white mb-6">
              Knowbuild User Forum
            </h1>
            <div className="text-xl text-slate-600 dark:text-slate-300 max-w-3xl mx-auto mb-8 space-y-3">
              <div>
                <p className="font-semibold text-slate-700 dark:text-slate-200 mb-2">
                  Have a problem you want solved?
                </p>
                <p>
                  Ask our experts any question by business function to discover how Knowbuild QERP.CRM can be applied to your specific challenges.
                </p>
              </div>
              <p className="text-lg font-medium text-slate-500 dark:text-slate-400 my-4">
                Or
              </p>
              <div>
                <p className="font-semibold text-slate-700 dark:text-slate-200 mb-2">
                  Looking to solve a specific operational challenge?
                </p>
                <p>
                  Search discussions to see how Knowbuild QERP.CRM is being used across different business functions and learn from real-world implementations.
                </p>
              </div>
            </div>
            <Button onClick={() => setShowForm(!showForm)} variant="primary" size="lg">
              {showForm ? 'Hide Form' : 'Ask a Question'}
            </Button>
          </div>

          {/* Error Message */}
          {error && (
            <div className="max-w-3xl mx-auto mb-8 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
              <p className="text-red-800 dark:text-red-200">{error}</p>
            </div>
          )}

          {/* Question Submission Form */}
          {showForm && (
            <div className="max-w-3xl mx-auto mb-16 bg-white dark:bg-slate-800 rounded-2xl p-8 shadow-lg">
              {submitted ? (
                <div className="text-center py-12">
                  <div className="w-16 h-16 bg-green-100 dark:bg-green-900/30 rounded-full flex items-center justify-center mx-auto mb-4">
                    <Send className="text-green-600 dark:text-green-400" size={32} />
                  </div>
                  <h3 className="text-2xl font-bold text-brand-navy dark:text-white mb-2">Thank You!</h3>
                  <p className="text-slate-600 dark:text-slate-400">
                    Your question has been submitted for review. We'll publish the answer soon.
                  </p>
                </div>
              ) : (
                <form onSubmit={handleSubmit} className="space-y-6">
                  <h2 className="text-2xl font-bold text-brand-navy dark:text-white mb-6">Submit Your Question</h2>

                  <div className="grid md:grid-cols-2 gap-6">
                    <div>
                      <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">First Name *</label>
                      <input
                        type="text"
                        required
                        disabled={submitting}
                        className="w-full px-4 py-3 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-900 text-slate-900 dark:text-white disabled:opacity-50"
                        value={formData.firstName || ''}
                        onChange={(e) => setFormData({ ...formData, firstName: e.target.value })}
                      />
                      <p className="mt-2 text-xs text-slate-500 dark:text-slate-400">
                        Only your first name will be displayed.
                      </p>
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">Last Name</label>
                      <input
                        type="text"
                        disabled={submitting}
                        className="w-full px-4 py-3 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-900 text-slate-900 dark:text-white disabled:opacity-50"
                        value={formData.lastName || ''}
                        onChange={(e) => setFormData({ ...formData, lastName: e.target.value })}
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">Work Email *</label>
                    <input
                      type="email"
                      required
                      disabled={submitting}
                      className="w-full px-4 py-3 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-900 text-slate-900 dark:text-white disabled:opacity-50"
                      value={formData.email}
                      onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                    />
                    <p className="mt-2 text-xs text-slate-500 dark:text-slate-400">
                      Your work email will never be shown publicly.
                    </p>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">Company Name *</label>
                    <input
                      type="text"
                      required
                      disabled={submitting}
                      className="w-full px-4 py-3 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-900 text-slate-900 dark:text-white disabled:opacity-50"
                      value={formData.company}
                      onChange={(e) => setFormData({ ...formData, company: e.target.value })}
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">Module/Category *</label>
                    <select
                      required
                      disabled={submitting}
                      className="w-full px-4 py-3 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-900 text-slate-900 dark:text-white disabled:opacity-50"
                      value={formData.module}
                      onChange={(e) => setFormData({ ...formData, module: e.target.value })}
                    >
                      <option value="">Select a module</option>
                      {modules.filter(m => m !== 'All').map(m => (
                        <option key={m} value={m}>{m}</option>
                      ))}
                    </select>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">Your Question *</label>
                    <textarea
                      required
                      rows={4}
                      disabled={submitting}
                      className="w-full px-4 py-3 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-900 text-slate-900 dark:text-white disabled:opacity-50"
                      value={formData.question}
                      onChange={(e) => setFormData({ ...formData, question: e.target.value })}
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">How did you hear about knowbuild? (Optional)</label>
                    <input
                      type="text"
                      disabled={submitting}
                      className="w-full px-4 py-3 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-900 text-slate-900 dark:text-white disabled:opacity-50"
                      value={formData.source}
                      onChange={(e) => setFormData({ ...formData, source: e.target.value })}
                    />
                  </div>

                  <Button type="submit" variant="primary" size="lg" fullWidth disabled={submitting}>
                    {submitting ? (
                      <>
                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                        Submitting...
                      </>
                    ) : (
                      'Submit Question'
                    )}
                  </Button>
                </form>
              )}
            </div>
          )}

          {/* Search and Filter */}
          <div className="max-w-4xl mx-auto mb-12">
            <div className="flex flex-col md:flex-row gap-4 mb-6">
              <div className="flex-1 relative">
                <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" size={20} />
                <input
                  type="text"
                  placeholder="Search questions..."
                  className="w-full pl-12 pr-4 py-3 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-900 text-slate-900 dark:text-white"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                />
              </div>
              <div className="md:w-64">
                <select
                  className="w-full px-4 py-3 rounded-lg border border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-900 text-slate-900 dark:text-white"
                  value={selectedModule}
                  onChange={(e) => setSelectedModule(e.target.value)}
                >
                  {modules.map(m => (
                    <option key={m} value={m}>{m}</option>
                  ))}
                </select>
              </div>
            </div>
          </div>

          {/* Q&A List */}
          <div className="max-w-4xl mx-auto space-y-6">
            <h2 className="text-2xl font-bold text-brand-navy dark:text-white mb-6">
              {selectedModule !== 'All' ? `${selectedModule} Questions` : 'All Questions'}
              {!loading && <span className="text-lg font-normal text-slate-500 ml-2">({filteredQuestions.length})</span>}
            </h2>

            {loading ? (
              <div className="text-center py-12">
                <Loader2 className="h-8 w-8 animate-spin text-brand-blue mx-auto mb-4" />
                <p className="text-slate-500">Loading questions...</p>
              </div>
            ) : filteredQuestions.length === 0 ? (
              <div className="text-center py-12 text-slate-500">
                No questions found. Try a different search or ask a new question.
              </div>
            ) : (
              filteredQuestions.map((qa) => (
                <div key={qa.id} className="bg-white dark:bg-slate-800 rounded-2xl p-8 shadow-sm">
                  <div className="flex items-start gap-4 mb-4 flex-wrap">
                    <span className="px-3 py-1 bg-brand-blue/10 text-brand-blue text-xs font-bold rounded-full">
                      {qa.module}
                    </span>
                    <span className={`px-3 py-1 text-xs font-bold rounded-full flex items-center gap-1 ${
                      qa.status === 'answered' 
                        ? 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400' 
                        : 'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-700 dark:text-yellow-400'
                    }`}>
                      {qa.status === 'answered' ? (
                        <>
                          <CheckCircle2 size={12} />
                          Answered
                        </>
                      ) : (
                        <>
                          <Clock size={12} />
                          Pending
                        </>
                      )}
                    </span>
                    {qa.answerCount !== undefined && qa.answerCount > 0 && (
                      <span className="px-3 py-1 bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-400 text-xs font-medium rounded-full">
                        {qa.answerCount} {qa.answerCount === 1 ? 'answer' : 'answers'}
                      </span>
                    )}
                  </div>
                  <h3 className="text-xl font-bold text-brand-navy dark:text-white mb-4">
                    {qa.question}
                  </h3>
                  {qa.askerName ? (
                    <p className="text-sm text-slate-500 dark:text-slate-400 mb-4">
                      Asked by {qa.askerName}
                    </p>
                  ) : null}
                  {qa.answer ? (
                    <div className="text-slate-600 dark:text-slate-400 leading-relaxed">
                      <p className="font-medium text-slate-700 dark:text-slate-300 mb-2">Answer:</p>
                      <p>{qa.answer}</p>
                    </div>
                  ) : (
                    <p className="text-slate-500 italic">This question is awaiting an answer.</p>
                  )}
                  {qa.tags && qa.tags.length > 0 && (
                    <div className="mt-4 flex flex-wrap gap-2">
                      {qa.tags.map((tag, idx) => (
                        <span key={idx} className="px-2 py-1 bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-400 text-xs rounded">
                          #{tag}
                        </span>
                      ))}
                    </div>
                  )}
                </div>
              ))
            )}
          </div>
        </div>
      </section>
    </>
  );
};

