'use client';

import { useState } from 'react';
import dynamic from 'next/dynamic';
import { toast } from 'sonner';
import {
  RiAddLine,
  RiEditLine,
  RiDeleteBinLine,
  RiSaveLine,
  RiQuestionLine,
} from '@remixicon/react';
import { Button } from '@/components/ui/button';
import {
  Card,
  CardContent,
} from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Spinner } from '@/components/ui/spinners';

const RichTextEditor = dynamic(() => import('./RichTextEditor'), { ssr: false });
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import {
  useBlogFaqsBilingual,
  useCreateBlogFaq,
  useUpdateBlogFaq,
  useDeleteBlogFaq,
} from '../hooks';
import type { BlogFaq } from '../types';

interface Props {
  blogId: number;
}

export default function BlogFaqManager({ blogId }: Props) {
  const { data: bilingualData, isLoading } = useBlogFaqsBilingual(blogId);
  const faqs = bilingualData?.en;
  const faqsAr = bilingualData?.ar;
  const createMutation = useCreateBlogFaq();
  const updateMutation = useUpdateBlogFaq();
  const deleteMutation = useDeleteBlogFaq();

  const [isFormOpen, setIsFormOpen] = useState(false);
  const [editingFaq, setEditingFaq] = useState<BlogFaq | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<BlogFaq | null>(null);
  const [form, setForm] = useState({ question_en: '', question_ar: '', answer_en: '', answer_ar: '' });

  const openCreate = () => {
    setEditingFaq(null);
    setForm({ question_en: '', question_ar: '', answer_en: '', answer_ar: '' });
    setIsFormOpen(true);
  };

  const openEdit = (faq: BlogFaq) => {
    setEditingFaq(faq);

    const arFaq = faqsAr?.find((af) => af.id === faq.id);

    setForm({
      question_en: String(faq.question ?? ''),
      question_ar: arFaq ? String(arFaq.question ?? '') : '',
      answer_en: String(faq.answer ?? ''),
      answer_ar: arFaq ? String(arFaq.answer ?? '') : '',
    });
    setIsFormOpen(true);
  };

  const handleSubmit = () => {
    if (!form.question_en.trim()) {
      toast.error('English question is required');
      return;
    }
    if (!form.answer_en.trim()) {
      toast.error('English answer is required');
      return;
    }
    if (form.question_en.length > 255 || form.question_ar.length > 255) {
      toast.error('Question must be 255 characters or less');
      return;
    }
    if (form.answer_en.length > 2000 || form.answer_ar.length > 2000) {
      toast.error('Answer must be 2000 characters or less');
      return;
    }

    const fd = new FormData();
    fd.append('question_en', form.question_en);
    fd.append('question_ar', form.question_ar || form.question_en);
    fd.append('answer_en', form.answer_en);
    fd.append('answer_ar', form.answer_ar || form.answer_en);

    if (editingFaq) {
      updateMutation.mutate(
        { faqId: editingFaq.id, data: fd },
        {
          onSuccess: () => {
            toast.success('FAQ updated');
            setIsFormOpen(false);
          },
          onError: (error: unknown) => {
            const resp = (error as { response?: { data?: { message?: string } } })?.response?.data;
            toast.error(resp?.message ?? 'Failed to update FAQ');
          },
        },
      );
    } else {
      createMutation.mutate(
        { blogId, data: fd },
        {
          onSuccess: () => {
            toast.success('FAQ added');
            setIsFormOpen(false);
          },
          onError: (error: unknown) => {
            const resp = (error as { response?: { data?: { message?: string } } })?.response?.data;
            toast.error(resp?.message ?? 'Failed to add FAQ');
          },
        },
      );
    }
  };

  const handleDelete = () => {
    if (!deleteTarget) return;
    deleteMutation.mutate(deleteTarget.id, {
      onSuccess: () => {
        toast.success('FAQ deleted');
        setDeleteTarget(null);
      },
      onError: () => toast.error('Failed to delete FAQ'),
    });
  };

  const isPending = createMutation.isPending || updateMutation.isPending;

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12 text-muted-foreground gap-2">
        <Spinner className="size-4 animate-spin" /> Loading FAQs...
      </div>
    );
  }

  return (
    <>
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <h3 className="font-semibold">FAQs ({faqs?.length ?? 0})</h3>
          <Button size="sm" onClick={openCreate}>
            <RiAddLine className="size-4 mr-1" />
            Add FAQ
          </Button>
        </div>

        {(!faqs || faqs.length === 0) ? (
          <div className="text-center py-8 text-muted-foreground border rounded-lg border-dashed">
            <RiQuestionLine className="size-8 mx-auto mb-2 text-muted-foreground/50" />
            <p className="font-medium">No FAQs yet</p>
            <p className="text-sm mt-1">Add frequently asked questions for this blog post.</p>
          </div>
        ) : (
          <div className="space-y-3">
            {faqs.map((faq) => (
              <Card key={faq.id}>
                <CardContent className="py-4">
                  <div className="flex items-start justify-between gap-4">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1">
                        <h4 className="font-medium text-sm">{String(faq.question ?? '')}</h4>
                      </div>
                      <div
                        className="text-sm text-muted-foreground line-clamp-3 prose prose-sm max-w-none"
                        dangerouslySetInnerHTML={{ __html: String(faq.answer ?? '').replace(/<script[\s\S]*?<\/script>/gi, '').replace(/on\w+\s*=\s*["'][^"']*["']/gi, '').replace(/javascript\s*:/gi, '') }}
                      />
                    </div>
                    <div className="flex gap-1 shrink-0">
                      <Button variant="ghost" size="sm" className="size-8 p-0" onClick={() => openEdit(faq)}>
                        <RiEditLine className="size-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        className="size-8 p-0 text-destructive hover:text-destructive"
                        onClick={() => setDeleteTarget(faq)}
                      >
                        <RiDeleteBinLine className="size-4" />
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </div>

      <Dialog open={isFormOpen} onOpenChange={setIsFormOpen}>
        <DialogContent className="sm:max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editingFaq ? 'Edit FAQ' : 'Add FAQ'}</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-2">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-1.5">
                <Label>Question (English)</Label>
                <Input
                  value={form.question_en}
                  onChange={(e) => setForm((p) => ({ ...p, question_en: e.target.value }))}
                  placeholder="Enter the question in English"
                />
              </div>
              <div className="space-y-1.5">
                <Label>Question (Arabic)</Label>
                <Input
                  dir="rtl"
                  value={form.question_ar}
                  onChange={(e) => setForm((p) => ({ ...p, question_ar: e.target.value }))}
                  placeholder="أدخل السؤال بالعربية"
                />
              </div>
            </div>
            <div className="space-y-1.5">
              <Label>Answer (English)</Label>
              <RichTextEditor
                content={form.answer_en}
                onChange={(html) => setForm((p) => ({ ...p, answer_en: html }))}
                placeholder="Write your answer in English..."
                dir="ltr"
                minHeight="150px"
              />
            </div>
            <div className="space-y-1.5">
              <Label>Answer (Arabic)</Label>
              <RichTextEditor
                content={form.answer_ar}
                onChange={(html) => setForm((p) => ({ ...p, answer_ar: html }))}
                placeholder="اكتب الإجابة بالعربية..."
                dir="rtl"
                minHeight="150px"
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" size="sm" onClick={() => setIsFormOpen(false)}>Cancel</Button>
            <Button size="sm" onClick={handleSubmit} disabled={isPending}>
              <RiSaveLine className="size-4 mr-1" />
              {isPending ? 'Saving...' : 'Save'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={!!deleteTarget} onOpenChange={(open) => !open && setDeleteTarget(null)}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Delete FAQ</DialogTitle>
          </DialogHeader>
          <p className="text-sm text-muted-foreground py-2">
            Are you sure you want to delete this FAQ?
          </p>
          <DialogFooter className="gap-2 sm:gap-0">
            <Button variant="outline" size="sm" onClick={() => setDeleteTarget(null)}>Cancel</Button>
            <Button variant="destructive" size="sm" onClick={handleDelete} disabled={deleteMutation.isPending}>
              {deleteMutation.isPending ? 'Deleting...' : 'Delete'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
