import React, { useState, useEffect } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger, DialogFooter } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Loader2, Mail, Copy, Check, RefreshCw, AlertTriangle, ShieldCheck } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";

export default function ClientEmailDialog({ clientId, clientName, trigger }) {
  const [isOpen, setIsOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [emailData, setEmailData] = useState(null);
  const [copied, setCopied] = useState(false);
  const { toast } = useToast();
  const db = supabase;

  useEffect(() => {
    if (isOpen && clientId) {
      fetchEmail();
    }
  }, [isOpen, clientId]);

  const fetchEmail = async () => {
    setLoading(true);
    try {
      // Note: client_email_addresses table may need to be created if not present
      const { data, error } = await db
        .from('associations')
        .select('email')
        .eq('id', clientId)
        .maybeSingle();

      if (error) {
        console.error("ClientEmailDialog: Error fetching email:", error);
        toast({ variant: "destructive", title: "Fetch Error", description: "Could not retrieve email settings." });
      }
      
      setEmailData(data ? { email_address: data.email, created_at: new Date().toISOString() } : null);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const generateEmail = async () => {
    setLoading(true);
    try {
      const { data, error } = await supabase.functions.invoke('generate-client-email', {
        body: { 
            clientId: clientId,
            clientName: clientName 
        },
      });

      if (error) {
          throw new Error(data?.error || error.message || "Function invocation failed");
      }
      
      await fetchEmail();
      
      toast({ 
          title: "Email Generated", 
          description: `Successfully assigned email`,
      });
    } catch (err) {
      console.error("ClientEmailDialog: Generation error", err);
      toast({ 
          variant: "destructive", 
          title: "Generation Failed", 
          description: err.message || "Failed to generate email address." 
      });
    } finally {
      setLoading(false);
    }
  };

  const handleCopy = () => {
    if (emailData?.email_address) {
      navigator.clipboard.writeText(emailData.email_address);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
      toast({ title: "Copied", description: "Email address copied to clipboard." });
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={setIsOpen}>
      <DialogTrigger asChild>
        {trigger || (
          <Button variant="outline" size="sm" className="gap-2">
            <Mail className="h-4 w-4" />
            Manage Inbound Email
          </Button>
        )}
      </DialogTrigger>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Inbound Email Configuration</DialogTitle>
          <DialogDescription>
             Configuration for <strong>{clientName}</strong>. 
          </DialogDescription>
        </DialogHeader>

        <div className="py-4 space-y-6">
          {loading && !emailData ? (
             <div className="flex flex-col items-center justify-center py-8 gap-3">
                 <Loader2 className="h-8 w-8 animate-spin text-blue-600" />
                 <p className="text-sm text-slate-500">Communicating with server...</p>
             </div>
          ) : emailData ? (
            <div className="space-y-6">
              <div className="space-y-2">
                <Label className="text-xs font-semibold uppercase text-slate-500">Active Inbound Address</Label>
                <div className="flex gap-2">
                  <div className="relative flex-1">
                    <Input readOnly value={emailData.email_address} className="pr-10 font-mono bg-slate-50 text-slate-700 border-slate-300" />
                    <ShieldCheck className="absolute right-3 top-3 h-4 w-4 text-green-500" />
                  </div>
                  <Button variant="outline" size="icon" onClick={handleCopy} className="shrink-0">
                    {copied ? <Check className="h-4 w-4 text-green-600" /> : <Copy className="h-4 w-4" />}
                  </Button>
                </div>
                <p className="text-[11px] text-slate-400">
                    Created on {new Date(emailData.created_at).toLocaleDateString()}
                </p>
              </div>

              <Alert className="bg-blue-50 border-blue-100 text-blue-800">
                <Mail className="h-4 w-4 text-blue-600" />
                <AlertTitle className="text-blue-900 font-semibold ml-2">How it works</AlertTitle>
                <AlertDescription className="text-blue-800/90 text-xs mt-1 ml-2 leading-relaxed">
                  Emails sent to this address are automatically processed. 
                  The content is extracted and added as a <strong>Status Update</strong> for this association.
                </AlertDescription>
              </Alert>
              
              <div className="border-t pt-4">
                  <div className="flex items-center justify-between">
                     <div>
                        <p className="text-sm font-medium text-slate-900">Regenerate Address</p>
                        <p className="text-xs text-slate-500">Create a new random address if spam occurs.</p>
                     </div>
                     <Button 
                        variant="ghost" 
                        size="sm" 
                        onClick={generateEmail}
                        disabled={loading}
                        className="text-red-500 hover:text-red-600 hover:bg-red-50"
                     >
                        <RefreshCw className={`h-3 w-3 mr-2 ${loading ? 'animate-spin' : ''}`} /> 
                        Regenerate
                     </Button>
                  </div>
              </div>
            </div>
          ) : (
            <div className="text-center py-6 space-y-6">
              <div className="mx-auto bg-slate-100 p-6 rounded-full w-20 h-20 flex items-center justify-center border border-slate-200">
                 <Mail className="h-10 w-10 text-slate-400" />
              </div>
              <div className="space-y-2 max-w-xs mx-auto">
                <h4 className="font-semibold text-slate-900">No Email Address Assigned</h4>
                <p className="text-sm text-slate-500">Generate a unique inbound address for {clientName} to enable email-to-status features.</p>
              </div>
              <Button onClick={generateEmail} disabled={loading} className="w-full max-w-xs bg-blue-600 hover:bg-blue-700">
                 {loading ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <RefreshCw className="h-4 w-4 mr-2" />}
                 Generate Email Address
              </Button>
            </div>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}