import { useState, useEffect } from 'react';
import {
    ChevronLeft,
    Upload,
    Clock,
    RefreshCw,
    File,
    CreditCard,
    Building,
    Landmark,
    CheckCircle2,
    Check,
    Info,
    User,
    MapPin
} from 'lucide-react';
import { toast } from 'sonner';
import { API } from '@/api/API';
import * as SelectPrimitive from '@radix-ui/react-select';
import { cn } from '@/components/ui/utils';
import { Select, SelectContent, SelectTrigger, SelectValue } from '@/components/ui/select';

interface Props {
    id: string;
    onBack: () => void;
}

export function ProspectiveApplicationDetails({ id, onBack }: Props) {
    const requiredDocumentTypes = [
        'PAN Card',
        'GST Certificate',
        'Aadhaar Card',
        'Security Deposit Receipt',
        'First Fill Receipt',
        'Partnership Deed',
        'LLP Agreement',
        'Certificate of Incorporation',
        'MOA',
        'AOA',
        'Firm Registration',
        'Rental Agreement',
        'Property Documents',
        'Nodal Agreement',
        'Cancelled Check',
        'LOI Acknowledgement',
        'Architecture Blueprint',
        'Site Plan',
        'Other'
    ];
    const [details, setDetails] = useState<any>(null);
    const [loading, setLoading] = useState(true);
    const [documents, setDocuments] = useState<any[]>([]);
    const [selectedDocType, setSelectedDocType] = useState('');
    const [file, setFile] = useState<File | null>(null);
    const [isUploading, setIsUploading] = useState(false);
    const [isSaving, setIsSaving] = useState(false);



    // Statutory & Bank State
    const emptyForm = {
        panNumber: '',
        gstNumber: '',
        registeredAddress: '',
        bankName: '',
        accountNumber: '',
        ifscCode: '',
        branchName: '',
        accountHolderName: ''
    };
    const [form, setForm] = useState(emptyForm);
    const [savedForm, setSavedForm] = useState(emptyForm);
    const isFormDirty = JSON.stringify(form) !== JSON.stringify(savedForm);
    const uploadedDocumentTypes = new Set(
        documents.map((doc) => String(doc.documentType || '').trim().toLowerCase())
    );
    const selectedDocAlreadyUploaded = selectedDocType
        ? uploadedDocumentTypes.has(selectedDocType.toLowerCase())
        : false;

    useEffect(() => {
        fetchData();
    }, [id]);

    const fetchData = async () => {
        setLoading(true);
        try {
            const [detailsRes, docsRes]: [any, any] = await Promise.all([
                API.getApplicationById(id),
                API.getDocuments(id)
            ]);
            
            if (detailsRes.data?.success) {
                const data = detailsRes.data.data;
                const nextForm = {
                    panNumber: data.panNumber || '',
                    gstNumber: data.gstNumber || '',
                    registeredAddress: data.registeredAddress || data.address || '',
                    bankName: data.bankName || '',
                    accountNumber: data.accountNumber || '',
                    ifscCode: data.ifscCode || '',
                    branchName: data.branchName || '',
                    accountHolderName: data.accountHolderName || data.applicantName || ''
                };
                setDetails(data);
                setForm(nextForm);
                setSavedForm(nextForm);
            }
            if (docsRes.data?.success || docsRes.ok) {
                setDocuments(docsRes.data.data || []);
            }
        } catch (error) {
            console.error('Failed to fetch details:', error);
            toast.error('Failed to load application details');
        } finally {
            setLoading(false);
        }
    };

    const handleSaveDetails = async () => {
        setIsSaving(true);
        try {
            console.log('Saving business details for:', id, form);
            const response: any = await API.updateApplication(id, form);
            
            if (response.ok) {
                toast.success('Business details saved successfully');
                await fetchData();
            } else {
                const errorMsg = response.data?.message || 'Failed to update business details';
                toast.error(errorMsg);
                console.error('Update failed:', response);
            }
        } catch (error: any) {
            console.error('Save details fatal error:', error);
            toast.error(error.message || 'A network error occurred while saving');
        } finally {
            setIsSaving(false);
        }
    };

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files && e.target.files[0]) {
            setFile(e.target.files[0]);
        }
    };

    const handleUpload = async () => {
        if (!file || !selectedDocType) {
            toast.error('Please select a document type and file');
            return;
        }

        const formData = new FormData();
        formData.append('file', file);
        formData.append('documentType', selectedDocType);

        setIsUploading(true);
        try {
            const response: any = await API.uploadDocument(id, formData);
            if (response.data?.success || response.ok) {
                toast.success('Document uploaded successfully');
                setFile(null);
                setSelectedDocType('');
                const fileInput = document.getElementById('file-upload') as HTMLInputElement;
                if (fileInput) fileInput.value = '';
                // Refresh documents
                const docsRes: any = await API.getDocuments(id);
                if (docsRes.data?.success || docsRes.ok) {
                    setDocuments(docsRes.data.data || []);
                }
            } else {
                toast.error(response.data?.message || 'Upload failed');
            }
        } catch (error) {
            console.error('Upload error:', error);
            toast.error('Upload failed');
        } finally {
            setIsUploading(false);
        }
    };

    if (loading) {
        return (
            <div className="flex items-center justify-center py-20">
                <RefreshCw className="w-8 h-8 animate-spin text-re-red" />
            </div>
        );
    }

    if (!details) {
        return (
            <div className="bg-white rounded-xl border border-slate-200 p-8 text-center">
                <p className="text-slate-600 mb-4">Application details not found.</p>
                <button onClick={onBack} className="bg-re-red text-white px-4 py-2 rounded-md hover:bg-re-red-hover">Go Back</button>
            </div>
        );
    }

    return (
        <div className="space-y-6">
            <div className="flex items-center justify-between mb-4">
                <div className="flex items-center">
                    <button
                        onClick={onBack}
                        className="mr-3 p-1.5 rounded-full hover:bg-slate-200 text-slate-600 transition-colors"
                        data-testid="onboarding-prospective-details-back-btn"
                    >
                        <ChevronLeft className="w-5 h-5" />
                    </button>
                    <div>
                        <h1 className="text-slate-900 text-2xl font-bold mb-1">Application Details</h1>
                        <div className="flex items-center gap-2">
                            <p className="text-slate-600 font-medium" data-testid="onboarding-prospective-details-app-id">
                                {details.applicationId || 'Loading...'}
                            </p>
                            {details.districtId ? (
                                <span className="text-[10px] bg-green-100 text-green-700 font-bold px-1.5 py-0.5 rounded uppercase tracking-wider" data-testid="onboarding-prospective-details-type-badge">Opportunity</span>
                            ) : (
                                <span className="text-[10px] bg-blue-100 text-blue-700 font-bold px-1.5 py-0.5 rounded uppercase tracking-wider" data-testid="onboarding-prospective-details-type-badge">Future Reference</span>
                            )}
                        </div>
                    </div>
                </div>
            </div>

            <div className="animate-in fade-in duration-500 space-y-6">
                {/* Status & Tracking Summary Card */}
                <div className="bg-white rounded-xl border border-slate-200 shadow-sm p-6" data-testid="onboarding-prospective-details-summary-card">
                    <div className="mb-4 border-b pb-2">
                        <h4 className="text-lg font-semibold text-slate-900 flex items-center gap-2">
                            <Info className="w-5 h-5 text-re-red" /> Application Summary
                        </h4>
                    </div>
                    
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div className="space-y-4">
                            <div className="flex items-start gap-3" data-testid="onboarding-prospective-details-applicant-info">
                                <div className="p-2 bg-blue-50 rounded-lg">
                                    <User className="w-4 h-4 text-blue-600" />
                                </div>
                                <div>
                                    <p className="text-[10px] text-slate-500 uppercase font-bold">Applicant</p>
                                    <p className="text-sm font-semibold text-slate-900" data-testid="onboarding-prospective-details-name">{details.applicantName}</p>
                                    <p className="text-xs text-slate-600">{details.email} | {details.phone}</p>
                                </div>
                            </div>
                            <div className="flex items-start gap-3" data-testid="onboarding-prospective-details-location-info">
                                <div className="p-2 bg-red-50 rounded-lg">
                                    <MapPin className="w-4 h-4 text-re-red" />
                                </div>
                                <div>
                                    <p className="text-[10px] text-slate-500 uppercase font-bold">Proposed Location</p>
                                    <p className="text-sm font-semibold text-slate-900">{details.city}, {details.state}</p>
                                    <p className="text-xs text-slate-600">{details.preferredLocation || 'Standard Area'}</p>
                                </div>
                            </div>
                        </div>

                        <div className="space-y-4">
                            <div className="flex items-start gap-3" data-testid="onboarding-prospective-details-concept-info">
                                <div className="p-2 bg-green-50 rounded-lg">
                                    <Building className="w-4 h-4 text-green-600" />
                                </div>
                                <div>
                                    <p className="text-[10px] text-slate-500 uppercase font-bold">Business Concept</p>
                                    <p className="text-sm font-semibold text-slate-900">{details.businessType} - {details.constitutionType}</p>
                                    <p className="text-xs text-slate-600">Investment: {details.investmentCapacity}</p>
                                </div>
                            </div>
                            <div className="flex items-start gap-3" data-testid="onboarding-prospective-details-date-info">
                                <div className="p-2 bg-slate-50 rounded-lg">
                                    <Clock className="w-4 h-4 text-slate-600" />
                                </div>
                                <div>
                                    <p className="text-[10px] text-slate-500 uppercase font-bold">Applied On</p>
                                    <p className="text-sm font-semibold text-slate-900">
                                        {details.createdAt ? new Date(details.createdAt).toLocaleDateString('en-IN', { day: 'numeric', month: 'long', year: 'numeric' }) : '-'}
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    <div className="lg:col-span-3 space-y-6">
                        {/* Statutory & Bank Details Form */}
                        <div className="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden" data-testid="onboarding-prospective-details-statutory-card">
                            <div className="p-4 bg-slate-900 text-white flex justify-between items-center">
                                <h4 className="flex items-center gap-2 text-sm font-bold uppercase tracking-widest">
                                    <CreditCard className="w-4 h-4 text-re-red" /> Statutory & Bank Details
                                </h4>
                                <button
                                    onClick={handleSaveDetails}
                                    disabled={isSaving}
                                    className={`text-xs text-white px-3 py-1 rounded font-bold transition-all flex items-center gap-1 disabled:opacity-50 ${isFormDirty ? 'bg-emerald-600 hover:bg-emerald-700 ring-2 ring-emerald-300 animate-pulse' : 'bg-re-red hover:bg-re-red-hover'}`}
                                    data-testid="onboarding-prospective-details-save-statutory-btn"
                                >
                                    {isSaving ? <RefreshCw className="w-3 h-3 animate-spin" /> : <CheckCircle2 className="w-3 h-3" />}
                                    Save Business Info
                                </button>
                            </div>
                            <div className="p-6">
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-4">
                                    <div className="space-y-1">
                                        <label className="text-[10px] font-bold text-slate-500 uppercase">Registered Business Name</label>
                                        <input
                                            type="text"
                                            className="w-full rounded-md border border-slate-200 bg-white px-3 py-2 text-sm focus:ring-2 focus:ring-re-red outline-none transition-all"
                                            value={form.accountHolderName}
                                            onChange={(e) => setForm({ ...form, accountHolderName: e.target.value })}
                                            placeholder="As per legal documents"
                                            data-testid="onboarding-prospective-details-input-biz-name"
                                        />
                                    </div>
                                    <div className="space-y-1">
                                        <label className="text-[10px] font-bold text-slate-500 uppercase">Permanent Account Number (PAN)</label>
                                        <input
                                            type="text"
                                            className="w-full rounded-md border border-slate-200 bg-white px-3 py-2 text-sm focus:ring-2 focus:ring-re-red outline-none transition-all uppercase"
                                            value={form.panNumber}
                                            onChange={(e) => setForm({ ...form, panNumber: e.target.value.toUpperCase() })}
                                            placeholder="ABCDE1234F"
                                            maxLength={10}
                                            data-testid="onboarding-prospective-details-input-pan"
                                        />
                                    </div>
                                    <div className="space-y-1">
                                        <label className="text-[10px] font-bold text-slate-500 uppercase">GST Identification Number (GSTIN)</label>
                                        <input
                                            type="text"
                                            className="w-full rounded-md border border-slate-200 bg-white px-3 py-2 text-sm focus:ring-2 focus:ring-re-red outline-none transition-all uppercase"
                                            value={form.gstNumber}
                                            onChange={(e) => setForm({ ...form, gstNumber: e.target.value.toUpperCase() })}
                                            placeholder="27ABCDE1234F1Z5"
                                            maxLength={15}
                                            data-testid="onboarding-prospective-details-input-gst"
                                        />
                                    </div>
                                    <div className="space-y-1">
                                        <label className="text-[10px] font-bold text-slate-500 uppercase">Registered Office Address</label>
                                        <textarea
                                            rows={1}
                                            className="w-full rounded-md border border-slate-200 bg-white px-3 py-2 text-sm focus:ring-2 focus:ring-re-red outline-none transition-all"
                                            value={form.registeredAddress}
                                            onChange={(e) => setForm({ ...form, registeredAddress: e.target.value })}
                                            placeholder="Full legal address"
                                            data-testid="onboarding-prospective-details-input-address"
                                        />
                                    </div>

                                    <div className="md:col-span-2 border-t pt-2 mt-2">
                                        <h5 className="text-xs font-black text-slate-900 uppercase flex items-center gap-2 mb-3">
                                            <Landmark className="w-3.5 h-3.5 text-blue-600" /> Primary Bank Information
                                        </h5>
                                    </div>

                                    <div className="space-y-1">
                                        <label className="text-[10px] font-bold text-slate-500 uppercase">Bank Name</label>
                                        <input
                                            type="text"
                                            className="w-full rounded-md border border-slate-200 bg-white px-3 py-2 text-sm focus:ring-2 focus:ring-re-red outline-none transition-all"
                                            value={form.bankName}
                                            onChange={(e) => setForm({ ...form, bankName: e.target.value })}
                                            placeholder="e.g. HDFC Bank"
                                            data-testid="onboarding-prospective-details-input-bank"
                                        />
                                    </div>
                                    <div className="space-y-1">
                                        <label className="text-[10px] font-bold text-slate-500 uppercase">Account Number</label>
                                        <input
                                            type="text"
                                            className="w-full rounded-md border border-slate-200 bg-white px-3 py-2 text-sm focus:ring-2 focus:ring-re-red outline-none transition-all"
                                            value={form.accountNumber}
                                            onChange={(e) => setForm({ ...form, accountNumber: e.target.value })}
                                            placeholder="Bank account number"
                                            data-testid="onboarding-prospective-details-input-acc-num"
                                        />
                                    </div>
                                    <div className="space-y-1">
                                        <label className="text-[10px] font-bold text-slate-500 uppercase">IFSC Code</label>
                                        <input
                                            type="text"
                                            className="w-full rounded-md border border-slate-200 bg-white px-3 py-2 text-sm focus:ring-2 focus:ring-re-red outline-none transition-all uppercase"
                                            value={form.ifscCode}
                                            onChange={(e) => setForm({ ...form, ifscCode: e.target.value.toUpperCase() })}
                                            placeholder="HDFC0001234"
                                            maxLength={11}
                                            data-testid="onboarding-prospective-details-input-ifsc"
                                        />
                                    </div>
                                    <div className="space-y-1">
                                        <label className="text-[10px] font-bold text-slate-500 uppercase">Branch Name</label>
                                        <input
                                            type="text"
                                            className="w-full rounded-md border border-slate-200 bg-white px-3 py-2 text-sm focus:ring-2 focus:ring-re-red outline-none transition-all"
                                            value={form.branchName}
                                            onChange={(e) => setForm({ ...form, branchName: e.target.value })}
                                            placeholder="e.g. South Mumbai"
                                            data-testid="onboarding-prospective-details-input-branch"
                                        />
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* Document Upload Card */}
                        <div className="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden" data-testid="onboarding-prospective-details-upload-card">
                            <div className="p-4 border-b border-slate-200 bg-slate-50 flex justify-between items-center">
                                <h4 className="flex items-center gap-2 text-sm font-bold uppercase tracking-widest text-slate-900">
                                    <Upload className="w-4 h-4 text-re-red" /> Required Documents
                                </h4>
                            </div>
                            <div className="p-6 space-y-6">
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 p-4 bg-slate-50 rounded-lg border border-slate-100">
                                    <div className="space-y-1">
                                        <div className="flex items-center justify-between gap-2">
                                            <label className="text-[10px] font-bold text-slate-500 uppercase">Document Category</label>
                                            {selectedDocType && (
                                                <span className="rounded-full bg-red-50 px-2 py-0.5 text-[10px] font-bold text-re-red">
                                                    {selectedDocAlreadyUploaded ? 'Already uploaded' : 'Pending upload'}
                                                </span>
                                            )}
                                        </div>
                                        <div className="relative">
                                            <CheckCircle2 className={`pointer-events-none absolute left-3 top-1/2 z-10 h-4 w-4 -translate-y-1/2 ${selectedDocAlreadyUploaded ? 'text-green-600' : 'text-slate-300'}`} />
                                            <Select value={selectedDocType} onValueChange={setSelectedDocType} disabled={isUploading}>
                                                <SelectTrigger className="h-12 rounded-xl border-slate-200 bg-gradient-to-r from-white to-slate-50 pl-10 pr-3 text-sm font-medium text-slate-700 shadow-sm focus:border-re-red/40 focus:ring-2 focus:ring-re-red" data-testid="onboarding-prospective-details-doc-type-select">
                                                    <SelectValue placeholder="Choose document type" />
                                                </SelectTrigger>
                                                <SelectContent className="rounded-xl border-slate-200 shadow-lg" data-testid="onboarding-prospective-details-doc-type-content">
                                                    {requiredDocumentTypes.map((docType) => {
                                                        const isUploaded = uploadedDocumentTypes.has(docType.toLowerCase());
                                                        return (
                                                            <SelectPrimitive.Item
                                                                key={docType}
                                                                value={docType}
                                                                textValue={docType}
                                                                className={cn(
                                                                    'relative flex w-full cursor-default select-none items-center gap-2 rounded-lg py-2 pl-2 pr-8 text-sm text-slate-700 outline-none',
                                                                    'focus:bg-red-50 focus:text-slate-900 data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
                                                                )}
                                                                data-testid={`onboarding-prospective-details-doc-type-item-${docType.replace(/\s+/g, '-').toLowerCase()}`}
                                                            >
                                                                <span className="absolute right-2 flex size-3.5 items-center justify-center">
                                                                    <SelectPrimitive.ItemIndicator>
                                                                        <Check className="size-4" />
                                                                    </SelectPrimitive.ItemIndicator>
                                                                </span>
                                                                <div className="flex min-w-0 flex-1 items-center gap-2">
                                                                    <CheckCircle2
                                                                        className={cn(
                                                                            'h-4 w-4 shrink-0',
                                                                            isUploaded ? 'text-green-600' : 'text-slate-300',
                                                                        )}
                                                                        aria-hidden
                                                                    />
                                                                    <SelectPrimitive.ItemText>{docType}</SelectPrimitive.ItemText>
                                                                </div>
                                                            </SelectPrimitive.Item>
                                                        );
                                                    })}
                                                </SelectContent>
                                            </Select>
                                        </div>
                                    </div>
                                    <div className="space-y-1">
                                        <label className="text-[10px] font-bold text-slate-500 uppercase">Select File</label>
                                        <input
                                            type="file"
                                            id="file-upload"
                                            className="w-full text-xs text-slate-600 file:mr-4 file:py-1 file:px-4 file:rounded-full file:border-0 file:text-xs file:font-semibold file:bg-red-50 file:text-re-red hover:file:bg-red-100"
                                            onChange={handleFileChange}
                                            disabled={isUploading}
                                            data-testid="onboarding-prospective-details-file-input"
                                        />
                                    </div>
                                    <div className="md:col-span-2 flex justify-end">
                                        <button
                                            onClick={handleUpload}
                                            disabled={!file || !selectedDocType || isUploading}
                                            className="bg-re-red text-white px-5 py-2 rounded-md hover:bg-re-red-hover disabled:opacity-50 text-xs font-bold transition-all shadow-sm flex items-center gap-2"
                                            data-testid="onboarding-prospective-details-upload-btn"
                                        >
                                            {isUploading ? <RefreshCw className="w-3.5 h-3.5 animate-spin" /> : <Upload className="w-3.5 h-3.5" />}
                                            Upload Document
                                        </button>
                                    </div>
                                </div>

                                <div className="space-y-4">
                                    <div className="flex items-center gap-2 text-slate-900 border-b pb-1">
                                        <File className="w-4 h-4 text-blue-600" />
                                        <h3 className="text-xs font-black uppercase tracking-tighter">Uploaded Library ({documents.length})</h3>
                                    </div>
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-3" data-testid="onboarding-prospective-details-doc-library">
                                        {documents.length > 0 ? documents.map((doc, idx) => (
                                            <div key={doc.id} className="flex justify-between items-center p-3 border border-slate-100 rounded-xl bg-slate-50 group hover:border-red-200 transition-all" data-testid={`onboarding-prospective-details-doc-item-${idx}`}>
                                                <div className="flex items-center gap-3">
                                                    <div className="w-8 h-8 rounded bg-white flex items-center justify-center border border-slate-200 group-hover:bg-blue-50">
                                                        <File className="w-4 h-4 text-slate-400 group-hover:text-blue-600" />
                                                    </div>
                                                    <div>
                                                        <p className="text-[11px] font-bold text-slate-900" data-testid={`onboarding-prospective-details-doc-type-${idx}`}>{doc.documentType}</p>
                                                        <p className="text-[10px] text-slate-400 truncate w-32">{doc.fileName}</p>
                                                    </div>
                                                </div>
                                                <span className={`text-[9px] px-2 py-0.5 rounded-full font-black uppercase tracking-tighter ${doc.status === 'Approved' ? 'bg-green-100 text-green-700' : 'bg-red-50 text-re-red'}`} data-testid={`onboarding-prospective-details-doc-status-${idx}`}>
                                                    {doc.status || 'Pending'}
                                                </span>
                                            </div>
                                        )) : (
                                            <div className="col-span-2 py-8 text-center bg-slate-50 rounded-xl border border-dashed border-slate-200" data-testid="onboarding-prospective-details-doc-empty">
                                                <Info className="w-6 h-6 text-slate-300 mx-auto mb-2" />
                                                <p className="text-xs text-slate-500 font-medium">No documents in your library yet</p>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>


                </div>
            </div>
        </div>
    );
}
