import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Save, Loader2, Mail } from 'lucide-react';
import { supabase } from '@/lib/supabaseClient';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { AdminLayout } from '@/components/layout/AdminLayout';
import { useUserRole } from '@/hooks/useUserRole';
import { handleError, handleSuccess } from '@/lib/errorHandler';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { useDocumentTitle } from '@/hooks/useDocumentTitle';

export default function AdminEmailSettings() {
  useDocumentTitle('Email Settings - Admin');
  const queryClient = useQueryClient();
  const { isSuperuser, loading: rolesLoading } = useUserRole();
  const [signature, setSignature] = useState('');

  // Fetch email signature
  const { data: signatureSetting, isLoading } = useQuery({
    queryKey: ['admin-email-signature'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('admin_settings')
        .select('setting_value')
        .eq('setting_key', 'email.signature')
        .single();

      if (error && error.code !== 'PGRST116') { // PGRST116 = no rows returned
        throw error;
      }

      // Type guard for the setting value
      const settingValue = data?.setting_value as { signature?: string } | null;
      return settingValue?.signature || '';
    },
  });

  useEffect(() => {
    if (signatureSetting !== undefined) {
      setSignature(signatureSetting);
    }
  }, [signatureSetting]);

  // Update email signature mutation
  const updateSignatureMutation = useMutation({
    mutationFn: async (newSignature: string) => {
      const { data: existing } = await supabase
        .from('admin_settings')
        .select('id')
        .eq('setting_key', 'email.signature')
        .single();

      if (existing) {
        // Update existing
        const { error } = await supabase
          .from('admin_settings')
          .update({
            setting_value: { signature: newSignature },
            updated_at: new Date().toISOString(),
          })
          .eq('setting_key', 'email.signature');

        if (error) throw error;
      } else {
        // Insert new
        const { error } = await supabase
          .from('admin_settings')
          .insert({
            setting_key: 'email.signature',
            setting_value: { signature: newSignature },
            category: 'email',
            description: 'Email signature automatically appended to all contact submission replies',
          });

        if (error) throw error;
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin-email-signature'] });
      handleSuccess('Saved', 'Email signature has been updated successfully');
    },
    onError: (error) => {
      handleError(error, { action: 'update_email_signature' });
    },
  });

  const handleSave = () => {
    updateSignatureMutation.mutate(signature);
  };

  // Show loading state while roles are being fetched
  if (rolesLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  // Superuser-only access check
  if (!isSuperuser()) {
    return (
      <AdminLayout>
        <div className="flex items-center justify-center min-h-[60vh]">
          <Card className="max-w-md">
            <CardContent className="pt-6 text-center">
              <Mail className="h-12 w-12 text-destructive mx-auto mb-4" />
              <h2 className="text-xl font-semibold mb-2">Access Denied</h2>
              <p className="text-muted-foreground">
                Email settings can only be managed by superusers.
              </p>
            </CardContent>
          </Card>
        </div>
      </AdminLayout>
    );
  }

  return (
    <AdminLayout>
      <div className="mb-8">
        <h1 className="text-4xl font-bold mb-2">Email Settings</h1>
        <p className="text-muted-foreground">
          Configure automatic email signature for contact submission replies
        </p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Mail className="h-5 w-5" />
            Email Signature
          </CardTitle>
          <CardDescription>
            This signature will be automatically appended to all email replies sent to users from the Contact Submissions page.
            The signature will be added after a separator line.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <Alert>
            <AlertDescription>
              <strong>Preview:</strong> The signature will appear as:
              <div className="mt-2 p-3 bg-muted rounded-md text-sm font-mono whitespace-pre-wrap">
                [Your reply message]
                {'\n\n'}---
                {'\n'}[Admin Display Name]
                {signature ? `\n${signature}` : '\n[No signature set]'}
              </div>
            </AlertDescription>
          </Alert>

          <div className="space-y-2">
            <Label htmlFor="signature">Signature Text</Label>
            <Textarea
              id="signature"
              value={signature}
              onChange={(e) => setSignature(e.target.value)}
              placeholder="Best regards,&#10;The ThrillWiki Team&#10;&#10;Need help? Reply to this email or visit https://thrillwiki.com/contact"
              rows={8}
              disabled={isLoading}
            />
            <p className="text-xs text-muted-foreground">
              Use plain text. Line breaks will be preserved. You can include team name, contact info, or helpful links.
            </p>
          </div>

          <div className="flex items-center gap-3 pt-4">
            <Button
              onClick={handleSave}
              disabled={updateSignatureMutation.isPending || isLoading}
            >
              {updateSignatureMutation.isPending && (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              )}
              <Save className="mr-2 h-4 w-4" />
              Save Signature
            </Button>
            {signature !== signatureSetting && (
              <Button
                variant="outline"
                onClick={() => setSignature(signatureSetting || '')}
                disabled={updateSignatureMutation.isPending}
              >
                Reset Changes
              </Button>
            )}
          </div>
        </CardContent>
      </Card>
    </AdminLayout>
  );
}
