import React, { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { supabase } from '@/integrations/supabase/client';
import { notifyStaffOfArcSubmission } from '@/lib/arcSubmissionEmail';
import { useToast } from '@/hooks/use-toast';
import { Loader2, Upload, X, FileText, Trash2 } from 'lucide-react';
import { v4 as uuidv4 } from 'uuid';

function ARCApplicationDialog({ open, onOpenChange, application, onSuccess }) {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [clients, setClients] = useState([]);
  const [owners, setOwners] = useState([]);
  const [ownersLoading, setOwnersLoading] = useState(false);
  const [ownerSearch, setOwnerSearch] = useState('');

  const [newFiles, setNewFiles] = useState([]);
  const [existingFiles, setExistingFiles] = useState([]);
  
  const [formData, setFormData] = useState({
    title: '',
    association_id: '',
    description: '',
    status: 'submitted',
    owner_id: '',
    unit_id: '',
  });

  useEffect(() => {
    const fetchClients = async () => {
      const { data } = await supabase.from('associations').select('id, name').eq('status', 'active').order('name');
      setClients(data || []);
    };
    if (open) fetchClients();
  }, [open]);

  // Load owners for the selected association
  useEffect(() => {
    const fetchOwners = async () => {
      if (!formData.association_id) {
        setOwners([]);
        return;
      }
      setOwnersLoading(true);
      try {
        const { data } = await supabase
          .from('owners')
          .select('id, first_name, last_name, property_address, unit_id, status')
          .eq('association_id', formData.association_id)
          .neq('status', 'archived')
          .order('last_name', { nullsFirst: false })
          .limit(2000);
        setOwners(data || []);
      } finally {
        setOwnersLoading(false);
      }
    };
    fetchOwners();
  }, [formData.association_id]);

  useEffect(() => {
    if (application) {
      setFormData({
        title: application.title || '',
        association_id: application.association_id || '',
        description: application.description || '',
        status: application.status || 'submitted',
        owner_id: application.owner_id || '',
        unit_id: application.unit_id || '',
      });
      setExistingFiles([]);
    } else {
      setFormData({ title: '', association_id: '', description: '', status: 'submitted', owner_id: '', unit_id: '' });
      setNewFiles([]);
      setExistingFiles([]);
    }
    setOwnerSearch('');
  }, [application, open]);

  const filteredOwners = React.useMemo(() => {
    const q = ownerSearch.trim().toLowerCase();
    if (!q) return owners.slice(0, 100);
    return owners.filter(o => {
      const name = `${o.first_name || ''} ${o.last_name || ''}`.toLowerCase();
      const addr = (o.property_address || '').toLowerCase();
      return name.includes(q) || addr.includes(q);
    }).slice(0, 100);
  }, [owners, ownerSearch]);

  const selectedOwner = owners.find(o => o.id === formData.owner_id);

  const handleFileChange = (e) => {
    if (e.target.files) {
      const filesArray = Array.from(e.target.files);
      setNewFiles(prev => [...prev, ...filesArray]);
    }
  };

  const removeNewFile = (index) => {
    setNewFiles(prev => prev.filter((_, i) => i !== index));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);

    try {
      const { data: { user } } = await supabase.auth.getUser();
      
      const payload = {
        title: formData.title,
        association_id: formData.association_id,
        description: formData.description,
        status: formData.status,
        owner_id: formData.owner_id || null,
        unit_id: formData.unit_id || (selectedOwner?.unit_id ?? null),
        updated_at: new Date().toISOString()
      };

      let appId = application?.id;

      if (application) {
        const { error: err } = await supabase.from('arc_applications').update(payload).eq('id', application.id);
        if (err) throw err;
      } else {
        const { data, error: err } = await supabase.from('arc_applications').insert([payload]).select().single();
        if (err) throw err;
        appId = data.id;

        // Fire-and-forget staff notification email for new submissions only
        const assocName = clients.find((c) => c.id === formData.association_id)?.name;
        notifyStaffOfArcSubmission({
          applicationId: data.id,
          applicationTitle: formData.title || 'Architectural review request',
          associationId: formData.association_id || null,
          associationName: assocName,
          description: formData.description || null,
          fileCount: newFiles.length,
        });
      }

      // Upload files to arc-files bucket and mirror into Documents under "ARC Applications"
      if (newFiles.length > 0 && appId && formData.association_id) {
        // Try to look up an address for context
        let addressLabel = '';
        try {
          const { data: appRow } = await supabase
            .from('arc_applications')
            .select('unit_id, owner_id')
            .eq('id', appId)
            .maybeSingle();
          if (appRow?.unit_id) {
            const { data: u } = await supabase.from('units').select('address, unit_number').eq('id', appRow.unit_id).maybeSingle();
            addressLabel = u?.address || u?.unit_number || '';
          }
          if (!addressLabel && appRow?.owner_id) {
            const { data: o } = await supabase.from('owners').select('property_address').eq('id', appRow.owner_id).maybeSingle();
            addressLabel = o?.property_address || '';
          }
        } catch {}
        if (!addressLabel) addressLabel = 'Unknown Address';

        for (const file of newFiles) {
          try {
            const storagePath = `${formData.association_id}/${appId}/${Date.now()}-${file.name}`;
            const { error: upErr } = await supabase.storage.from('arc-files').upload(storagePath, file, { contentType: file.type });
            if (upErr) continue;
            const { data: urlData } = supabase.storage.from('arc-files').getPublicUrl(storagePath);
            await supabase.from('documents').insert({
              title: `${addressLabel} - ${formData.title || 'ARC Application'} - ${file.name}`,
              file_name: file.name,
              file_url: urlData.publicUrl,
              file_size: file.size,
              category: 'ARC Applications',
              association_id: formData.association_id,
              visibility: [],
              is_public: false,
            });
          } catch (e) {
            console.error('ARC file upload failed', e);
          }
        }
      }

      toast({
        title: application ? "Application Updated" : "Application Submitted",
        description: "ARC Application saved successfully."
      });
      setNewFiles([]);
      onSuccess(); 
      onOpenChange(false);

    } catch (err) {
      console.error(err);
      toast({
        variant: "destructive",
        title: "Error",
        description: err.message
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{application ? 'Edit ARC Application' : 'New ARC Application'}</DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
                <div>
                    <Label htmlFor="title">Project Title *</Label>
                    <Input 
                        id="title" 
                        value={formData.title} 
                        onChange={e => setFormData({...formData, title: e.target.value})} 
                        required 
                        placeholder="e.g. Fence Installation"
                    />
                </div>
                <div>
                    <Label htmlFor="association_id">Association *</Label>
                    <select
                        id="association_id"
                        value={formData.association_id}
                        onChange={e => setFormData({...formData, association_id: e.target.value})}
                        required
                        className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                    >
                        <option value="">Select Association</option>
                        {clients.map(c => (
                            <option key={c.id} value={c.id}>{c.name}</option>
                        ))}
                    </select>
                </div>
            </div>

            <div>
                <Label className="mb-1 block">Homeowner</Label>
                {!formData.association_id ? (
                  <p className="text-xs text-muted-foreground">Select an association first to choose an owner.</p>
                ) : (
                  <div className="space-y-2">
                    {selectedOwner ? (
                      <div className="flex items-center justify-between rounded-md border bg-muted/40 p-2 text-sm">
                        <div className="min-w-0">
                          <div className="font-medium truncate">
                            {(selectedOwner.first_name || '') + ' ' + (selectedOwner.last_name || '')}
                          </div>
                          {selectedOwner.property_address && (
                            <div className="text-xs text-muted-foreground truncate">{selectedOwner.property_address}</div>
                          )}
                        </div>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={() => setFormData(f => ({ ...f, owner_id: '', unit_id: '' }))}
                        >
                          <X className="w-4 h-4" />
                        </Button>
                      </div>
                    ) : (
                      <>
                        <Input
                          placeholder={ownersLoading ? 'Loading owners...' : 'Search owners by name or address...'}
                          value={ownerSearch}
                          onChange={(e) => setOwnerSearch(e.target.value)}
                          disabled={ownersLoading}
                        />
                        {ownerSearch.trim() && (
                          <div className="max-h-48 overflow-y-auto rounded-md border divide-y">
                            {filteredOwners.length === 0 ? (
                              <div className="p-2 text-xs text-muted-foreground">No owners match.</div>
                            ) : (
                              filteredOwners.map(o => (
                                <button
                                  key={o.id}
                                  type="button"
                                  className="w-full text-left p-2 text-sm hover:bg-accent"
                                  onClick={() => {
                                    setFormData(f => ({ ...f, owner_id: o.id, unit_id: o.unit_id || '' }));
                                    setOwnerSearch('');
                                  }}
                                >
                                  <div className="font-medium">{(o.first_name || '') + ' ' + (o.last_name || '')}</div>
                                  {o.property_address && (
                                    <div className="text-xs text-muted-foreground truncate">{o.property_address}</div>
                                  )}
                                </button>
                              ))
                            )}
                          </div>
                        )}
                      </>
                    )}
                  </div>
                )}
            </div>

            <div>
                <Label htmlFor="description">Description</Label>
                <Textarea 
                    id="description" 
                    value={formData.description} 
                    onChange={e => setFormData({...formData, description: e.target.value})} 
                    rows={4}
                    placeholder="Describe the proposed changes, materials, dimensions, etc..."
                    required
                />
            </div>

            <div>
                <Label className="mb-2 block">Attachments</Label>
                <div className="flex items-center gap-2 mb-3">
                    <label htmlFor="file-upload" className="cursor-pointer inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors border border-input hover:bg-accent hover:text-accent-foreground h-10 px-4 py-2 w-full border-dashed border-2">
                        <Upload className="w-4 h-4 mr-2" />
                        Click to Select Files (Images, PDF)
                    </label>
                    <input 
                        id="file-upload" 
                        type="file" 
                        multiple
                        onChange={handleFileChange}
                        className="hidden"
                    />
                </div>

                <div className="space-y-2 max-h-[150px] overflow-y-auto">
                    {newFiles.map((file, idx) => (
                        <div key={idx} className="flex items-center justify-between p-2 bg-muted/50 rounded border text-sm">
                            <div className="flex items-center gap-2 overflow-hidden">
                                <Upload className="w-4 h-4 text-primary flex-shrink-0" />
                                <span className="truncate">{file.name}</span>
                            </div>
                            <Button 
                                type="button" 
                                variant="ghost" 
                                size="sm" 
                                className="h-6 w-6 p-0"
                                onClick={() => removeNewFile(idx)}
                            >
                                <X className="w-3 h-3" />
                            </Button>
                        </div>
                    ))}
                </div>
            </div>

            <div className="flex justify-end pt-4 space-x-2">
                <Button variant="outline" type="button" onClick={() => onOpenChange(false)}>Cancel</Button>
                <Button type="submit" disabled={loading}>
                    {loading && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
                    Save Application
                </Button>
            </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}

export default ARCApplicationDialog;
