
import React, { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { supabase } from '@/integrations/supabase/client';
import { HardDrive, Loader2 } from 'lucide-react';
import { toast as sonnerToast } from 'sonner';
import { useGoogleDrive } from '@/hooks/useGoogleDrive';
import GoogleDriveFolderPickerDialog from '@/components/documents/GoogleDriveFolderPickerDialog';

const DEFAULT_FOLDERS = [
  'Bank Statements',
  'Collections',
  'Financials',
  'Insurance',
  'Litigation',
  'Management Reports',
  'Meetings',
  'New Owner Files',
  'Owner Correspondence',
  'Reports',
];

export function SaveToDocumentsDialog({ 
  open, 
  onOpenChange, 
  onSave, 
  defaultName = '', 
  defaultClientId = '',
  residentFileMode = false,
  unitId = '',
  unitNumber = '',
  unitAddress = '',
}) {
  const [loading, setLoading] = useState(false);
  const [clients, setClients] = useState([]);
  const [folders, setFolders] = useState(DEFAULT_FOLDERS);
  const drive = useGoogleDrive();
  const [saveToDrive, setSaveToDrive] = useState(false);
  const [driveFolder, setDriveFolder] = useState(null);
  const [drivePickerOpen, setDrivePickerOpen] = useState(false);
  const [resolvedAddress, setResolvedAddress] = useState('');

  // Auto-recognize the unit's street address so the Resident Files folder
  // is labeled by address instead of an opaque UUID.
  useEffect(() => {
    if (!residentFileMode) { setResolvedAddress(''); return; }
    if (unitAddress) { setResolvedAddress(unitAddress); return; }
    if (!unitId) { setResolvedAddress(''); return; }
    let cancelled = false;
    supabase.from('units').select('address, unit_number').eq('id', unitId).maybeSingle()
      .then(({ data }) => { if (!cancelled) setResolvedAddress(data?.address || data?.unit_number || ''); });
    return () => { cancelled = true; };
  }, [residentFileMode, unitId, unitAddress]);

  const residentFolderName = resolvedAddress || unitAddress || unitNumber || unitId;
  const residentFolder = residentFolderName ? `Resident Files/${residentFolderName}` : 'Resident Files';

  const [formData, setFormData] = useState({
    name: defaultName,
    description: '',
    clientId: defaultClientId,
    category: residentFileMode ? residentFolder : 'general'
  });

  useEffect(() => {
    if (open) {
      setFormData({
        name: defaultName || 'Untitled Document',
        description: '',
        clientId: defaultClientId,
        category: residentFileMode ? residentFolder : 'general'
      });
      setSaveToDrive(false);
      setDriveFolder(null);

      try {
        const stored = localStorage.getItem('doc_custom_folders');
        const customFolders = stored ? JSON.parse(stored) : [];
        setFolders([...new Set([...DEFAULT_FOLDERS, ...customFolders])].sort());
      } catch {
        setFolders(DEFAULT_FOLDERS);
      }

      fetchOptions();
    }
  }, [open, defaultName, defaultClientId, residentFileMode, residentFolder]);

  const fetchOptions = async () => {
    try {
      const { data, error } = await supabase
        .from('associations')
        .select('id, name')
        .eq('status', 'active')
        .order('name');

      if (error) {
        console.error('Error fetching associations for dialog:', error);
        return;
      }

      if (data) setClients(data);
    } catch (err) {
      console.error('Error fetching options for dialog:', err);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!formData.name || !formData.clientId) return;
    
    setLoading(true);
    try {
      const result = await onSave({
        name: formData.name,
        description: formData.description,
        clientId: formData.clientId,
        category: formData.category
      });

      if (saveToDrive) {
        if (!drive.isConnected) throw new Error('Connect Google Drive before saving there.');
        const pdfBlob = result instanceof Blob ? result : result?.blob;
        if (!pdfBlob) throw new Error('This file was saved locally, but could not be sent to Google Drive.');
        const fileName = `${formData.name.replace(/[^a-zA-Z0-9._ -]+/g, '_').trim() || 'Document'}.pdf`;
        const driveFile = new File([pdfBlob], fileName, { type: 'application/pdf' });
        const uploadResult = await drive.uploadFile(driveFile, driveFolder?.id || undefined);
        if (!uploadResult.success) throw new Error('Document saved locally, but Google Drive upload failed.');
      }
      onOpenChange(false);
    } catch (err) {
      console.error('Save to documents failed:', err);
      sonnerToast.error('Save to Documents failed', {
        description: err?.message || 'Please try again.',
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>{residentFileMode ? 'Save to Resident File' : 'Save to Documents'}</DialogTitle>
          <DialogDescription>
            {residentFileMode
              ? `This document will be saved under "Resident Files / ${residentFolderName || '(no unit)'}" inside the selected association.`
              : 'Save this PDF into the document library and optionally place it in a folder.'}
          </DialogDescription>
        </DialogHeader>
        
        <form onSubmit={handleSubmit} className="space-y-4 py-4">
          <div className="space-y-2">
            <Label htmlFor="doc-client">Association <span className="text-destructive">*</span></Label>
            <Select 
              value={formData.clientId} 
              onValueChange={(val) => setFormData(prev => ({ ...prev, clientId: val }))}
              required
            >
              <SelectTrigger id="doc-client" className="bg-background">
                <SelectValue placeholder="Select Association..." />
              </SelectTrigger>
              <SelectContent>
                {clients.map(c => (
                  <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label htmlFor="doc-folder">Folder {residentFileMode ? '' : '(Optional)'}</Label>
            {residentFileMode ? (
              <Input
                id="doc-folder"
                value={residentFolder}
                disabled
                className="bg-muted text-muted-foreground"
              />
            ) : (
              <Select 
                value={formData.category} 
                onValueChange={(val) => setFormData(prev => ({ ...prev, category: val }))}
              >
                <SelectTrigger id="doc-folder" className="bg-background">
                  <SelectValue placeholder="Select Folder..." />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="general">No Folder (Root Level)</SelectItem>
                  {folders.map(folder => (
                    <SelectItem key={folder} value={folder}>{folder}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            )}
          </div>

          <div className="space-y-2">
            <Label htmlFor="doc-name">Document Name <span className="text-destructive">*</span></Label>
            <Input 
              id="doc-name" 
              value={formData.name} 
              onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
              placeholder="e.g. Official Notice"
              required
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="doc-desc">Description (Optional)</Label>
            <Textarea 
              id="doc-desc" 
              value={formData.description} 
              onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
              placeholder="Brief description of this document..."
              rows={3}
            />
          </div>

          <div className="rounded-md border border-border p-3 space-y-2">
            <div className="flex items-center justify-between gap-3">
              <div className="min-w-0">
                <Label className="text-xs font-medium flex items-center gap-2">
                  <HardDrive className="h-4 w-4 text-primary" /> Save to Google Drive
                </Label>
                <p className="text-xs text-muted-foreground truncate">
                  {driveFolder?.name || 'Choose a Drive folder for this PDF.'}
                </p>
              </div>
              <Button type="button" variant="outline" size="sm" onClick={() => { setSaveToDrive(true); setDrivePickerOpen(true); }} disabled={!drive.isConnected || loading}>
                Choose
              </Button>
            </div>
            {!drive.isConnected && <p className="text-xs text-muted-foreground">Connect Google Drive from Documents before saving files there.</p>}
            {driveFolder && (
              <Button type="button" variant="ghost" size="sm" className="h-7 px-2" onClick={() => { setSaveToDrive(false); setDriveFolder(null); }}>
                Remove Google Drive save
              </Button>
            )}
          </div>

          <DialogFooter className="pt-4">
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={loading}>
              Cancel
            </Button>
            <Button type="submit" disabled={loading || !formData.clientId || !formData.name}>
              {loading && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
              Save Document
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>

      <GoogleDriveFolderPickerDialog
        open={drivePickerOpen}
        onOpenChange={setDrivePickerOpen}
        driveFiles={drive.driveFiles}
        browsing={drive.browsing}
        browseFiles={drive.browseFiles}
        listSharedDrives={drive.listSharedDrives}
        onSelect={(selected) => { setDriveFolder(selected); setSaveToDrive(true); }}
      />
    </Dialog>
  );
}

export default SaveToDocumentsDialog;
